Wednesday, January 20, 2010

SharePoint Code Behind Tutorial

Once you become familiar with the steps required to deliver a code behind a SharePoint Page you will find that it is actually a very simple process.

  1. Create the Code-Behind Assembly
  2. Deploy the Code-Behind Assembly
  3. Reference the Assembly in your SharePoint Page
  4. Tell SharePoint that it is safe to use the assembly
This tutorial will guide you through the steps.

Create the Code-Behind Assembly
To create the code behind assembly do the following:
Create a new empty C# Class Project. 

In your new class add a reference to Microsoft.SharePoint
Add the following Code

using Microsoft.SharePoint;

namespace IRMSealerEngineForm

{
public class SealEngineForm : System.Web.UI.Page
{
  protected Label lblHeading = new Label();
  protected LinkButton cmdReturnToList = new LinkButton();


  protected override void OnInit(EventArgs e)
  {
    base.OnInit(e);
    cmdReturnToList.Click += new EventHandler
    (cmdReturnToList_Click);
  }


  protected void Page_Load(object sender, EventArgs e)
  {
    if (!IsPostBack)
    {
      //do something... example:
      //the following code read a querystring and set the text  
      // on a label.

      lblHeading.Text = "The following error occurred:";
     
      if (this.Request.QueryString["ErrorMessage"] != null)
      {
        if (this.Request.QueryString["ErrorMessage"] != "")
        {
          lblHeading.Text = this.Request.QueryString 
          ["ErrorMessage"].ToString();
        }
      }
    }
  }


    protected void cmdReturnToList_Click(object sender,  
     EventArgs e)
    {
           //Do something...this example will do a redirect.
     if (this.Request.QueryString["SourceURL"] != null)
      {
       this.Page.Response.Redirect(this.Request.QueryString
       ["SourceURL"].ToString());
    }
  }
 }
}

Sign the project with a strong-name key.
Build the project.

Deploy the Code-Behind Assembly
Before you deploy the code behind assembly you need to collect the assembly public key.
You can do this within Visual Studio 2008 by going to Tools --> Get Public Key.
Alternatively you can use the very handy RedGate .NET Reflector to inspect your compiled dll.





 
 
 
 
 
 










Now, copy your compiled assembly to C:\Inetpub\wwwroot\wss\VirtualDirectories\22015\bin\  where 22015 is the port number of your web application.

Reference the Assembly in your SharePoint Page

Okey, we are making progress.. the next step is to open your SharePoint Page using SharePoint Designer and tell the page to rather be controlled by you assembly than by the standard SharePoint assemblies.
to do this:
Open SharePoint Designer
Open your site
Locate the page which you want to associate with the code behind
Open the page
View the page in code view
Look at the top of the code and replace the "Inherits" section from standard sharepoint to your new asembly.

The standard is:
Inherits="Microsoft.SharePoint.WebPartPages.WebPartPage,Microsoft.SharePoint,Version=12.0.0.0,Culture=neutral,PublicKeyToken=71e9bce111e9429c"  

replace this with:

Inherits="IRMSealerEngineForm.SealEngineForm"
You can remove all the other standard attributes so that your code look like:
Page Language="C#" MasterPageFile="~masterurl/default.master" Inherits="IRMSealerEngineForm.SealEngineForm" EnableViewState="false" EnableViewStateMac="false" meta:progid="SharePoint.WebPartPage.Document" title=""
















Tell SharePoint that it is safe to use the assembly
Browse to C:\Inetpub\wwwroot\wss\VirtualDirectories\22015\ where 22015 is the port number of your web application.
Make a backup of the web.config file (for safe-keeping)
Open the web.config file and locate the safecontrols section.
You will notice that this section already contains a few entries.
Add an entry for your custom assembly.
Example (I did not include the "<" and "/>" in the code below, but you should have it in place):
SafeControl Assembly="IRMSealerEngineForm, Version=1.0.0.0, Culture=neutral, PublicKeyToken=e3046d5fe4a2aed9" Namespace="IRMSealerEngineForm" TypeName="*" Safe="True"

Where e3046d5fe4a2aed9 is the public key token of your assembly (as per description earlier in this tutorial)










Save the web.config and close the file.

Do an IIS Reset and browse to your SharePoint site...open the page which contains the code-behind and test your code.
You can also debug your code by attaching it to a w3wp process... in Visual Studio go to Debug...Attach to Process..and select all the w3wp process and click on attach.

Enjoy and let me know if it does not work !!!!

5 comments:

Harry said...

Did not understand from

"Locate the page which you want to associate with the code behind"

Which page is this? I don't have any page

Harry said...

Page is recognising that it needs the class to load, but the text of the label is not changing on page load.

Tapan kumar said...

Thanks @John, you are such a briliant.

I have followed two of your articles and those worked for me like miracles.

Thanks for sharing your valuabe knoladge with us.

Unknown said...

Hi Johan, I followed this but didn't work.

sameer said...

Public key token not generating for me and there is no port folder. Please advice.

Post a Comment