Create a simple Webpart HOWTO

Create a simple Webpart HOWTO

In this blog post, I want to show you how to create a simple Webpart. All you need is a Visual Studio 2005 (e.g. the express version) and of course SharePoint.

  1. Start your VS and create a new "Class Library"
  2. Add a reference to the Microsoft.SharePoint.dll. We will create a SharePoint Webpart, to be able to add Properties.
  3. To display some text, override the render method. You have to create a reference to the Microsoft.Web.dll, and type using System.Web.UI;

namespace simple_Webpart_HOWTO

{

public class Class1:WebPart

{

protected override void Render(HtmlTextWriter writer)

{

writer.Write("I like SharePoint.");

}

}

}

  1. (optional) Rename Class1 to some better name like "simpleWebpart". In the solution Explorer you can rename Class1.dll to simpleWebpart.dll
  2. Add [assembly: AllowPartiallyTrustedCallers()] to the AssemblyInfo.cs
  3. Next, we will create a Key, to sign our Assembly and give it a strong name. Open the "Visual Studio 2005 Command Prompt" from the Startmenu.
    sn -k 1024 c:\temp\keypair.snk
  4. Add the created Keypair to your project, and configure it to be signed

    After you build your project, you can extract your public key token with:
    sn -T "C:\PathToYourProject\bin\debug\simple Webpart HOWTO.dll"
    In my case the token is 2e6fe95c9937e6f4

Caution:

  • ALWAYS put a try/catch block around your code, if it might generate an error. If you don’t, the whole page will display an error, instead of just your Webpart.

catch (Exception ex)

{

HtmlGenericControl errorControl = new HtmlGenericControl("DIV");

errorControl.Attributes.Add("style", "padding: 20px; margin: 20px; border-style: groove; background-color: #FFFFFF;");

errorControl.InnerHtml = "<IMG src=\"/_layouts/images/error16by16.gif\" border=\"0\"/>" + ex.ToString();

Controls.Add(errorControl);

}

You can download the solution here.

Leave a Reply