Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

.NET

SharePoint Web Part Development


April, 2005: SharePoint Web Part Development

Making collaboration a reality

Seth is a software architect and practice manager at DataLan Corp., the 2004 NY/NJ Microsoft Platform Partner of the Year (http://www.datalan.com/). He can be reached at [email protected].


With the release of Windows 2003, Microsoft introduced Windows SharePoint Services (WSS)—a web-based team collaboration and document management platform. WSS (http://www.microsoft.com/sharepoint/) lets you create team sites for collaborating on documents, managing tasks, tracking issues, and the like. Features include document management tasks, such as check-in, check-out, versioning, and content approval. Customizable lists provide the basis behind storing information including tasks, issues, events, or other custom data pertinent to site users.

While you can quickly create hundreds of sites when deploying WSS, there's no easy method for allowing users to see what sites exist or search for pertinent sites. Microsoft addressed this problem by developing SharePoint Portal Server 2003 (SPS), a specialized set of WSS sites for browsing or searching existing sites. It also enhances user experiences through the use of audiences that can target content to those users who would most be interested in that content. Additionally, SPS lets users customize a "My Site" to store documents and data for personal use. SPS works well when developed as a company intranet, acting as the entry point in which users can manage their tasks, documents, and information, as well as locate WSS sites for teams or projects that they are involved in.

Customizing SharePoint

A major asset to SharePoint is the ability to customize both its functionality and appearance. Physical web pages do not exist on the SharePoint server. Instead, all site information is stored in SQL Server. Additionally, all documents, files, and list data are stored in SQL. When users request a page, the SharePoint engine uses the data in SQL, along with a specialized form of XML called "Collaborative Application Markup Language" (CAML), to generate the page content. You can use FrontPage to change the layout and content of SharePoint sites, as well as modify the CAML files themselves, which are located on the SharePoint server.

The third major way to customize SharePoint—and what I focus on in this article—is creating custom web parts, functional building blocks for creating a useable SharePoint page. For instance, SharePoint comes with web parts that let it display an external web page, HTML content, document, and list data—even your Microsoft Outlook Web Access Inbox or Calendar.

Creating Web Parts

Web parts are created using Visual Studio .NET and are similar to a Web Control Library project. (A template project for creating web parts can be downloaded from Microsoft at http://www.microsoft.com/downloads/details.aspx?familyid=CAC3E0D2-BEC1-494C-A74E-75936B88E3B5.)

It is easiest to do web part development on a server with WSS installed because the projects need references to the SharePoint DLLs and there is no programming SDK available. After you have downloaded and installed the templates on your development machine, start Visual Studio .NET and select Create a New Project. A new project template entitled "Web Part Library" appears under both Visual Basic Project and Visual C# Project types.

For this article, I create a web part that searches the publication database and displays results in a DataGrid control in the web part (the complete source code and related files are available electronically; see "Resource Center," page 5). Select the Web Part Library Project template under the Visual Basic project type, name it PubsSearch, and click OK. When created, the project includes a reference to the SharePoint object model. Files worth noting are WebPart1.vb (where you implement the web part); WebPart1.dwp (used to later import the web part into SharePoint); and AssemblyInfo.vb (used to properly configure security concerns).

Unfortunately, there is no visual designer for creating web parts, and creating controls, setting control properties, and determining how the web part should look is done via code. To display your web part, you must override the RenderWebPart method. This method contains a single HtmlTextWriter parameter that renders the contents of the web part (as HMTL) to the SharePoint page; see Example 1.

This approach is fine for simple web parts without child controls such as text boxes, DataGrids, or dropdown lists. However, to include these child controls in a web part and handle their events, you must override the CreateChildControls method to initialize the controls and add them to the web part's Controls collection; see Example 2. Admittedly, this approach is more tedious because you can't know for sure if what you've coded is visually correct until after you compile, deploy, and test the web part. The difficulty increases with an increased number of child controls. Consider the amount of coding necessary for a web part that requires dozens of child controls. Moreover, DataGrids and other .NET controls have visual property dialogs that are useless in this approach. For these instances, you need an alternative.

Easier Web Part Development with Web User Controls

An alternative approach is the use of Web User Controls, which lets you add multiple controls and their functionality into a single control that can then be added to a Web Form page or, in the case of SharePoint, a web part. For example, in the PubsSearch project, select Add Item from the Project menu. A Web User Control does not appear as an item that you can add to the project because the web part template does not have the necessary settings to let you add a Web User Control. You have to modify those settings. Save the PubsSearch project and close Visual Studio.NET. Add the Web User Control to the web part templates by opening the web part template file C:\Program Files\Microsoft Visual Studio .NET 2003\Vb7\VBProjectItems\Local Project Items\SharePointLocalProjects.vsdir in a text editor. Add this line to the list of project items that can be added to the project: ..\WebUserControl.vsz| |Web User Control|0|Web User Controls|{164B10B9-B200-11D0-8C61-00A0C91E29D5}|4544|0|WebUserControl.ascx. Save the file and open the PubsSearch project in Visual Studio .NET. Select Add New Item under the Project menu and verify that Web User Control is now displayed in the list of items that can be added to the project. Select the Web User Control, name it PubsDisplay.ascx as in Figure 1, and click Open. Using the Visual Studio toolbox, add a TextBox named txtSearch, a Button named btnSearch with text of Search, and a DataGrid named grdResults using the visual designer (see Figure 2).

Using a visual designer lets you modify the properties of complex controls such as the DataGrid and see results without having to compile and deploy each time. Right-click the DataGrid and choose Auto Format. Select a color scheme to make the header, footer, and items of the DataGrid easier to differentiate. You can also choose the Property Builder dialog from this menu to more precisely change DataGrid properties. Double-click the button to bring up the btnSearch.Click event handler in the code view. In the Web User Control code, you can use standard .NET code to handle the functionality for the web part. In this example, I use ADO.NET objects to retrieve a list of books, whose titles contain the text specified by the user, from the pubs database and bind the resulting data to the grdResults DataGrid control; see Example 3.

Lastly, you need to add code to the web part itself to load and display the Web User Control. There are several ways to do this, but the simplest is to create a private instance of a Control object in your web part class, then use the Page object's LoadControl method to load the Web User Control into the Control object instance. The LoadControl method takes a single parameter that specifies the path to the Web User Control file. You then add code to the RenderWebPart method to render the control (Example 4).

As you can see, this results in straightforward and easy to reuse code for the web part itself. This code can be enhanced to perform error handling and property management, while all of the functionality of the web part is contained in the Web User Control where you have the added benefit of a visual designer.

Deploying Web Parts

SharePoint requires that web parts be strongly named. A strong name gives an application a globally unique name, preventing confusion with another application that could run malicious code. Using strong naming, you are assured that another developer cannot alter your application without having the strong name key file you used to create the first version of the application. To strongly name a web part, you must create a strong name key file using the Strong Name tool that comes with Visual Studio .NET:

  • Open a Windows command window.
  • Change the directory to \Program Files\Microsoft Visual Studio .NET 2003\SDK\v1.1\bin.
  • Execute sn.exe -k c:\strongname.snk.

Once you have generated the strong name key, you reference it in the AssemblyInfo file of your web part to make the web part strongly named. The web part must also have a specific version number to properly use strong naming. Add an AssemblyKeyFile attribute to the AssemblyInfo file pointing to your strong name key, making sure the web part has a specific version number:

<Assembly: AssemblyVersion("1.0.0.0")>
<Assembly:
AssemblyKeyFile("c:\strongname.snk")>

One more thing to do before compiling the project is to edit the DWP file. For example, rename the DWP file to PubsSearch.dwp so that it more accurately describes the web part, then open it for editing. Change the title to "Pubs Search" and give it a description. Save all files and compile the web part project in Release mode.

Next, copy the necessary web part files to the SharePoint server. The custom web part DLL, PubsSearch.dll, should be copied into the bin directory of the SharePoint virtual server (for example, C:\inetpub\wwwroot\bin). This directory may need to be created. After copying the DLL to the bin directory, the web part's DWP file, PubsSearch.dwp, should be copied to the wpcatalog directory of the SharePoint virtual server (C:\inetpub\wwwroot\wpcatalog), which should also be created if it does not exist.

Because the development method used includes Web Form User Controls, the PubsDisplay.ascx User Control file must also be copied to the SharePoint server. Create a UserControls directory under the SharePoint virtual server (C:\inetpub\wwwroot\UserControls). Because SharePoint intercepts requests to files under the virtual server directory to process the pages from the content in the SharePoint SQL databases, you must explicitly exclude this directory from SharePoint control. Open SharePoint Central Administration (Start|Administrative Tools|SharePoint Central Administration) and click "Configure virtual server settings." In the Virtual Server List, click the virtual server where you placed the User Control file, usually "Default Web Site." On the Virtual Server Settings page, click "Define Managed Paths" under the Add A New Path section, enter "/UserControls" for the path, select the Excluded Path option, and click OK.

As an added security measure, SharePoint verifies that a web part is in the Safe Controls list of the virtual server's web.config file. This is referred to as "marking" the web part as safe. Without adding an entry into this list for the web part, SharePoint won't let you import it. Open the web.config file for the virtual server (C:\inetpub\wwwroot\web.config) in a text editor. The SafeControls section is where an entry must be added to allow the web part to be imported into SharePoint. The entry consists of the assembly name, version number, the strong name's public key, and the namespace and classes that are allowed. To retrieve the strong name's public key, again, use the Strong Name tool:

  • Open a Windows command window.
  • Change the directory to \Program Files\Microsoft Visual Studio .NET 2003\SDK\v1.1\bin.
  • Execute sn.exe -T c:\inetpub\wwwroot\bin\PubsSearch.dll.

Once you have the public-key token for your web part, add an entry in the SafeControls section:

<SafeControl Assembly=
"PubsSearch, Version=1.0.0.0,
Culture=neutral, PublicKeyToken=
<YOUR PUBLIC KEY TOKEN>
"Namespace=
"PubsSearch" TypeName="*"/>

Also set in the web.config file of the virtual server, the trust level determines what functionality a web part is allowed to execute. The trust level is used to determine the Code Access Security for the portal. Code Access Security (CAS) prevents malicious code from running on the server by determining what functional aspects, such as database connectivity and file-system access, can be utilized. The topic itself is too large to cover in this article, but you should know that SharePoint installs with various trust levels, each allowing a set of functionality for CAS. WSS_Minimal, the default trust level, prevents code from accessing SQL databases, file system, SharePoint object model, and other functionality. Because you are working in a test environment, set the trust level to Full so that you can access the pubs database. The Full trust level allows any access to all web parts in SharePoint and, therefore, should not be the trust level used in a production environment. The trust level can be found in the system.web section of the web.config file and looks like this:

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

The last step is to import the web part into SharePoint and add it to a page. Navigate to a SharePoint site using someone with permissions to add web parts, such as a user in the administrator site group. Click the Modify Shared Page link and select Add Web Parts|Import. Browse to the DWP file that you copied into the wpcatalog directory of the virtual server and select it. Click the Upload button and Pubs Search should appear in a list of uploaded web parts (Figure 3). Drag Pubs Search from the list of uploaded web parts to a web part zone on the page. Your web part should appear as in Figure 4 and you are ready to search the pubs database. Because the DWP file was added to the Virtual Server's wpcatalog directory, the web part now appears in the Virtual Server Gallery. The Virtual Server Gallery can be found by clicking the Modify Shared Page link and choosing Add Web Parts|Browse.

Conclusion

SharePoint provides the building blocks for creating customized collaboration and productivity web sites, and is increasingly being deployed at corporations and educational institutions world wide. There are numerous SharePoint development opportunities not discussed in this article including using the object model, creating connectable web parts, customizing the CAML, and more. Additional information regarding SharePoint can be found in Microsoft SharePoint: Building Office 2003 Solutions, by Scot Hillier (Apress, 2004); Advanced SharePoint Services Solutions, by Scot Hillier (Apress, 2004); and SharePoint 2003 Users Guide, by Seth Bates and Tony Smith, Apress (coming soon).

DDJ


Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.