How To: Create a Generic WebPart in Sharepoint

Creating Generic Web Parts

This article explains the mechanics of Generic Webpart and demonstrates how to build a Generic Webpart. The document explains the steps required in simple terms. The document is intended to help a beginner, in SharePoint Customization.

Before going deep into Generic Web Part development, we should understand the need of customization in Sharepoint and the situation in which we will go for customization. As per the best practices for Sharepoint, it is better to go for Sharepoint Development only if the ratio between the "Out of Box" features (Sharepoint Default Features) and customization is 80/20.

Customization should be taken into consideration only when none of the "Out of Box" features matches the user requirement. For ex: In a banking site, you need to calculate the monthly compound interest for a customer based on the minimum amount in a month. These kinds of scenarios are suitable to go for Customization.

What can be customized in Sharepoint?

Almost every aspect of the SharePoint implementation can be customized, including applications, look and feel, and web parts. Some of the more commonly implemented customizations are identified in the Table 1 below.

 

Table 1: Customization Types in Sharepoint

Customization Type

Customization Elements

Look and Feel

Themes, Master Pages, Page Layouts, Logos

Web Parts

Web part pages and new Web parts

Workflows

Customize existing workflows, No-Code Workflows, Coded Workflows

Features

Custom Capabilities

Forms

Browser accessible forms, No-Code Forms, Coded Forms

Search

Search Scopes, Keywords

 

One element of SharePoint that cannot be customized is the SQL Server database.

As you can see in the Table 1 above, most Sharepoint customizations can be created in three different ways.

  1. User customizations using standard SharePoint capabilities.
  2. No-code customizations using SharePoint Designer.
  3. Coded customizations using Visual Studio or ASP.Net applications

Creating Custom Web Parts Using WSS3.0 Web Part Template:

Microsoft Visual Studio 2005 extensions for Microsoft Windows SharePoint Services 3.0 include project templates that enable us to jumpstart our development work for the Windows SharePoint Services environment.

Creating a New Web Part Solution

The Web Part project template included in the extensions is customized especially for creating Web Parts for the Windows SharePoint Services environment.

To create a new Web Part solution

1.       Open Microsoft Visual Studio 2005.

2.       On the File menu, click New, and then select Project.

3.       In Project types, select Visual C#, and then select SharePoint.

Note: Currently, the extensions Web Part template supports only Microsoft Visual C#.

4.       In Templates, select Web Part.

5.       Specify a new name, location, or solution name for the Web Part, and then click OK. The extensions create a new Web Part solution project, which includes the following:

i)        References to the necessary DLLs

ii)       AssemblyInfo.cs, a file that enables us to specify company and product information for the Web Part assembly, and version information

iii)     Temporary.snk, a temporary signature key file for the Web Part assembly

Note: This temporary signature key file is only for development purposes. We must generate our own permanent signature key file when our Web Part assembly is ready for production.

iv)     A folder named "Web Part1" which contains three files:

a)      A Webpart1.cs file

b)      A Webpart1.xml file

c)       A Webpart1.webpart file

6.       Delete the folder named "Webpart1" from the project.

7.       In the Solution Explorer right click the newly created Web part project and select Add | New Item.

8.       In the Categories area of the Add New Item dialogue box select SharePoint and in the Templates area select Web Part.

9.       Give a suitable name to the Web part and click Add.

10.   Right click the Web part project and select Properties. The Project Properties will be displayed.

11.   Select the Debug tab.

12.   Set the Start URL to a valid URL of the site on which you want to deploy your Web part. This is used by VSeWSS to determine the location of SharePoint when deploying the solution.

13.   Open the .webpart file and change the Title and Description as desired.

14.   Now code the .CS file for the controls as desired.

15.   Build the project and deploy the web part to the location defined in step 12.

Example of a Generic Web part Code

The following example explains the use of Interest Calculation Generic Web Part, which calculates Simple as well as Compound Interest:

1.       Open a web part project as explained in steps above.

2.       Change the .webpart file with desired Title and Description. As highlighted in Snippet 1.

 

<?xml version="1.0" encoding="utf-8"?>

<webParts>

 <webPart xmlns="http://schemas.microsoft.com/WebPart/v3">

  <metaData>

<!-- The following Guid is used as a reference to the web part class,and it will be    automatically replaced with actual type name at deployment time.-->

 <type name="50c93264-0f34-49c7-ac6d-b8f8f28648b2" />

 <importErrorMessage>Cannot import MyGenericWebPart Web Part.</importErrorMessage>

  </metaData>

  <data>

   <properties>

    <property name="Title" type="string">MyWebPart</property>

    <property name="Description" type="string">This is a intrest calculating               webpart.</property>

   </properties>

  </data>

 </webPart>

</webParts>

Snippet 1

3.       In the .CS file CreateChildControl method will resemble the code, as in Snippet 2.

protected override void CreateChildControls()

    {

   base.CreateChildControls();

  

   // TODO: add custom rendering code here.

   Label label = new Label();

   label.Text = "My Generic Web Part";

   this.Controls.Add(label);

   }

Snippet 2

4.       The next step is to add properties to the Web part. Write the code as in Snippet 3 in the Web part Class.

 

  private double _principal=10000;

   public double Principal

   {

     get { return _principal; }

     set { _principal = value; }

   }

  private double _rateofinterest = 5;

   public double RateofInterest

   {

     get { return _rateofinterest; }

     set { _rateofinterest = value; }

   }

  private double _time = 2;

   public double Time

   {

     get { return _time; }

     set { _time = value; }

   }

Snippet 3

5.       In order for SharePoint to display the Web part property for user modification, you must add few attributes to the properties, before that add the following using  statement on the top of the .CS File:

 

using System.ComponentModel

Snippet 4

6.       Also you will have to add the attributes to the properties as shown in Snippet 5:

[WebBrowsable(true),

Personalizable(PersonalizationScope.User),

WebDescription("Enter the principal amount"),

Category("Custom Properties"),

WebDisplayName("Principal")]

   public double Principal

   {

get { return _principal; }

set { _principal = value; }

   }

 

[WebBrowsable(true),

Personalizable(PersonalizationScope.User),

WebDescription("Enter the Rate of Interest"),

Category("Custom Properties"),

WebDisplayName("Rate of Interest")]

   public double RateofInterest

   {

        get { return _rateofinterest; }

        set { _rateofinterest = value; }

   }

Snippet 5

7.       Set the attributes for all the properties that you want to be modified by the user.

8.       The description of the attributes used is shown in the table below:

Table 2: Attributes of Properties and their Description

Attribute

Description

WebBrowsable(true)

This is used to allow Editing of the Web Part property. Without this the property will not be displayed in the Web Part task pane.

WebDisplayName ("…")

This attribute defines the text that is used to label the property in the Web Part task pane.

Personalizable(PersonalizationScope.User)

User scope means that personalized data will be user-specific.

WebDescription ("…")

This is an optional attribute and can contain anything you define. The description is displayed as a tooltip when hovering over the property in the Web Part task pane.

Category ("…")

This optional attribute is an organizing mechanism, defining where the property should reside in the Web Part task pane of SharePoint and also providing a grouping strategy for logically related properties. The default category is Miscellaneous.

 

9.       The final CreateChildControl method will resemble the following code:

protected override void CreateChildControls()

{

     base.CreateChildControls();

     // TODO: add custom rendering code here.

     Label label = new Label();

     if (string.IsNullOrEmpty(Name))

     {

        Name = "Guest";

     }

 

     if (InterestType.ToString().Equals("SimpleInterest"))

     {

        Amount = Principal + ((Principal * RateofInterest * Time) / 100);

     }

     else

     {

        //Code for Compound Interest. Omitted for brevity

     }

     label.Text = string.Format("Hello {0}, the amount for your principal Rs.{1} with {2} of {3}% for {4} years is {5}", Name, Principal, InterestType, RateofInterest, Time, Amount);

 

    label.ForeColor = Color.FromKnownColor(Mycolor);

    this.Controls.Add(label);

    }

Snippet 6

10.   Deploying and testing the web part: The steps to deploy and test the web part are as follows-

a)      Right click the web part project and select "Properties".

b)      In the project properties window select the "Debug" tab and set the "start browser with url" to http://myserver/  (Note: The path is one where the web part will be deployed).

c)       Build and deploy the web part by right clicking the web part  project and selecting "Deploy".

d)      The status bar should display "Deploy Succeeded".

e)      Navigate to the Sharepoint site you provided in step 10(b).

f)       Select Site Actions|Edit Page located on the top right corner of the page.

 

Site Actions.JPG

    Figure 1

g)      Click Add a Web Part at the top of the Left Web Part zone.

 

AddWebPart.JPG

Figure 2

 

h)      Scroll to All WebParts|Miscellaneous|My WebPart and tick the check box.

 

AddwebpartDialog1.JPG

Figure 3

i)        Click Add. The selected WebPart will be added to the page displaying the default message.

 

Default Look.JPG

Figure 4

j)        To edit the webpart click "Edit" and select "Modify Shared Web part".

 

Edit.JPG

Figure 5

k)      In the webpart task pane that appears, expand the "Custom Properties" section.

 

       Custom Properties1.JPG

Figure 6

 

l)        In the text boxes fill the desired text, choose the Type of Interest you want to calculate and Text Color.

m)    Click OK and web part will display the modifications.

 

Output.JPG

Figure 7

 

This completes the example of how to create a Generic Web Part.

 

Summary

 

In this article, we explored how we can create a Generic Web Part, which could be used across various applications in Sharepoint. A Generic WebPart helps the developer where there is a need of slight modifications and uses it in a different way, as discussed in the example. The web part can be used for Simple Interest Calculation as well as Compound Interest Calculations.

Up Next
    Ebook Download
    View all
    Learn
    View all