Search This Blog

2009-05-17

Creating a Simple Webpart using usercontrol

Sometimes you may have an existing Web page application that needs to be ported to SharePoint. It is relatively simple to do this by converting the pages to User Controls. Although User Controls aren’t recommended for all Web Part applications, they can be a quick way to get an ASP.NET application deployed into your SharePoint Web sites.
We will need to create a Visual Studio Web Application project, create a Web User Control (ASCX), a class that can act as the Web Part interface to our ASCX Web User Control and a ASP.NET web page in which we can test and debug our components.

Step 1.In Visual Studio, create a new ASP.NET Web Application (new web site will NOT work for this exercise). For the project name, enter MyWebpart.




Step 2.Select the Microsoft.SharePoint.dll and set a reference to it in your project.



If you are developing on a machine not having SharePoint or MOSS, you will need to copy this file along with Microsoft.SharePoint.Search.dll and Microsoft.SharePoint.Search.xml from the same directory to a directory on your local computer.

Step 3.add a Web User Control file to your project and name it MyUserControl.ascx


Step 4.The design of the user control will be as follows
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="MyUserControl.ascx.cs" Inherits="MyWebpart.MyUserControl" %>
<table>
<tr>
<td>
Enter First Name :
</td>
<td>
<asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Enter Last Name :
</td>
<td>
<asp:TextBox ID="txtLastName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
<asp:Button ID="btnConcate" runat="server" Text="Concate" OnClick="btnConcate_Click" />
</td>
<td>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
</td>
</tr>
</table>



Step 5.Add the following code in the codebehind file of the user control
protected void btnConcate_Click(object sender, EventArgs e)
{
txtName.Text = txtFirstName.Text + " " + txtLastName.Text;
}

Step 6.Next, add a class file to your project named MyClass.cs


Step 7.Import the following namespace
using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
And Inherit Microsoft.SharePoint.WebPartPages.WebPart as follows

public class MyClass : Microsoft.SharePoint.WebPartPages.WebPart

Step 8.Creating the following class lavel veriable
protected string _userControlPath = @"~/usercontrols/";
protected string UserControlFileName = @"MyUserControl.ascx";
private Control _control;
private string _exceptions = "";
Step 9.Next, the class will override the CreateChildControls method to load the Web Control. In this method, the control is loaded from the source file

protected override void CreateChildControls()
{
try
{
_control = this.Page.LoadControl(_userControlPath + UserControlFileName);
Controls.Add(_control);
}
catch (Exception CreateChildControls_Exception)
{
_exceptions += "CreateChildControls_Exception2: " + CreateChildControls_Exception.Message;
}
finally
{
base.CreateChildControls();

}
}

Step 10.Next, we will override the RenderContents method which is specific to the WebPart class from which we inherit. This method was chosen because in the life cycle of SharePoint web pages, by the time this method is called all prerequisite processing will have taken place, including the creating and assignment of SharePoint variables and the CreateChildControls method. There is no need to call EnsureChildControls here since child controls will always exist when this method is called by the SharePoint ASP engine.

protected override void RenderContents(HtmlTextWriter writer)
{
try
{
base.RenderContents(writer);
}
catch (Exception RenderContents_Exception)
{
_exceptions += "RenderContents_Exception: " + RenderContents_Exception.Message;
}
finally
{
if (_exceptions.Length > 0)
{
writer.WriteLine(_exceptions);
}
}
}

Step 11.Just to work with the Javascript function and another server side function from the ECB Menu, write the following function
public override void CreateWebPartMenu()
{
SPWeb web = SPControl.GetContextWeb(this.Context);
Microsoft.SharePoint.WebPartPages.MenuItem mnuClientSideMenu = new Microsoft.SharePoint.WebPartPages.MenuItem("Menu With Javascript Handler", "javascript:return alert('Client Side Menu Click');");
Microsoft.SharePoint.WebPartPages.MenuItem mnuServerSideMenu = new Microsoft.SharePoint.WebPartPages.MenuItem("Menu With C# Handler", "MENUID", new EventHandler(mnuServerSideMenu_Click));
this.WebPartMenu.MenuItems.Insert(0, mnuClientSideMenu);
this.WebPartMenu.MenuItems.Insert(0, mnuServerSideMenu);
}
private void mnuServerSideMenu_Click(object sender, EventArgs e)
{
_exceptions += "Server Side Menu CLicked";
}

Step 12.We are not quite ready to build our class. Since we intend this WebPart and Web User Control to live in Microsoft Office SharePoint Server and the Global Assembly Cache, we will need to assign a Strong Name key and sign the control. In Solution Explorer, right-click the project node and select Properties. The Project Property Pages appear. Select the Signing tab from the choices on the left. Check the "Sign the assembly" box and select from the "Choose a strong name key file" drop down list.
Enter "MySnk.snk" in the "Key file name" field. Uncheck the box marked "Protect my key file with a password"




Step 13.First you will need to ensure that your target SharePoint web site has an UserControls directory. If not, create it. Then copy the ASCX file from your project directory to your SharePoint UserControls directory.




Step 14.The Global Assembly Cache (GAC) is a special folder located at %WINDIR%\Assembly where %WINDIR% is the full path to your Windows folder (such as C:\Windows or C:\Winnt). Use Windows Explorer to copy your DLL into the GAC folder.

Step 15.Open the web.config file of your Sharepoint Application from the C:\Inetpub\wwwroot\wss\VirtualDirectories\[port No\Web.config]



Step 16.Add the following line within the SafeControls section.The following four part assemblies name will be varied for your application
<SafeControl Assembly="MyWebpart, Version=1.0.0.0, Culture=neutral, PublicKeyToken=6f7e2cdc414a688d" Namespace="MyWebpart" TypeName="*" Safe="True" />

you can use .NET Reflector by Lutz Roeder at http://www.aisto.com/roeder/dotnet/ to browse to your assembly's DLL file and read out the Assembly information and Public Key Token with no hassles and the ability to cut and paste.



Step 17. Add the following line within the assemblies section.The following four part assemblies name will be varied for your application
<add assembly="MyWebpart, Version=1.0.0.0, Culture=neutral, PublicKeyToken=6f7e2cdc414a688d" />

Step 18.Next, we need to import (or upload) into SharePoint the WebPart file we created in the previous section. browse to your SharePoint site. Under "Site Actions" select Site Settings, Modify All Site Settings.



Step 19.On the Site Settings page, under Galleries, click Web Parts


Step 20.In the Web Part Gallery, click New:



Step 21.Check the following webpart you have made



Step 22.Click on Populate Gallery


Step 23.Now back to your web part galerry and click on "Edit Document Properties" for your web part



Step 24.Put the following values(all are optional) and click OK


Step 25.To test or use your WebPart, you will need to add it to a SharePoint page just like you would any other WebPart. This will be very simple since we have added our WebPart to the Web Part Gallery. To summarize:

Edit a SharePoint page
Select a zone into which you want to place your WebPart
Add the WebPart to the zone
Save the page




Step 26.Click on a zone and select "Add Web Part". The Add Web Part dialog will be displayed:



Step 27.Scroll down and find your Web Part, select it and click "Add". Publish your page so everyone can see it. Your web part will now be fully functional on your SharePoint page.

Step 28.Click on "Menu With C# Handler" and "Menu With Javascript Handler".You will get the followig output


Complete Code of "MyClass.cs"


using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace MyWebpart
{
public class MyClass : Microsoft.SharePoint.WebPartPages.WebPart
{
protected string _userControlPath = @"~/usercontrols/";
protected string UserControlFileName = @"MyUserControl.ascx";
private Control _control;
private string _exceptions = "";
protected override void CreateChildControls()
{
try
{
_control = this.Page.LoadControl(_userControlPath + UserControlFileName);
Controls.Add(_control);
}
catch (Exception CreateChildControls_Exception)
{
_exceptions += "CreateChildControls_Exception2: " + CreateChildControls_Exception.Message;
}
finally
{
base.CreateChildControls();
}
}
protected override void RenderContents(HtmlTextWriter writer)
{
try
{
base.RenderContents(writer);
}
catch (Exception RenderContents_Exception)
{
_exceptions += "RenderContents_Exception: " + RenderContents_Exception.Message;
}
finally
{
if (_exceptions.Length > 0)
{
writer.WriteLine(_exceptions);
}
}
}
public override void CreateWebPartMenu()
{
SPWeb web = SPControl.GetContextWeb(this.Context);
Microsoft.SharePoint.WebPartPages.MenuItem mnuClientSideMenu = new Microsoft.SharePoint.WebPartPages.MenuItem("Menu With Javascript Handler", "javascript:return alert('Client Side Menu Click');");
Microsoft.SharePoint.WebPartPages.MenuItem mnuServerSideMenu = new Microsoft.SharePoint.WebPartPages.MenuItem("Menu With C# Handler", "MENUID", new EventHandler(mnuServerSideMenu_Click));
this.WebPartMenu.MenuItems.Insert(0, mnuClientSideMenu);
this.WebPartMenu.MenuItems.Insert(0, mnuServerSideMenu);
}
private void mnuServerSideMenu_Click(object sender, EventArgs e)
{
_exceptions += "Server Side Menu CLicked";
}
}
}

Happy Programming!!!

No comments: