Tuesday, August 12, 2008

Constructing Pages with Custom Controls in SharePoint

The groundwork needed to create a custom control in SharePoint is somewhat similar to what is required in a custom ASP.NET application.

Let’s begin with a simple example of a custom control. A server-side control in ASP.NET is defined as a class that inherits from the Control class. Following is a simple code which, which displays "site title" and "site id" based on SPWeb object which is fetched from "SPContext".

using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SharePoint;
namespace CustomSitePages
public class CustomControl1 : WebControl
protected override void RenderContents(HtmlTextWriter output)
SPWeb site = SPContext.Current.Web;
output.Write("Current Site: " + site.Title);
output.Write("Current Site ID: " + site.ID.ToString());

If we were to this custom control in a SharePoint page, all we need to do is follow few simple steps:
  1. Compile above code into a DLL with strong name.
    You have two choices as to where to deploy an assembly DLL that contains a custom control when you want to use it in a site page. First, you can compile the assembly DLL with a strong name and install it in the Global Assembly Cache. Alternatively, you can deploy the assembly DLL by placing it inside the root directory of the hosting Web application inside a nested directory named bin. Note that when you plan to deploy the assembly DLL with custom controls in the bin directory, you have the option of compiling it with or without a strong name.
  2. make following entry in Web.config of sharepoint site
    Assembly="CustomSitePages, ...,public token"
    default web.config location for site running on port:11111 is: C:\Inetpub\wwwroot\wss\VirtualDirectories\11111\web.config
  3. Once the assembly DLL with the custom control is properly deployed, you can then reference it within a page template by using the ASP.NET Register directive. The following code example displays a page template that uses the custom control shown above.

    <%@ Page MasterPageFile="~masterurl/default.master"
    meta:progid="SharePoint.WebPartPage.Document" %>

    <%@ Register Assembly="CustomSitePages, ... "
    Namespace="CustomSitePages" TagPrefix="CustomSitePages" %

    <asp:Content ID="main"
    <h3>A custom control example</h3>
    <CustomSitePages:CustomControl1 ID="cc1" runat="server"/>
Hope this helps.


No comments: