Click here to Skip to main content
1,146 members
Articles / Security / ASP.NET
Posted 12 Apr 2012



Getting started with SharePoint 2007 Web Parts

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
12 Apr 2012CPOL
Four important aspects of SharePoint 2007 Web Part development


Writing SharePoint Web Parts is one of the best ways to customize the SharePoint platform. Web Parts combine the power of ASP.NET with the flexibility of Web Part Pages. This article is intended to help you get going quickly with Web Part development.

We briefly cover four topics in Web Part development:


Knowledge of SharePoint, ASP.NET and Visual Studio is required.

Creating the Visual Studio SharePoint development environment

In this section the steps to setup your development are covered. If you already have a working dev environment then you can safely skip this section.

In order to follow these steps you will need Visual Studio 2005 (.NET 2.0) or later. You will also need network access to a Windows 2003/8 server with SharePoint 2007 (WSS or MOSS) - SharePoint does not run on XP or Vista. I usually use a Windows 2003 Virtual PC with .NET 3.5 and Windows SharePoint Services 3.0. One can also install Visual Studio 2005/8 on the development server.

We assume you have administration rights on your SharePoint server and also administration rights in your target SharePoint web application.

The steps to setting up your Visual Studio Web Part development environment are as follows:

  1. In Visual Studio, create a new class library
  2. Add a reference to System.Web

  3. In this step we create a simple Web Part that prints "Hello World!" to the screen. A Web Part is a class that inherits from the WebPart class in System.Web.UI.WebControls.WebParts. In order to control the rendering of the Web Part one overrides the Render method. An HtmlTextWriter instance is passed into the Render method and can then be used to write markup to the page output. The code below is an example of this:
      1  using System;
      2  using System.Collections.Generic;
      3  using System.Text;
      5  using System.Web;
      6  using System.Web.UI;
      7  using System.Web.UI.WebControls;
      8  using System.Web.UI.WebControls.WebParts;
     10  namespace ExampleWebPartLibrary
     11  {
     12      public class MyWebPart : WebPart
     13      {
     15          protected override void Render(HtmlTextWriter writer)
     16          {
     17              writer.Write("Hello World!");
     18          }
     20      }
     21  }
  4. Using Visual Studio or another suitable tool, give your class library a strong name key and get the full name of your assembly. You can get the fullname by using "gacutil /l" in the Visual Studio Command Prompt or by using Lutz Roeder's .NET reflector.
  5. In your class library properties, set the build output path to the bin directory of your SharePoint development web application. I usually share the directory on my development server as "\\SharePointDev\wss_bin" and use this directory as my build output directory. In Windows SharePoint Services 3.0 the bin directory is usually of the form "C:\Inetpub\wwwroot\wss\VirtualDirectories\[Port Num]\bin" and I share this directory as "wss_bin".

  6. Add the code statements using System.Security; and [assembly: AllowPartiallyTrustedCallers] to your AssemblyInfo.cs file.
  7. Ensure that your class library builds and that Visual Studio places the DLL in the expected location on the server
  8. In the web.config file on your target server, you need to add the assembly as a safe control. You can copy one of the existing safe control entries and fill that in with the details of your assembly. You will need the full name of the assembly to complete this step.
        Assembly="ExampleWebPartLibrary, Version=, Culture=neutral, PublicKeyToken=db485f68ad2dc0c5" 
        TypeName="*" Safe="True" AllowRemoteDesigner="True" />
  9. You can now add the web part library to your SharePoint site. To do this, log in as an administrator and go to the settings page. Click on "Web Part Gallery" under the "Galleries" section. Click "New" and you should see your web part in a list. Select your web part and click "populate gallery".

  10. You can give your web part a friendly title and control its permissions using the edit button in the web part gallery. I have chosen to call the Web Part "My Web Part".
  11. Finally you can add the web part to a web part page and you should see the web part's hard coded "Hello World!" message.

If your build target is set to the SharePoint bin directory as per step 5 in the list above, then you won't have to redeploy when you want to test changes. Each time the class library is rebuilt, you can test the latest version of your Web Part by refreshing your Web Part page.

You also do not need to repeat the above steps whenever you add a new web part to the library. Each time you add a new web part to the library you simply need to "Populate Gallery" with your new web part.

Remote debugging can be used to debug the Web Part. We won't go into that here; the MSDN library has an article about this.

Using ASP.NET controls in your web part

In Web Part development you don't have the luxury of Visual Studio's code generation for ASP.NET. You have to declare, initialise, configure and render the controls yourself in the correct phases of the Web Part life cycle. In this example we will create a button and a label and use the button press event to change the label text.

Controls should be declared as member variables and then initialised and configured within an override of the CreateChildControls method. I usually create a separate method to setup each control and then invoke that method from CreateChildControls. It is important to add the created controls to the list of Web Part controls. If a control is not added to this list then it's events won't be raised on post back.

  1  private Button btnDemo;
  3  private void createBtnDemo()
  4  {
  5      btnDemo = new Button();
  6      btnDemo.Text = "Click me";
  7      btnDemo.Click += new EventHandler(btnDemo_Click);
  9      // This line of code is required to trigger the click event
 10      Controls.Add(btnDemo);
 11  }
 13  protected override void CreateChildControls()
 14  {
 15      base.CreateChildControls();
 16      createBtnDemo();
 17      createLblHelloWorld();
 18  }

The controls are rendered inside the Render method override. This method can be used to layout the web part it's controls. The HtmlTextWriter has many useful methods to help out, including WriteBreak() which writes a "<br />".

  1  protected override void Render(HtmlTextWriter writer)
  2  {
  3      writer.WriteBreak();
  5      lblHelloWorld.RenderControl(writer);
  7      writer.WriteBreak();
  8      writer.WriteBreak();
 10      btnDemo.RenderControl(writer);
 11  }
Note: A known work around to the problem of not having Visual Studio support for Web Part development is to embed UserControls in the Web Part. You can read about that in this Code Project article.

Accessing SharePoint data in your web part

There are two steps you need to take in order to access SharePoint data from within your web part. The first is to reference Microsoft.SharePoint.dll. You can get a copy of this DLL from your SharePoint server by browsing to the directory "[Program Files]\Common Files\Microsoft Shared\web server extensions\12\ISAPI".

The second step is to take care of the code access security for your web part. The easiest way of doing this is to set the target SharePoint site's trust level to "Full". This level of trust is generally acceptable in an Intranet environment. If you require that the SharePoint site be run in a minimal or medium trust level environment then you will need to configure your code access security manually.

To take the easy way out and set the site trust level to "Full" find the following in your site's web.config file:

<trust level="WSS_Minimal" originUrl="" />

Now change this to:

<trust level="Full" originUrl="" />

Now you can write some code to access SharePoint data. This is just a question of learning and understanding the SharePoint API, which is worthy of several articles in its own right. Here I show a simple web part that displays the name of the presently logged in user:

  1  using System.Web.UI.WebControls.WebParts;
  2  using Microsoft.SharePoint;
  4  namespace ExampleWebPartLibrary
  5  {
  6      public class HelloUser : WebPart
  7      {
  8          protected override void Render(System.Web.UI.HtmlTextWriter writer)
  9          {
 10              // Get a contextual reference to the current SPWeb
 11              SPWeb currentWeb = SPContext.Current.Web;
 13              // Write a message to the current user
 14              writer.Write("Hello " + currentWeb.CurrentUser.LoginName);
 15          }
 16      }
 17  }

SPContext.Current.Web is the starting point for accessing SharePoint data. For example you can use it to access data in lists and document libraries.

Using SharePoint settings to manage your Web Part


Web Parts will invariably need settings in order to be useful. There are two ways of providing your web parts with settings in run time. In a bespoke environment it may be acceptable to place the settings in the web.config and access them in the same way as you would for standard ASP.NET applications. However if you require that users be able to easily configure and manage the web part themselves, then you need to use the SharePoint API to give the web part settings. This will almost certainly be the case if you are an Independent Software Vendor making a packaged release of your Web Part.

Fortunately it's quite easy to settings-enable your web part. The following steps assume you are starting with an existing web part, but you can skip to the listing at the end of the article if you are starting from scratch.

  1. Add the required using statements
      1  using System;
      3  using System.ComponentModel;
      4  using System.Runtime.InteropServices;
      5  using System.Xml.Serialization;
      7  using Microsoft.SharePoint;
      8  using Microsoft.SharePoint.WebPartPages;
  2. Change your web part to inherit from the Microsoft.SharePoint.WebPartPages.WebPart
  3. Create a new guid for your web part. Add the Guid and XmlRoot attributes to your Web Part as follows:
      1  [Guid("692b5ada-2f4c-45b0-b9a5-e718db958ae6")]
      2  [XmlRoot(Namespace = "ExampleWebPartLibrarySettingsDemo")]
      3  public class SettingsDemo : Microsoft.SharePoint.WebPartPages.WebPart
  4. Add the different attributes applied to the property that is used as a setting. Adjust the constant string attribute arguments according to your needs.
      1  private string mySetting;
      3  // SharePoint setting with required attributes
      4  [Browsable(true),
      5   Category("Example Web Parts"),
      6   DefaultValue("Default"),
      7   WebPartStorage(Storage.Shared),
      8   FriendlyName("MySetting"),
      9   Description("An example setting")]
     10  public string MySetting
     11  {
     12      get { return mySetting; }
     13      set { mySetting = value; }
     14  }
  5. Using the setting in code (in this case, the render method).

The complete code listing is as follows:

  1  // using statements required for settings
  2  using System;
  4  using System.ComponentModel;
  5  using System.Runtime.InteropServices;
  6  using System.Xml.Serialization;
  8  using Microsoft.SharePoint;
  9  using Microsoft.SharePoint.WebPartPages;
 11  namespace ExampleWebPartLibrary
 12  {
 13      //Guid and XmlRoot attributes for a settings enabled web part
 14      [Guid("692b5ada-2f4c-45b0-b9a5-e718db958ae6")]
 15      [XmlRoot(Namespace = "ExampleWebPartLibrarySettingsDemo")]
 17      // NB inherit from SharePoint WebPart rather than ASP.NET Web Part
 18      public class SettingsDemo : Microsoft.SharePoint.WebPartPages.WebPart
 19      {
 20          private string mySetting;
 22          // SharePoint setting with required attributes
 23          [Browsable(true),
 24           Category("Example Web Parts"),
 25           DefaultValue("Default"),
 26           WebPartStorage(Storage.Shared),
 27           FriendlyName("MySetting"),
 28           Description("An example setting")]
 29          public string MySetting
 30          {
 31              get { return mySetting; }
 32              set { mySetting = value; }
 33          }
 36          // use the setting in code
 37          protected override void Render(System.Web.UI.HtmlTextWriter writer)
 38          {
 39              writer.Write("Value of MySetting: ");
 40              writer.Write(mySetting);
 41          }
 43      }
 44  }

Further reading


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Gavin Sinai
Technical Lead Optalitix
United Kingdom United Kingdom
This member doesn't quite have enough reputation to be able to display their biography and homepage.

Comments and Discussions

-- There are no messages in this forum --