Welcome!

.NET Authors: Liz McMillan, Peter Silva, Yakov Werde, Matthew Pollicove , Kevin Benedict

Related Topics: .NET

.NET: Article

Developing Web Parts Using the SharePoint Object Model

Reaching into SharePoint's infrastructure

Since the first article ("Developing Web Parts") in this series appeared in July 2003 (Vol. 1, issue 7), Microsoft Office SharePoint Portal Server 2003 (SPS) and Microsoft Windows SharePoint Services (WSS) have been launched as part of the Microsoft Office System. After the successful launch and much adoption, SharePoint products and technologies have allowed collaboration to become a large part of distributed applications in a simplified way. While SPS and WSS can add much value with Web parts included in the product, the ability to create customized Web parts adds the flexibility to meet customer's specific needs.

This article will focus on using the SharePoint object model to reach into SharePoint to connect to information contained within its infrastructure. Accessing the object model allows developers to connect and collect information in new ways. The article will also discuss how to create a custom Tool Part that allows users or administrators to customize the display and functionality of a Web part.

Object Model
One look into the SharePoint object model and your first impression is likely that it is massive. One of the best aspects of this object model is that it exposes most classes, properties, and methods used to create SPS and WSS. This means that anything that you can do using the application and administrative interfaces within SharePoint can be done using the object model. The only drawback is that it can be difficult to find the correct method, but that makes the SharePoint SDK an invaluable resource to search through the all the available classes. The bottom line remains that the developer is empowered to do virtually anything because everything is exposed through a selective subset.

The SharePoint object model is written entirely in .NET managed code using C#, and Web parts are slight variations of ASP.NET server controls. This means that the object model is easily accessible via ASP.NET or any other server process.

A look at one of the Web parts that comes packaged within WSS demonstrates how a part interrogates the object model to display information to the user. Take the "Shared Documents" Web part for example. This part lists metadata about documents that users have created or uploaded to a given site. The part uses the GetItemsInFolder method of SPDocumentLibrary class. The definition for the GetItemsInFolder is:

public SPListItemCollection GetItemsInFolder(SPView view, SPFolder folder);

Once we know we can get all the items in the folder, it is relatively trivial to make the necessary connections to execute the method. The code in Listing 1 demonstrates how you get the current site, navigate to the document library, and then display the document names. It shows how the SharePoint developers use the object model to create a simple yet very powerful Web part.

Before writing our own Web part, I would like to illustrate some of the other common tasks that can be performed by accessing the object model. Say that a department head is frustrated because she has little insight into her staff's activities. You can respond to that need by creating a Web part that looks at all of the meeting workspaces that have been created by the staff for the last week and display them in a consolidated view. The department head can see who contributed to the meetings and browse to find more status on outcomes or action items.

Another powerful use for the object model involves handling events within document libraries. Previous versions of SharePoint Portal Server had an implementation of document workflow. While some miss the built-in workflow, document library events offer a flexible way to create workflow. If you have handled events in .NET before, then writing a handler for these events will be very similar. The events that you would expect are exposed, including Check In, Check Out, Insert, Delete, and Update, but there are more. Listing 2 shows a very simple event handler that sends an e-mail to a user when a new document is created.

"Sub Webs" Web Part
After creating many sites underneath a WSS or SPS, it can be easy to lose track of the sites that have been created, especially if many people have access to create sites. The "Sub Webs" Web part was created to drag the part onto a page to list sites, document workspaces, and meeting workspaces that exist below the current page. The part also displays metadata such as author, date created, and number of items for each of the sites. It was puzzling to many people that this capability did not ship within the product, but it gives us a chance to develop it.

The main goal of the "Sub Webs" Web part is to simply list the sites underneath the current page. Using the object model, this is a relatively trivial task to accomplish. In fact, once the Web context is retrieved, it is simply one method call to access a collection of the Webs beneath the current site.

In Listing 3, the first two lines of code in the GetSubWebs method do a lot of work. First, retrieving the Web context reaches into the current HTTP request, determines the location, and returns an object that represents the current Web. Once the SPWeb object is returned, the GetSubwebsFor CurrentUser method is called to retrieve only the Webs to which the user that is executing the Web part has access.

The SPWebCollection implements the ICollection interface that allows us to loop through the results using a foreach statement. The SPWeb object has many properties that describe the Web, which will be used to populate the metadata to be displayed to the user. The example in Listing 3 shows the enumeration of the Sub Webs and exposing the properties in an HTML table. For readability, much of the table formatting has been eliminated and only a subset of the properties are displayed. The code available with this article shows the Web part in full fidelity.

The sample code in Listing 3 shows how to retrieve four pieces of metadata from each of the Sub Webs. It is possible to retrieve more data; within the full Web part there are 10 fields that can be displayed to the user. Figure 1 shows the "Sub Webs" Web part and some of the additional fields that are displayed to the user.

Tool Part
Another powerful aspect of Web parts is giving the user or an administrator the ability to customize the display and functionality of the Web part. In the case of the "Sub Webs" Web part, customization allows anyone that can edit the part to choose which fields are displayed. All Web parts have a default configuration associated through the tool part. The tool part is displayed each time a user clicks on the "Modify Web part" menu option. This opens up the tool part and allows modification of the Web part name, size, and other options common to all Web parts.

It is possible to create custom options that go far beyond the default options of the tool part. There are two steps to adding a custom tool part. The first step is to create a new class that inherits from the ToolPart class and then override the CreateChildControls, ApplyChanges, and RenderToolPart methods. This procedure looks very similar to creating a new Web part, and it should, because the tool part is just another Web part with added functionality, such as the ability to apply changes.

In Listing 4, the SubSitesToolPart class uses the CreateChildControls method to create a label and two checkboxes to display configuration options to the user. If the user checks a checkbox, that will signal the Web part to display the respective field such as the description or URL. The initial values are pulled from the values set within the Web part's properties. The ApplyChanges method is the mechanism that sets the values of the properties with the Web part with what the user has selected in the tool part. Finally, the RenderToolPart method is responsible for rendering all of the controls and displaying the custom tool part.

Once the custom tool part is completed, we must tell the Web part that it can be used. This is accomplished by overriding the GetToolParts method within the Web part class. The GetToolParts method takes an array of objects that implement the WebPart base class. In this case, we create an instance of the custom tool part as well as an instance of the default tool part and pass it to the method. This creates all of the custom UI that we want to be displayed to the user as well as the entire default configuration for the Web part (see Listing 5).

When a user modifies a Web part in edit mode, they will receive a tool part as displayed in Figure 2.

Conclusion
Using the SharePoint object model with Web parts is a powerful way to connect users to information contained within the SharePoint site. The object model is comprehensive and allows a developer to do anything that can be done via the Web or administrative tools. In addition, this article demonstrated how to develop a tool part to allow users or administrator to configure a Web part. Both of these technologies are integral to developing quality Web parts.

More Stories By Ben Waldron

Ben Waldron is a developer consultant focusing on .NET and SharePoint products and technologies for Microsoft Consulting Services, based in Washington, D.C. He is a Microsoft Certified Solution .NET Developer (MCSD .NET) and is responsible for design, development, and deployment of enterprise-scale applications using .NET and SharePoint technologies. Ben also teaches classes in .NET and Web service development for Microsoft partners.

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.