You are on page 1of 24

Creating a WebPart to Manage Lists

This document provides steps for creating a custom Web Part to access list. It is a
simple Web Part that allows you to add records in the SharePoint list.

Requirements
Microsoft Visual Studio .NET 2005
Microsoft Office SharePoint Server 2007

In This Document
There are 3 sections of this document that includes,
1. Creating a Web Part
2. Deploying your Web Part
3. Testing your Web Part

1 |Page
1. Creating a Web Part
We will create Web Part in C#.

Create a new Class Library project

1. Start Visual Studio .NET.


2. On the File menu, point to New, and then click Project.
3. In the New Project dialog box, click Visual C# Projects, and then select
the Class Library template.
4. Type WPPartList as the name and specify the location for the project files,
and then click OK.

Adding references

1. To create a Web Part, you need to add a reference to the


Microsoft.SharePoint assembly (Microsoft.SharePoint.dll) in your Class
Library project. If you're working from Visual Studio .NET installed on a server
running Microsoft Windows SharePoint Services, the Microsoft.SharePoint
assembly will be registered and available from the Add Reference dialog box.
If you want to develop Web Parts on another computer, you will need access
to a server running Windows SharePoint Services. On the server computer,
copy Microsoft.SharePoint.dll from the RootDrive:\Program Files\Common
Files\Microsoft Shared\Web Server Extensions\60\ISAPI folder to a folder on
the computer where you will be developing Web Parts, and follow the steps in
2 |Page
this topic to add a reference. You will also need to add a reference to
System.Xml.dll to support the System.Xml.Serialization namespace which is
used to define the XML namespace for serializing custom properties, as
described later in this topic.

To add a reference to Microsoft.SharePoint.dll to a project

If you are creating a Web Part on a computer that has Windows SharePoint
Services or SharePoint Portal Server installed on it:

1. On the Project menu, click Add Reference.


2. On the .NET tab, double-click Windows SharePoint Services.
3. Click OK.

If you are creating a Web Part on a computer that does not have Windows
SharePoint Services or SharePoint Portal Server installed on it:

3 |Page
1. On the Project menu, click Add Reference.
2. On the .NET tab, click Browse, and then navigate to
C:\inetpub\wwwroot\bin (or the folder to which you copied
Microsoft.SharePoint.dll). Select Microsoft.SharePoint.dll, and click
Open.
3. Click OK.

4 |Page
To add a reference to System.Xml.dll to a project

The same steps apply regardless of whether you are creating a Web Part on a
computer that has Windows SharePoint Services or SharePoint Portal Server
installed on it:

1. On the Project menu, click Add Reference.


2. On the .NET tab, double-click System.Xml.dll.
3. Click OK.

5 |Page
Initial project settings

Before you start working with the code for a Web Part, you need to make the
following changes to your project settings:

• Ensure the version number does not auto increment.


• Strongly name the assembly.

Ensure the version number does not auto increment.

If the AssemblyVersion property of your project is set to increment each time you
recompile, change this behavior. A Web Part Page identifies a Web Part with the
version number that is specified in the web.config file. (For details, see "Register the
Web Part as a Safe Control" later in this document.) With the AssemblyVersion
property set to increment, if you recompile your Web Part after importing it into a
Web Part Page, the Web Part Framework will look for the version number you
specified in the web.config file. If the version number does not match, an error will
occur. To prevent the version number of your Web Part from incrementing each
time you recompile, you need to set the version number in AssemblyInfo.cs. These
steps are not required if you use the Web Part Library template.

To set the version number

1. In the Solution Explorer, double-click AssemblyInfo.cs.


2. Edit the line
[assembly: AssemblyVersion("1.0.*")]
so that it reads
[assembly: AssemblyVersion("1.0.0.0")]

6 |Page
Strongly name the assembly

Web Parts are designed to be distributed over the Internet or an intranet. For
security reasons when creating a custom Web Part, you must strongly name it to
ensure that the part can be trusted by your users.

A strong name consists of the assembly's identity plus a public key and a digital
signature. In Visual Studio .NET 2005 it is very easy to create a file containing the
key pair.

To strongly name the assembly

1. On the Project menu, click Properties.


2. On the Signing tab, check the option Sign the assembly. This will enable
the combo box below.
3. In the Choose a strong key file combo box, select <New…>.

7 |Page
The Create Strong Name Key dialog will open.

4. Type the Key file name as Workflow (You can type any other name you
desire).
5. Uncheck the option Protect my key file with a password.
6. Click OK.

Note:

1. Although it is possible to create and use the same strong name key
pair file (.snk) for all Web Part assemblies you build, for greater
security it is recommend that you create and use a different key pair
file (.snk) for each assembly you create.
2. Also, if you change the key pair file, you will need to register the Web
Part again as SafeControl in web.config file.

8 |Page
Modifying the default class file

• Adding namespace directives


• Inheriting from the WebPart class
• Defining the XML namespace
• Modifying the Web Part’s namespace

To start modifying the default class file

• In the Solution Explorer, double-click Class1.cs.


• Rename it to PartAdd.cs.

• Also change the class name to PartAdd.

public class PartAdd


{
}

Adding namespace directives

To make it easier to write a basic Web Part class, you should use the using
directive to reference the following namespace in your code:

Add the following using directives near the top of your code:

using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Xml.Serialization;
using System.Diagnostics;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;

9 |Page
• The Microsoft.SharePoint.WebPartPages namespace provides the types
for Web Part Pages, such as the WebPart class.
• The System.Xml.Serialization namespace provides the XmlRootAttribute
and XmlElementAttribute classes that support the XmlRoot and
XmlElement attributes used to declare the XML namespace that is used for
the serialization of any custom properties implemented by your Web Part.

For the purposes of this sample, we're also adding using directives for the
System.Web.UI.HtmlControls and System.Web.UI.WebControls namespaces
because we'll use few HtmlControls & WebControls classes in the rendering of
this Web Part.

Inheriting from the WebPart class

A Web Part is compatible with ASP.NET server controls because the


Microsoft.SharePoint.WebPartPages.WebPart base class inherits from the
same parent class as server controls, the System.Web.UI.Control class. To create
a Web Part, the implementation of your WebPart class must inherit from the
WebPart base class.

To inherit from the WebPart base class

• Change the class definition as shown below

public class PartAdd : WebPart


{
}

Defining the XML namespace

To successfully import your custom Web Part, you must define an XML namespace
for all of the properties in your Web Part. You can do this globally by declaring the
XmlRoot attribute at the top of your Web Part class definition, or by declaring an
XmlElement attribute for each custom property in your class.

To define the XML namespace for an entire WebPart class

• Add the XMLRoot attribute above declaration for your WebPart class

[XmlRoot(Namespace = "WorkflowStudios")]
public class PartAdd : WebPart
{
}

10 | P a g e
Modifying the Web Part's namespace

If you are creating multiple Web Parts, you should generally use the same
namespace across all of your Web Parts. By default, both the Web Control Library
and Web Part Library templates assign the namespace the same name as your
project. For this example, we're using the arbitrary namespace of
WorkflowStudios for both the WebPart class and XML namespace for the Web
Part's properties.

To modify the Web Part namespace

• Replace this line of code


namespace WPPartList
• with this line
namespace WorkflowStudios

11 | P a g e
Defining the logic and rendering of your Web Part

After you have completed the previous steps, you can define the logic and
rendering for your Web Part.

For this Web Part, we will write some basic ASP.NET code to create few Web & HTML
server controls. We will have 4 labels, 4 text boxes and 1 command button. Labels
are displayed before the textboxes. User will enter values in those textboxes. After
clicking the command button a new item will be added in the PartInfo list.

The following code sample shows the complete PartAdd.cs file with all of the
modifications described in the previous steps plus the additional code to define the
Web Part's functionality.

This code sample assumes the existence of a list named as PartInfo with following
columns added as,

PartNo (required)
PartDesc
Price (Type = Currency)
The field Title is added by default when the list is created and is required. If
you don’t want you can remove it.

using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Xml.Serialization;
using System.Diagnostics;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebPartPages;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.WebControls;

namespace WorkflowStudios
{
[XmlRoot(Namespace = "WorkflowStudios")]
public class PartAdd : WebPart
{
// Declare variables for HtmlControls user interface elements.
Label _lbTitle;
Label _lbPartNo;
Label _lbDesc;
Label _lbPrice;
HtmlInputText _txtTitle;
HtmlInputText _txtPartNo;

12 | P a g e
HtmlInputText _txtDesc;
HtmlInputText _txtPrice;
HtmlButton _btnUpdate;

// Event handler for _btnUpdate control that sets the


public void _btnUpdate_Click(object sender, EventArgs e)
{
try
{
String strUrlSiteName = "niranjan";
String strListName = "PartInfo";

SPSite siteCollection = SPControl.GetContextSite(Context);


SPWeb web = siteCollection.AllWebs[strUrlSiteName];
SPList list = web.Lists[strListName];

// accessing the list


SPListItem item;
SPListItemCollection items = list.Items;

// add data
item = items.Add();
item["Title"] = _txtTitle.Value;
item["PartNo"] = _txtPartNo.Value;
item["PartDesc"] = _txtDesc.Value;
item["Price"] = _txtPrice.Value;

// update
item.Update();
list.Update();
}
catch (Exception ex)
{
System.Diagnostics.EventLog.WriteEntry("PartAdd", ex.Message,
EventLogEntryType.Error);
}
}

// Override the ASP.NET Web.UI.Controls.CreateChildControls


// method to create the objects for the Web Part's controls.
protected override void CreateChildControls()
{

// Create label controls


_lbTitle = new Label();
_lbTitle.Text = "Title: ";
Controls.Add(_lbTitle);

_lbPartNo = new Label();


_lbPartNo.Text = "Part No.: ";
Controls.Add(_lbPartNo);

_lbDesc = new Label();


_lbDesc.Text = "Part Description: ";
Controls.Add(_lbDesc);

13 | P a g e
_lbPrice = new Label();
_lbPrice.Text = "Price: ";
Controls.Add(_lbPrice);

// Create textbox controls


_txtTitle = new HtmlInputText();
_txtTitle.Value = "";
Controls.Add(_txtTitle);

_txtPartNo = new HtmlInputText();


_txtPartNo.Value = "";
_txtPartNo.MaxLength = 5;
Controls.Add(_txtPartNo);

_txtDesc = new HtmlInputText();


_txtDesc.Value = "";
Controls.Add(_txtDesc);

_txtPrice = new HtmlInputText();


_txtPrice.Value = "";
_txtPrice.MaxLength = 6;
Controls.Add(_txtPrice);

// Create button control and wire its event handler.


_btnUpdate = new HtmlButton();
_btnUpdate.InnerText = "Save Part Information";
_btnUpdate.ServerClick += new EventHandler(_btnUpdate_Click);
Controls.Add(_btnUpdate);

// Here we will decide how those Web/Html controls get rendered


// on the Web Part.
protected override void RenderWebPart(HtmlTextWriter output)
{
// Securely write out HTML
output.Write("<b>Part Information</b>");
output.Write("<br>");
output.Write("<br>");
_lbTitle.RenderControl(output);
_txtTitle.RenderControl(output);
output.Write("<br>");
_lbPartNo.RenderControl(output);
_txtPartNo.RenderControl(output);
output.Write("<br>");
_lbDesc.RenderControl(output);
_txtDesc.RenderControl(output);
output.Write("<br>");
_lbPrice.RenderControl(output);
_txtPrice.RenderControl(output);
output.Write("<br>");
output.Write("<br>");
_btnUpdate.RenderControl(output);

14 | P a g e
output.Write("<br>");
}

}
}

After you've added all of the preceding code, you can build your Web Part. After
building it will create an assembly for the part named WPPartList.dll . Assuming
that you are building your Web Part on your server,

15 | P a g e
2. Deploying your Web Part
There are 3 deployment location types available for Web Parts.

• Global Assembly Cache


• RootDrive:\Inetpub\wwwroot\wss\VirtualDirectories\80\bin
(Or that is your SharePoint sites \bin folder)
• Any local directory on machine hosting SharePoint Server

In our example we will use the Global Assembly Cache to deploy a Web Part:

• Install the assembly to Global Assembly Cache (GAC)


• Register your Web Part as a safe control.
• Import your Web Part into a Web Part Page.

Irrespective of the location, you must perform last 2 steps to deploy a Web Part.

Install the assembly to Global Assembly Cache

Installing the assembly to GAC is as easy as drag and drop.

To install the assembly to Global Assembly Cache

1. Open RootDrive:\WINDOWS\assembly folder in one Explorer window.


2. Open the bin folder where the WPPartList.dll assembly is generated.
3. Simply drag the assembly from bin folder to the
RootDrive:\WINDOWS\assembly folder

Register your Web Part as a SafeControl

As a security measure, Windows SharePoint Services requires you (or a server


administrator) to register the Web Part's assembly and namespace as a SafeControl
in the web.config file of the server.

To register a Web Part assembly as a SafeControl

1. Open RootDrive :\Inetpub\wwwroot\wss\VirtualDirectories\80


\web.config in Visual Studio .NET or Notepad.
2. Add the following line in the <SafeControls> block:

16 | P a g e
<SafeControl Assembly=" WPPartList, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=e499361e1f510dbc" Namespace="WorkflowStudios"
TypeName="*" Safe="True" />

Note: Replace the PublicKeyToken value (e499361e1f510dbc) with the


actual PublicKeyToken value for your Web Part's assembly.

To get the PublicKeyToken value of our assembly

1. Go to the RootDrive:\WINDOWS\assembly folder.


2. Look for the assembly WPPartList.
3. Right click on the assembly WPPartList and select Properties.
4. Select and copy the value against Public Key Token

Note: Every time you register a Web Part as SafeControl, you will need to
restart the IIS Server.

To restart IIS Server

1. In Windows, go Start > Run.


2. Type iisreset
3. Click OK.

17 | P a g e
Import your Web Part into a Web Part Page

To use and test our Web Part, we first need to import it into SharePoint site and
then use it in the Web Part Page.

To import your Web Part

1. Login to SharePoint site (http://localhost) with user account having


Administrative Rights. Probably this is the Windows user account you used
to install SharePoint Server.
2. Click on the button in the top right corner.
3. Select menu Site Settings > Modify All Site Settings.

18 | P a g e
4. In the Site Settings page, under Galleries, click on the link Web Parts.

5. Click on the New button in the menu bar.

19 | P a g e
6. Now in the page Web Part Gallery: New Web Parts, locate our Web Part.
Mostly it will be the last of all Web Parts. (If it is not listed, try restarting IIS
server once again)

7. Click on the button Populate Gallery at the top.

To use the Web Part in Web Part Page

1. Open the SharePoint site (http://localhost) or any Web Part page you already
created.
2. Click on the button to drop down a menu.

20 | P a g e
3. Select Edit Page.
4. Click on Add a Web Part.

21 | P a g e
5. Look for PartAdd Web Part and select it.

6. Click the button Add.

7. Now click on the Exit Edit Mode below Site Actions button.

22 | P a g e
3. Test your Web Part

To use the Web Part

1. Enter some values in the text boxes.


2. Click on the button Save Part Information.
3. Check the list PartInfo, the record is added.

23 | P a g e
24 | P a g e

You might also like