2

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 !!!!

18

SharePoint Custom Action: Execute Code from the EditControlBlock Location

There are a few great blogs available to show how to develop custom actions. However, it is quite tricky to attach custom code to a EditControlBlock location.















Normally with most custom action locations, you can simply specify the assembly and control class in the Elements.xml file.



Example:
ControlAssembly="LaunchDocItemCustEvent, Version=1.0.0.0, Culture=neutral, PublicKeyToken=63316a326efb84ec"
ControlClass="LaunchDocItemCustEvent.LaunchDocWriter";


But in the case of EditControlBlock you will get an “Invalid URL” error when you try execute the code.


You have to specify a custom target URL and not an assembly..example:
UrlAction Url=http://www.google.com


This article will show you how to work around this problem by applying a bit of Javascript and additional custom code.

The tutorial will show all the steps required to get our URLAction in the EditControlBlock to initiate a postback and we will then trap the postback in another (second) custom action which has a control class in place. From here we can then execute any custom code.


So, We will change to UrlAction from:
     UrlAction Url=http://www.google.com/
to
     UrlAction Url="javascript:__doPostBack('MyEventTarget',{ItemId});"

Here are the steps:



1. Install WSPBuilder


2. To start, go ahead and create a new WSPBuilder project called “LaunchDocItemCustEvent”.















and add a Blank Feature to it named “WriteTextFile”.


















 Construct the elements.xml file (I removed the '<' and '/>' characters in this post) :
?xml version="1.0" encoding="utf-8" ?

Elements xmlns="http://schemas.microsoft.com/sharepoint/"
CustomAction
Id="WriteDocId"
Title="Write Doc ID to Text File"
Location="EditControlBlock"
Description="Write Doc ID to Text File"
RegistrationType="List"
RegistrationId="101"
ShowInLists="TRUE"
UrlAction Url="http://www.google.com"/
CustomAction
Elements


Build the project.



Enable Output Window.

Build WSP


 
 





View results in Output Window. Ensure there are no errors.



















Deploy the solution






















Remember that your solution will deploy to the web url you specified in the project properties...go to Project --&gt; Properties --&gt; Debug.. enter the web url to which you want to deploy.

After deployment go to your SharePoint site, refresh and then navigate to a document library. Select a document item and click on the dropdown actions menu.
You will see the new custom action menu item.
When you click on the custom action you will see that you are redirected to Google.com

















OK, so we have a foundation in place and now we can start tweaking it to NOT redirect, but rather to execute our custom code.

Add new C# class your solution – name it LaunchDocWriter

In the new Class add references to:
Microsoft.SharePoint
System.Web

Add the following Code:
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.Utilities;
using System.IO;


Inherit from SPLinkButton. The IMPORTANT thing is also that your class must be public.

public class LaunchDocWriter : SPLinkButton
{
} 

Overwrite the onload event:

protected override void OnLoad(EventArgs e)
{
this.EnsureChildControls();
base.OnLoad(e);


if (this.Page.Request["__EVENTTARGET"] == "MyEventTarget")
{
int itemId = Convert.ToInt32(this.Page.Request["__EVENTARGUMENT"]);


System.IO.TextWriter mywriterFired = new StreamWriter(@"C:\zzz_CodeBehindFileItemMenu.txt", true);


mywriterFired.WriteLine("Event Fired at:" + DateTime.Now.ToLongTimeString() + ": Item ID:" + itemId.ToString());


mywriterFired.Close();
}
}


Now we need to somehow instruct SharePoint to NOT redirect to a url, but to rather execute the new code.

In Elements.xml change (I left out the '&lt;' and '/&gt;' characters for this post to work, but you should include them in your code):
UrlAction Url=http://www.google.com/
to
UrlAction Url="javascript:__doPostBack('MyEventTarget',{ItemId});"

?xml version="1.0" encoding="utf-8" ?
Elements xmlns="http://schemas.microsoft.com/sharepoint/"
CustomAction
Id="WriteDocId"
Title="Write Doc ID to Text File"
Location="EditControlBlock"
Description="Write Doc ID to Text File"
RegistrationType="List"
RegistrationId="101"
ShowInLists="TRUE"
UrlAction Url="javascript:__doPostBack('MyEventTarget',{ItemId});"


CustomAction
CustomAction Id="UserInterfaceCustomActions.SiteActionsToolbar"
GroupId="SiteActions"
Location="Microsoft.SharePoint.StandardMenu"
Sequence="1000"
Title="MY SITE ACTIONS BUTTON"
ControlAssembly=""
ControlClass="LaunchDocItemCustEvent.LaunchDocWriter"
CustomAction
Elements

Rebuild your project.

Add

ControlAssembly="LaunchDocItemCustEvent, Version=1.0.0.0, Culture=neutral, PublicKeyToken=63316a326efb84ec"
To
CustomAction Id="UserInterfaceCustomActions.SiteActionsToolbar"
GroupId="SiteActions"
Location="Microsoft.SharePoint.StandardMenu"
Sequence="1000"
Title="MY SITE ACTIONS BUTTON"
ControlAssembly="LaunchDocItemCustEvent, Version=1.0.0.0, Culture=neutral, PublicKeyToken=63316a326efb84ec"
ControlClass="LaunchDocItemCustEvent.LaunchDocWriter"
/CustomAction
/Elements

Right click on your project and select "Build WSP"
Right click on your project and select "Deploy WSP"


If you did not get any errors you can refresh your SharePoint site.
Attach your project to all w3wp processes and add a breakpoint.
you will now see that your code execute when the user click on the menu item.

Enjoy !















3

Custom Properties inside a SmartPart User Control

To add custom properties to a smartpart usercontrol is actually very easy.
First create a simple usercontrol and ensure the usercontrol works when added to a SharePoint SmartPart Web Part.
Then use the code (below) to add functionality within the usercontrol to manage the custom properties.


In this example when the user edit the SharePoint Page and "Modify Web Part", he/she will see on the right hand side of the screen a new custom property as part of the web part properties page.

When the user store a value in the smartpart Custom Property and return to the SharePoint page, he/she can click on the "cmdFetchValue" button and the code will return the value of the custom property into a textbox.

namespace testmysmartpart2

{
    [System.ComponentModel.Description("Custom Property Demo  
     SmartPart")]



    public partial class CustomProperties :  
                      System.Web.UI.UserControl
    {
        private string _customValue = null;
        [System.ComponentModel.Browsable(true),         
         System.ComponentModel.Description("Custom Value")]


        public string CustomValue
        {
        get { return _customValue; }
        set { _customValue = value; }
        }


        protected void cmdFetchValue_Click(object sender,
                                           EventArgs e)
        {
            TextBox1.Text = _customValue;
        }
    }
}

1

SharePoint Event Handler Tutorial 2: Download Document to Local Folder

Someone recently asked how to add SharePoint event handler code which will download a file from a document library to a local NTFS folder every time a document is uploaded into a SharePoint document library.
The solution is actually very easy.
1-Create a new Event Handler on a SharePoint Document Library (ItemEventReceiver). To do this, please follow my tutorial available here.
2-Ensure that your basic event handler as per the turorial in step 1 is working and that you can debug (step through) the code.
3-Now you are ready to add the code to save a document to a local folder. Extend the tutorial code in the following way:
    3.1-Add the following using statements: (remember this is C#)
           using System.IO;

           using System.Text;
    3.2-Add the following code inside the ItemAdded event so that the complete event look like below:
public override void ItemAdded(SPItemEventProperties properties)

{
StringBuilder strWFBuilderCheck = new StringBuilder();
strWFBuilderCheck.Append(@"C:\TestFolder\");
strWFBuilderCheck.Append(DateTime.Now.Date.Year.ToString());
strWFBuilderCheck.Append(DateTime.Now.Date.Month.ToString());
strWFBuilderCheck.Append(DateTime.Now.Date.Day.ToString());
strWFBuilderCheck.Append("_");
strWFBuilderCheck.Append(DateTime.Now.TimeOfDay.Hours.ToString());
strWFBuilderCheck.Append(DateTime.Now.TimeOfDay.Minutes.ToString());
strWFBuilderCheck.Append(DateTime.Now.TimeOfDay.Seconds.ToString());
strWFBuilderCheck.Append("_");
strWFBuilderCheck.Append(properties.ListItem.File.Name);

string WorkfFileLocationcheck;
WorkfFileLocationcheck = strWFBuilderCheck.ToString();


BinaryWriter binWritercheck = new BinaryWriter(File.Open(WorkfFileLocationcheck, FileMode.Create));
byte[] itembytescheck = properties.ListItem.File.OpenBinary();
string itemstringcheck = Encoding.ASCII.GetString(itembytescheck);
System.Text.ASCIIEncoding encodingcheck = new System.Text.ASCIIEncoding();
byte[] bytescheck = encodingcheck.GetBytes(itemstringcheck);


binWritercheck.Write(itembytescheck);


binWritercheck.Close();
}


Build your solution
Deploy the solution
Create a local folder called "C:\TestFolder\"
Refresh your SharePoint website
Add a breakpoint to the code
Attach the code to a process (w3wp)
Go to a document library and upload a document...you will see the document is also written to a local folder.
The example will also work when uploading multiple documents as well as when you open a document library in explorer view and then copy and paste (or drag) files into the folder.
 
Shout if you need any help !!
 
Enjoy !!