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.
- Start your VS and create a new “Class Library”
-
Add a reference to the Microsoft.SharePoint.dll. We will create a SharePoint Webpart, to be able to add Properties.
- 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;
-
{
public class Class1:WebPart
{
protected override void Render(HtmlTextWriter writer)
{
writer.Write("I like SharePoint.");
}
}
}
- (optional) Rename Class1 to some better name like “simpleWebpart”. In the solution Explorer you can rename Class1.dll to simpleWebpart.dll
- Add [assembly: AllowPartiallyTrustedCallers()] to the AssemblyInfo.cs
-
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-
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
-
-
- Add [assembly: AllowPartiallyTrustedCallers()] to the AssemblyInfo.cs
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 = "" + ex.ToString();
Controls.Add(errorControl);
}
You can download the solution here.