Microsoft Technology, .Net, BizTalk, Sharepoint & etc.

Liedong(Ken) Zheng, Senior SharePoint Developer at SIMPLOT

Archive for September, 2008

SharePoint Search Scopes don’t appear in drop-down list

Posted by ken zheng on September 30, 2008

The “All Sites” and “People” search make use of the Search Center capabilities in MOSS. It appears that you do not have a Search Center created, or the URL for the Search Center is not correct.

a) Create a Search Center Site
b) Associate the Site Collection Search settings with that Search Center
You can get to this by clicking on Search Settings under the Site Collection Administration section. When you select Custom Scope, you need to provide a URL to the search center.

Once you have the site create you will just select People Search Webpart

Edit -> Modify Shared WebPart and in the Miscellaneous section change the
Target search results page URL to /sites/SearchCenter/results.aspx.
If you use People search in the dropdownlist. You will need to change the scope by SharedSerivce Provider (SharedServices1 > Search Settings > Scopes > Scope Properties and Rules )

Posted in Sharepoint | Tagged: , | 1 Comment »

Build Webpart WSP and install the feature

Posted by ken zheng on September 30, 2008

Once you have tested your webpart. Just right click your project and select WSPBuilder ->Build WSP. It will generate a WSP file you. You can use SharePoint Solution Installer to install the wsp by just dropping your WSP in the Installer folder and modify the config file to your wsp file name. All done.


SharePoint SmartTemplates for Visual Studio

WSPBuilder

SharePoint Solution Installer

Posted in Sharepoint | Tagged: , , | Leave a Comment »

Create a Ajax WebPart for SharePoint

Posted by ken zheng on September 30, 2008

Today, I followed Abdulla’s example to create a Ajax Webpart. It works very well. One thing really struggle me is I add Web Extenstion 3.5 instead of 1.06.

First of all you need to add
· System.Web
· System.Web.Extensions (v1.06)
· System.Web.Extensions.Design (v1.06)
. Syste.Data

Modify the SharePoint Web.Config file. http://msdn.microsoft.com/en-us/library/bb861898.aspx
The below is the c# code

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using System.Data;
using System.Data.SqlClient;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
using System.ComponentModel;

namespace SharePointAjaxWebPart
{
    [Guid("579e8377-d57c-4b5e-98c1-1001c20301cc")]
    public class MyAjaxWebPart : System.Web.UI.WebControls.WebParts.WebPart
    {

    private GridView _grdSearch;
    private TextBox _txtSearch;
    private Button _btnSearch;
    private Label _lblMsg;
    private UpdatePanel _updatePanel;
    private UpdateProgress _updateProgress;
    private static readonly object EventSubmitKey = new object();

    public MyAjaxWebPart()
    {
        this.ExportMode = WebPartExportMode.All;
    }

    [WebBrowsable(true), Personalizable(PersonalizationScope.Shared), Category("AbdHaq Property")]
    public string LoadingImageURL {
        get {
            object _obj = ViewState["LoadingImageURL"];
            if (_obj == null) {
                return string.Empty;
            }
            else {
                return (string)ViewState["LoadingImageURL"];
            }

        }
        set { ViewState["LoadingImageURL"] = value; }
    }
    public event EventHandler Submit {
        add { Events.AddHandler(EventSubmitKey, value); }
        remove { Events.RemoveHandler(EventSubmitKey, value); }
    }

    private void _btnSearch_Click(object source, EventArgs e)
    {

        _grdSearch.Visible = false;

        System.Threading.Thread.Sleep(1500);

        ////Create DataTable Structure
        DataTable Dtable = new DataTable("tmpTable");
        ////User_ID Col
        Dtable.Columns.Add("User_ID", typeof(int));
        Dtable.Columns["User_ID"].AutoIncrement = true;
        Dtable.Columns["User_ID"].AutoIncrementSeed = 1;
        ////User_Name Col
        Dtable.Columns.Add("User_Name", typeof(string));
        ////User_Department Col
        Dtable.Columns.Add("User_Department", typeof(string));

        DataRow dr = default(DataRow);

        dr = Dtable.NewRow();
        dr["User_Name"] = "Abdulla Abdelhaq";
        dr["User_Department"] = "Technical";
        Dtable.Rows.Add(dr);

        dr = Dtable.NewRow();
        dr["User_Name"] = "Noura Ahmad";
        dr["User_Department"] = "Technical";
        Dtable.Rows.Add(dr);

        dr = Dtable.NewRow();
        dr["User_Name"] = "Oday Mohammad";
        dr["User_Department"] = "Production";
        Dtable.Rows.Add(dr);

        string _searchFor = "%";

        if (_txtSearch.Text != string.Empty) {
            _searchFor = _txtSearch.Text;
        }

        DataView dtView = new DataView(Dtable);
        dtView.RowFilter = "User_Name LIKE '%'+'" + _searchFor + "'+'%'";

        if (dtView.Count > 0) {
            _grdSearch.Visible = true;
            _grdSearch.AutoGenerateColumns = true;
            _grdSearch.DataSource = dtView;
            _grdSearch.DataBind();
            _lblMsg.Text = string.Empty;
        }
        else {
            _lblMsg.Text = "<font color='red'>Sorry, No Data Found!.</font>";
            _grdSearch.Visible = false;
        }

    }

    protected override void CreateChildControls()
    {
        Controls.Clear();

        _updatePanel = new UpdatePanel();
        {
            _updatePanel.ID = "UpdatePanel1";
            _updatePanel.ChildrenAsTriggers = true;
            _updatePanel.UpdateMode = UpdatePanelUpdateMode.Conditional;
        }

        _updateProgress = new UpdateProgress();
        _updateProgress.ID = "UpdateProgress1";

        string _templateHTML = null;
        if (LoadingImageURL == string.Empty) {
            _templateHTML = "<span>Loading ...</span>";
        }
        else {
            _templateHTML = "<div><img alt='Loading...' src='" + LoadingImageURL.Trim() + "'/></div>";
        }

        _updateProgress.ProgressTemplate = new ProgressTemplate(_templateHTML);

        _updateProgress.AssociatedUpdatePanelID = _updatePanel.ClientID;

        this.Controls.Add(_updatePanel);

        _grdSearch = new GridView();
        _grdSearch.ID = "GrdSearch";

        _txtSearch = new TextBox();
        _txtSearch.ID = "txtSearch";

        _btnSearch = new Button();
        _btnSearch.Text = "Search";
        _btnSearch.ID = "BtnSearch";

        _lblMsg = new Label();
        _lblMsg.ID = "lblMsgError";

        _btnSearch.Click += _btnSearch_Click;

        _updatePanel.ContentTemplateContainer.Controls.Add(_txtSearch);
        _updatePanel.ContentTemplateContainer.Controls.Add(_btnSearch);
        _updatePanel.ContentTemplateContainer.Controls.Add(_grdSearch);
        _updatePanel.ContentTemplateContainer.Controls.Add(_lblMsg);
        _updatePanel.ContentTemplateContainer.Controls.Add(_updateProgress);

    }

    protected override void OnInit(EventArgs e)
    {

        base.OnInit(e);

        //get the existing ScriptManager if it exists on the page
        ScriptManager _AjaxManager = ScriptManager.GetCurrent(this.Page);
        if (_AjaxManager == null) {

            //create new ScriptManager and EnablePartialRendering
            _AjaxManager = new ScriptManager();
            _AjaxManager.EnablePartialRendering = true;

            //Fix problem with postbacks and form actions (DevDiv 55525)
            Page.ClientScript.RegisterStartupScript(this.GetType(), this.ID, "_spOriginalFormAction = document.forms[0].action;", true);

            //tag:"form" att:"onsubmit" val:"return _spFormOnSubmitWrapper()"
            //blocks async postbacks after the first one
            //not calling "_spFormOnSubmitWrapper()" breaks all postbacks
            //returning true all the time, somewhat defeats the purpose of the
            //_spFormOnSubmitWrapper() which is to block repetitive postbacks,
            //but it allows MS AJAX Extensions to work properly

            if ((this.Page.Form != null)) {
                string formOnSubmitAtt = this.Page.Form.Attributes["onsubmit"];
                if (!string.IsNullOrEmpty(formOnSubmitAtt) & formOnSubmitAtt == "return _spFormOnSubmitWrapper();") {
                    this.Page.Form.Attributes["onsubmit"] = "_spFormOnSubmitWrapper();";
                }
                //add the ScriptManager as the first control in the Page.Form
                this.Page.Form.Controls.AddAt(0, _AjaxManager);

            }
        }

    }

    protected override void RenderContents(System.Web.UI.HtmlTextWriter writer)
    {
        _updatePanel.RenderControl(writer);
    }
}
//Class for Building progress tempales
public class ProgressTemplate : ITemplate
{
    private string template;

    public ProgressTemplate(string temp)
    {
        template = temp;
    }

    public void InstantiateIn(Control container)
    {
        LiteralControl ltr = new LiteralControl(this.template);
        container.Controls.Add(ltr);
    }

}

}

The full tutorial is here

Posted in Sharepoint | Tagged: , | 2 Comments »

More Details about “An unexpected error has occurred” in WSS v3

Posted by ken zheng on September 30, 2008

Debugging SharePoint can be problematic at times, it does like to hide debugging information from you. The bain of my life recently has been “An unexpected error has occurred” with nothing written to log files, trace or the event log.

Normally I can debug the problem with a little commenting & narrowing down of the problem, but today I have managed to get rid of that error screen completely.

The solution is to change a single entry in web.config, by modifying the line…

<SafeMode MaxControls=“200“ CallStack=“false“…

to…

<SafeMode MaxControls=“200“ CallStack=“true“…

You will also need to set custom errors to ‘Off’ .

You will no longer see the “An unexpected error has occurred” error page and instead you get a lovely ’standard ASP.Net error page’ with the stack trace and everything…development has got that little bit easier!!

Here is a good article for debugging in SharePoint

http://blog.thekid.me.uk/archive/2007/07/25/debugging-tips-for-sharepoint-and-wss-exceptions.aspx

Posted in Uncategorized | Tagged: | Leave a Comment »

Easily get to the WebPart Maintenance page for any Sharepoint Site Url

Posted by ken zheng on September 29, 2008

Symptom:

Often times, developers in WSS3.0/MOSS2007 probably run across the issue where a web part is dropped on to a page
and then Sharepoint errors out for one reason or the other. Sometimes, the user is directed to a Web Part Maintenance page,
which helps the developer remove the offending web part from the page.

However, there is no way to get to this page from any easily available link.

Resolution:

In order to get to the Web Part Maintenance page for ANY sharepoint url, try the following trick.

Append the querystring ?contents=1 to the url in the browser as shown below
http://portal/area/default.aspx?contents=1

Posted in Sharepoint | Tagged: , , | Leave a Comment »

Packaging a WCF Service as a SharePoint Solution

Posted by ken zheng on September 29, 2008

A great post show you how to Packaging a WCF Service as a SharePoint Solution
http://www.intranoggin.com/Lists/Posts/Post.aspx?ID=23

Posted in Uncategorized | Tagged: | Leave a Comment »

Create a SharePoint WebPart calling Web Service

Posted by ken zheng on September 29, 2008

To call a WCF Web Service, your code needs to have a config file. To do this in Sharepoint 2007, you need to use the web application config file so you can edit the web.config file of that web application adding the bindings and the client sections to the system.serviceModel section making the web.config file will look something like that. Add ServiceModel seciton after configSections

WebPart Config

The way I did is to create a WCF in VS 2008. Hosted and create a webpart in vs 2008. Use the same way to add service reference and write some code. Remember always catch excpetion in webpart otherwise the whole page will not work. Deploy the web part and modify the web.config to add ServiceModel.

Posted in Sharepoint, VS2008 | Tagged: , | 2 Comments »

General guideline for troubleshooting SharePoint issues

Posted by ken zheng on September 29, 2008

This is the list of steps to follow for troubleshooting general SharePoint issues.

1. Turn on the debug flag from SharePoint web.config

Note: Enabling debugging is not recommended on a production environment.

a. Locate the SharePoint web.config file which is typically located under one of the virtual directories in C:\Inetpub\wwwroot\wss\VirtualDirectories.
b. Make a backup of the web.config just in case.
c. Open the SharePoint web.config using a Visual Studio or a text editor such as notepad.
d. Find “CallStack”
e. Change the value of CallStack to “true”
f. Find “CustomErrors”
g. Change the value of CustomErrors mode to ”off”
h. Save the web.config.

2. Reproduce an issue you’re having i.e. by refreshing the broken web page

3. Examine the error from EventLog. In most cases, you will find no useful information from EventLog since SharePoint does a poor job leaving a trace on the EventLog.

4. Go to SharePoint logs folder (c:\Program Files\Common Files\Microsoft Shared\web server extensions\12\Logs). SharePoint dumps all logs in this folder, and so you should be able to find clues by examining logs in this folder.

a. Sort items by Date Modified
b. Open the latest log file using a notepad or other text editors.
c. Scroll down to the bottom
d. Examine the latest log

5. Analyze error messages found from Step 2, 3 and 4.

6. Investigate issue for 10 minutes

a. Examine the system account used for an application pool of a SharePoint application. Does the account have proper permissions?

7. If you’re stuck for more than 10 minutes, stop what you’re doing.

8. Search for the clues from Internet — Many times, we forget how useful Internet is and that somebody else typically had the same problem before.

9. If no clues have been found, ask for help.

a. Describe detailed steps how to reproduce the issues
b. Ask colleagues or reach out communities such as the MSDN SharePoint Forums [1]

10. Iterate the step 1 to step 5 until an issue is resolved.

[1] – http://forums.microsoft.com/MSDN/default.aspx?ForumGroupID=328&SiteID=1

Posted in Sharepoint | Tagged: | 1 Comment »

SharePoint dev tip – easily go to the 12 Hive

Posted by ken zheng on September 29, 2008

Just wanted to share a tip I find really useful. The idea being, I find myself going to the 12 hive quite often via command prompt.

Just create a file called 12.cmd and put it in your C:\Windows directory in the file put:
c:
cd c:\program files\…12… then from anywhere, just type 12 and voila!

Posted in Handy Tips, Sharepoint | Tagged: | Leave a Comment »

SiteList WebPart for SharePoint

Posted by ken zheng on September 26, 2008

This webpart will list all the sites you have permission to access.

Create a webpart project in vs 2005/2008,below is the source code:

[Guid("56d8a90d-8186-4333-b05d-f3b6b47a132c")]
    public class SiteList : System.Web.UI.WebControls.WebParts.WebPart
    {
        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            try
            {
                SPWeb Web = SPControl.GetContextWeb(Context);
                SPWebCollection webs = Web.GetSubwebsForCurrentUser();

                if (webs.Count == 0)
                {
                }
                else
                {
                    SPTreeView siteTreeView = new SPTreeView();
                    siteTreeView.ExpandDepth = 10;
                    int i = 0;
                    foreach (SPWeb webToDisplay in webs)
                    {
                        siteTreeView.Nodes.Add(new TreeNode(webToDisplay.Title, webToDisplay.Url, "", webToDisplay.Url, ""));

                        TreeNode topNode = siteTreeView.Nodes[i];
                        ProcessWeb(topNode, webToDisplay);
                        i++;
                    }
                    Controls.Add(siteTreeView);
                }
            }
            catch (Exception ex)
            {
                Controls.Clear();
                Label errorMessage = new Label();
                errorMessage.Text = "There was an error in the code.  Please contact your system administrator and rely the following " +
                    "message: " + ex.Message;
                Controls.Add(errorMessage);
            }
        }

        private void ProcessWeb(TreeNode topNode, SPWeb subsite)
        {
            SPWebCollection webs = subsite.GetSubwebsForCurrentUser();
            foreach (SPWeb webToDisplay in webs)
            {
                topNode.ChildNodes.Add(new TreeNode(webToDisplay.Title, webToDisplay.Url, "", webToDisplay.Url, ""));

                 ProcessWeb(topNode, webToDisplay);

            }
        }
    }

Posted in Sharepoint, VS2008 | Tagged: , | Leave a Comment »