Introduction
I taught a week long SharePoint boot camp about a month ago for Microsoft Enterprise Customers that pretty much covered everything SharePoint. The first day dealt with Planning and Governance, days 2 and 3 went over Administration and Point&Click design, and Days 4 and 5 involved custom development.
Over the next month or so I plan to put up quite a few of the examples I used during the class, but today I want to go over how to get started with Web Parts and then build onto the topic in later postings. It is one of my favorite things to code in SharePoint and a good foundation will definitely make your life easier in the long run. You have to have some understanding of the Page Life Cycle to follow what is happening when, and hopefully after reading this you will be better equipped to go roll your own.
I will cover this topic in five small sections:
- The Page Lice Cycle
- The Web Part Life Cycle
- Tools to help make Web Parts
- The Hello World Web Part
- Adding functionality to your Web Part
Before I get started, I just want to point out is that Web Parts are not a SharePoint construct – they are simply an ASP web control. ASP web parts can be used in SharePoint and Web parts you make for your SharePoint site may be used in an ASP based web page (If you do everything correctly). We however will focus on SharePoint.
The Page Life Cycle
When a request is received for an ASP page, the .NET framework runs the page through a series of steps to initialize objects, analyze the request, view any state and post back information, handle any raised events and finally render the output. A solid understanding of the page life cycle will let you better understand what and when everything is happening. More importantly perhaps, it will let you understand where you need to put your code that it fits in correctly. Below are the 6 stages of the Page Life Cycle. Note that they are not official stages, but are being grouped logically here.
- Page Request
- Determines if the requested page is cached
- There are no methods to override at this stage
- Start up
- The Request and Response properties are set
- Determines if there is a new request or post back
- There are no methods to override at this stage
- Initialization
- Themes and Master pages are applied
- Controls are created in the Web Part’s OnInit() Method
- Client side scripts and connection strings are registered
- The OnInit() method for the page is invoked after each child control’s OnInit()
- Loading
- Properties that utilize the post back or view state are set
- Initial or default values are set in the OnLoad() Function
- The Page’s OnLoad() is invoked before each child control’s OnLoad()
- Rendering – 3 Sub Phases
- Pre-Render
- EnsureChildControls() and CreateChildControls() are called
- Note: All Controls should be added through CreateChildControls()
- OnPreRender() is called which is the last chance to edit the page
- OnPreRender() for the page is called which recursively calls each control’s
- Save State
- The View and Control States are created and saved
- Render
- All controls process their Render() method and generate HTML
- Unloading
- This is the final stage where open files and database connections are closed
- There are no methods to override at this stage
The Web Part Life Cycle
It is kind of hard to separate the Web Part life cycle from the Page’s as the Web Part runs within the context of the Page, but it helped me understand it when I tried to separate it out. You could also look at this little part as a summary of what is really important from the above section.
- Initialization Stage
- Web Part’s OnInit() is called BEFORE the Page’s OnInit()
- The SPWebPartManager loads and applies any personalization settings
- Loading Stage
- Web Part’s OnLoad() is called AFTER the Page’s OnLoad()
- Render Stage
- CreateChildControls() is called – Add your controls here
- OnPreRender() is called AFTER the page’s OnPreRender()
- RenderContents() is called
Tools for Web Part Development
So, now that we have a basic outline of when events occur in the life cycle of a web part, we need to start developing. There are a couple of tools that will definitely make your life easier that I highly recommend. The first one is Visual Studio Extensions for SharePoint which is a plug in for Visual Studio that has a web part template. The newest version (1.3) made some very good improvements and even lets you deploy a web part to the local bin folder instead of the GAC. This is the tool I will be using later in this segment and what I generally use for all of my web part projects.
The second tool you should look at is the SharePoint Dispose Checker Tool which scans your code for SharePoint Memory leaks related to improper Dispose calls. Run this before ever putting your SharePoint code into production – memory leaks are bad.
The Hello World Web Part
Note: You can download the project I go through below Here if you don’t want to follow along.
So, now that you have installed the Visual Studio Extensions for SharePoint, create a new Project and select SharePoint –> Web Part as the project template. This will give you a blank web part that has a webpart.xml file that defines properties on the web part, a .webpart file that further defines the web part and a c# file with the code for the web part.
The first thing we want to do is rename the webpart.xml file to the name you want your web part to have. It will ask you if you want it to change the name throughout the project, select yes. Next, open up the Webpart.xml file and modify the <file> tag as shown below. By adding the property tag to it, it allows us to group our web parts in the “Add New Web Part” dialog box sharepoint users will see when adding a web part to their page. An Image of how this will work is also shown below, showing one of my test servers and several web parts I have made listed under my custom group header.
<File Path=“HelloWorld.webpart" Url=“HelloWorld.webpart" Type="GhostableInLibrary">
<Property Name="Group" Value="Steve's Custom Web parts" />
</File>

Allright, now that we have a couple of things set up, lets add a little bit of code. Inside of the CreateChildControls method that was created for you, put the following line of code.
this.Controls.Add(new LiteralControl
("CreateChildControls"));
Then, paste in the following function.
protected override void RenderContents(HtmlTextWriter writer)
{
writer.Write("Render Contents");
}
So we now are adding a control to the CreateChildControls function which will be rendered in the web part, displaying “CreateChildControls”. But we also added a write statement to the RenderContents method… so what will happen? Will both print? Which one will print first? Deploy it and find out (or scroll down just a little bit). To deploy it, open the project settings and type in the url of your test server in the debug window. Then clicking deploy in the top tool bar and deploy solution, it will be installed on your server. Now go add it to a web part page like any other web part, easy as that.
So, that should have printed out “Render Contents”. Now, stick the following line of code at the very beginning of the Render Contents Method.
base.RenderContents(writer);
So now it should print out “CreateChildControlsRender Contents”. This is because before we did not include the base functions of the default RenderContents() method, which renders everything that was added in CreateChildControls(). This may seem useless, but it is important to understand what is being done where, and if nothing else, remember to call the base method when you override one.
Now, something that is very useful when developing web parts is to catch and display your error messages in the web part (Yes, you will make errors). To do so, we need to catch the error and then add it as a literal to the web part. Replace the contents of the CreateChildControls method with the following code to try it out.
try
{
SPSite site
= new SPSite
("http:\\badurl");
this.Controls.Add(new LiteralControl
("CreateChildControls"));
}
catch (Exception Ex
)
{
this.Controls.Add(new LiteralControl
(Ex
.Message));
}
This should produce the following error message, unless your web application happens to be named badurl.

That is actually very useful and I recommend to always do it, and then maybe remove it once putting your code into production. You could also put some friendly error message telling people to call IT if you see this message.
There is one other semi-cool thing I want to show you that can help when creating web parts. We are going to enable Tracing for the page on which the web part was added. This will show when each function was called and really helps track down bugs. To turn on tracing, paste the code below into the try of the constructor of the web part. Note that you will need to add trace statements like the one below to each of your methods for this technique to truly be helpful.
Context.Trace.IsEnabled = true;
Context.Trace.Write("WebPart", "Begining WebPartConstructor()");
Context.Trace.Write("WebPart", "EndingWebPartConstructor()");
Now redeploy the solution and scroll down in the page, pretty neat eh? Below is a screen shot of what mine looks like in case you don’t feel like trying it.

Well, at least I think page level tracing is cool. You can also turn it on for the entire site by modifying the web.config file, but that is another story.\
All good web parts have a custom editor in which you can specify any parameters or values you want. After all, web parts are supposed to be generic and reusable right? Below is the code you need to add an editor class to your project that inherits from the EditorPart class. The first thing to do is add a blank c# class file to the project. Add the first block of code below to it, erasing anything that may already be in the file. Then, add the second block of code to the main c# file.
using System;
using System.Runtime.InteropServices;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;
namespace WebPart2
{
class myEditor
: System.Web.UI.WebControls.WebParts.EditorPart
{
private TextBox _message
;
protected override void CreateChildControls
()
{
base.CreateChildControls();
_message
= new TextBox
();
Controls
.Add(_message
);
}
public override bool ApplyChanges
()
{
EnsureChildControls
();
HelloWorld webPart
= WebPartToEdit
as HelloWorld
;
if (webPart
!= null)
{
webPart
.myMessage = _message
.Text;
}
return true;
}
public override void SyncChanges
()
{
EnsureChildControls
();
HelloWorld webPart
= WebPartToEdit
as HelloWorld
;
if (webPart
!= null)
{
_message
.Text = webPart
.myMessage;
}
}
}
}
using System.Collections.Generic;
protected override void CreateChildControls
()
{
try
{
this.Controls.Add(new LiteralControl
(myMessage
));
}
catch (Exception Ex
)
{
this.Controls.Add(new LiteralControl
(Ex
.Message));
}
}
[WebBrowsable
(false)]
public string myMessage
{ get
; set
; }
public override EditorPartCollection CreateEditorParts
()
{
List
<EditorPart
> editorParts
= new List
<EditorPart
>();
myEditor editor
= new myEditor
()
{
ID
= this.ID + "_editorPart1",
Title
= "Test Editor"
};
editorParts
.Add(editor
);
return new EditorPartCollection
(editorParts
);
}
This may seem like a lot, but it really isn’t too difficult. Make sure that your namespaces match what your using in your project. Below is a screenshot of the working editor class, passing the value entered in the editor to the web part.

Now, if you look at the code in the Editor class, there are three main functions that you need. The apply changes is called when you click apply or ok and it does what it says, it applies the changes. The Sync changes kind of works the other way, pulling information from the web part into the editor class. You can also override the same render stage methods in the editor class that you can in the web part to make your editor look more custom if you like. Also take note of the one method we added to the web part class. All this does is add your custom editor to the web part. You can set a few fields here like the title and description, but that’s pretty much it. Also important to notice is the attributes we set on the myMessage string in the web part class. This is required for the editor class to be able to retrieve its value. If you remove the line directly above it and declare it like a normal string, every time the editor window is opened any value previously entered into it will be lost.
Well, I am tired… and I the code is pretty self explanatory. Feel free to ask any questions if I failed to explain something. I think I will go over verbs in another posting and then get into some cooler, more usable examples. Web Parts in SharePoint 2007 and WSS 3.0 are much easier to get started than people think, and I encourage you to give them a shot.
You can download the web part project I went over above here.