Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
The Definitive Hello World Web Part Tutorial (Jul 2004)

The Definitive Hello World Web Part Tutorial

Office 2003

This content is no longer actively maintained. It is provided as is, for anyone who may still be using these technologies, with no warranties or claims of accuracy with regard to the most recent product version or service release.

Summary:   Learn how to create and deploy a full-functioning Web Part for a Windows SharePoint Services site. In this article you will see how to accomplish each of the steps to take a Web Part from its earliest stages to being fully packaged for wide distribution. This article pulls together tips and instructions from many sources and ties them together in a seamless, step-by-step approach. (11 printed pages)

John R. Durant, Microsoft Corporation

July 2004

Applies to: Microsoft Windows SharePoint Services, Microsoft Visual Studio .NET

Contents

If you have been reading this column for the past year, you saw that I have created other articles with "Definitive Hello World" in the title. My purpose with these articles is to give developers a step-by-step approach to getting a basic solution up and running so they do not need to read several articles just to get started. With each subject (smart documents, research services, and now Web Parts) the learning curve can seem a little steep at first, and developers may not test the waters if they have to do too much homework just to get in the game. This article takes you into the world of Web Part development for Microsoft Windows SharePoint Services, giving special attention to packaging and deployment.

The Web Part that you create and deploy in this article lists recent Office Talk articles I published on MSDN. My intention is that you can modify it and start creating your own. It is assumed that you have a basic understanding of Windows SharePoint Services and the Web Part infrastructure.

You can create a Web Part from scratch with no template (you could even write it all in Microsoft Notepad), but this is like using a slide rule when you have a calculator sitting in front of you. Sure, it pleases the truly outdated purists, but it is not efficient. More realistically, you still may want to create them without a template when you require more advanced functionality. In the end, Web Parts are just custom server controls that you can manipulate in Microsoft Visual Studio .NET 2003.

Fortunately, you can get a Web Part started in Visual Studio .NET 2003 using the Web Part Templates for Visual Studio .NET, available as a free download from Microsoft. Once you install the templates you see the template appear in the project templates for either Microsoft Visual Basic .NET or Microsoft Visual C# .NET (Figure 1). When you select the template and create the project, Visual Studio creates a solution with a project containing some default files.

Figure 1. Using a template to start creating a Web Part

Using a template to begin creating a Web Part

The new project contains a reference to Microsoft.SharePoint dll and some Web Part-specific files. These include a Web Part package manifest and a .dwp file. A manifest file is a configuration file that is important for the final deployment of the Web Part package on the target server. A .dwp file is an XML file that contains instructions for how to instantiate an instance of a Web Part on a Web Part Page. It includes a reference to a Web Part's assembly, namespace, and class name, plus optional property settings for the Web Part. The project also includes the obligatory AssemblyInfo file and a code file with a main class for the Web Part project. Figure 2 shows the contents of the project after creation using the template.

Figure 2. The basic contents of a Web Part solution

Contents of a new Web Part solution project

However, the files in Figure 2 are renamed, and the project has been named "OfficeTalkWebPart." After Visual Studio creates the solution and project using the template, the manifest, .dwp, and main class in the code file are all named WebPart1. This is about as generic a name as is possible, so you want to change the corresponding file names and their contents to reflect a more useful name. You should change the name of the class in the main code file. For example, the default class definition is (with the namespace being the name of the solution you created):

namespace officeTalkWebPart
{
  [DefaultProperty("Text"),
      ToolboxData ("<{0}:WebPart1 runat=server></{0}: WebPart1>"),
      XmlRoot(Namespace="officeTalkWebPart")]  
  public class WebPart1: Microsoft.SharePoint.WebPartPages.WebPart
  {
  }
} 

The class definition contains some member definitions, but these do not contain "WebPart1", and they require no changes. Looking at this code, you should change the "WebPart1" text to a more meaningful Web Part name you choose. Once you make this change, you need to change a few other things.

  1. First, you should change the name of the .dwp file to reflect the name of your Web Part class.

  2. In the .dwp file is an XML element: <TypeName>. This element contains the namespace and class name of your Web Part. Change it to reflect the change you made to the name of your class. You can also assign values to the <Title> and <Description> elements. Use "OfficeTalkWebPart" for the title, and give your Web Part a meaningful description.

  3. Because you changed the name of your .dwp file, you need to change the corresponding reference to that file in the manifest file. The manifest file has a <DwpFiles> node with a <DwpFile> element for each .dwp file in your Web Part project. In this simple example, there is one, so you need only change the FileName attribute of the <DwpFile> element in the manifest. Make sure that there is congruity through all of your naming in these files.

Again, we will be exploring these files and their purpose later. For now, we just want to have a solid and consistent foundation upon which to build the balance of the solution. You will also need to add a deployment project to the solution. You will configure this project later on when preparing the Web Part package for deployment.

To add a deployment project to the solution

  1. Right-click the solution in the Solution Explorer window.

  2. Click Add, and select New Project.

  3. In the Project Types window, choose Setup and Deployment Projects.

  4. In the Templates window, choose Cab Project.

  5. Set the name of the project, and choose a location for the files.

  6. Click OK.

  7. Verify that the project now appears in the solution by looking in the Solution Explorer window.

When you open the code file for a Web Part, some things are stubbed out for you ahead of time. They are the bare essentials. But, you can strip it down even further. Here is about the simplest code you could ever want in a Web Part:

namespace officeTalkWebPart
{
      [ToolboxData("<{0}: OfficeTalk
                  runat=server></{0}: OfficeTalk >"),
                  XmlRoot(Namespace=" officeTalkWebPart")]
      public class mywebpart: 
                  Microsoft.SharePoint.WebPartPages.WebPart
      { 
            protected override void RenderWebPart
                  (HtmlTextWriter output)
            {
                  output.Write();
            }
      }
}

The most important part is the RenderWebPart method definition which overrides the method in the base class. This is where you put your code to cause the Web Part to display something when the user sees it on the SharePoint site.

The Web Part for this article displays a list of some of the things I have published on MSDN (Figure 3). This list is actually a list of hyperlinks, so clicking on the item opens the target article in the browser. You should note that SharePoint sites already have support for Links lists that produce the same functional result as this Web Part. But for illustration purposes, this exercise shows you how to create a Web Part with similar functionality on your own.

Figure 3. A Web Part that displays a list of hyperlinks

Web Part that displays a list of hyperlinks

The code for displaying the list of links is quite short and very simple. Essentially, the code loops through a collection of key/value pairs, adding a HyperLink object instance for each item in the collection. Additionally, the code places each link in a <p></p> HTML block. The HyperLink object has a NavigateUrl property, and the code assigns the collection item's key to this while assigning it's value to the HyperLink object's Text property:

   for (int i=0;i<arr.GetUpperBound(0);i++)
   {
      System.Web.UI.WebControls.HyperLink link=new HyperLink();
      link.NavigateUrl=arr[i].ToString();
      link.Text=ht.GetValues(arr[i].ToString())[0].ToString();
      output.RenderBeginTag("p");
      link.RenderControl(output);
      output.RenderEndTag();
   }

The HyperLink object is a server control in the .NET Framework, and although it is fully programmable class on the server, it ultimately gets expressed as simple HTML in the client browser. The code here calls the HyperLink object's RenderControl method. This method outputs the contents of the server control to an instance of an HtmlTextWriter. This is what makes it possible to render the server control as HTML on the client. Thus, our code passes an HtmlTextWriter instance to the RenderControl method.

The rest of the RenderWebPart method call is mostly about populating the key/value collection that is used as the data source for the Web Part. This technique is perfectly acceptable, but it is not hard to imagine using an XML file, a database, a Web service or some other source for the list of data. The full method call looks like this:

protected override void RenderWebPart(HtmlTextWriter output)
{
   output.RenderBeginTag("div");
   System.Collections.Specialized.NameValueCollection ht=
      new System.Collections.Specialized.NameValueCollection();
   ht.Add("http://msdn.microsoft.com/library/en-" +
      "us/dnofftalk/html/ODC_office01012004.asp",


      "Developing Word XML Using the Microsoft Office" +
      " Word 2003 XML Toolbox");
   ht.Add("http://msdn.microsoft.com/library/en-" +
      "us/dnofftalk/html/office11062003.asp",
      "The Definitive 'Hello World' Custom Research Service Tutorial");
   ht.Add("http://msdn.microsoft.com/library/en-" +
      "us/dnofftalk/html/office09042003.asp",
      "The Definitive 'Hello World' Managed Smart Document Tutorial");
   ht.Add("http://msdn.microsoft.com/library/en-" +
      "us/dno2k3ta/html/odc_OFLetsSortCollab.asp",
      "Sorting Out Microsoft's Collaboration Technologies");
   ht.Add("http://msdn.microsoft.com/library/en-" +
      "us/dno2k3ta/html/odc_customfaces_net.asp",
      "Custom Button Faces in a Managed Code Add-" +
      "in for the Microsoft Office System");
   ht.Add("http://msdn.microsoft.com/library/en-" +
      "us/dno2k3ta/html/odc_listbuttonfaces.asp",


      "Listing Button Faces in the Command Bar for " +
      "the Microsoft Office System");
   ht.Add("http://msdn.microsoft.com/library/en-" +
      "us/dnexcl2k2/html/odc_STAutofilter.asp",
      "Creating Smart Tags and Event-Code for AutoFilter Results");
   ht.Add("http://msdn.microsoft.com/library/en-" +
      "us/dnexcl2k2/html/odc_WebQueries.asp",
      "Web Queries and Dynamic Chart Data in Excel 2002");
   ht.Add("http://msdn.microsoft.com/library/en-" +
      "us/odc_xl2003_ta/html/odc_XLDataDrill.asp",
      "Use Smart Tags to Enable Data Drill-Down in Excel");
   ht.Add("http://msdn.microsoft.com/library/en-" +
      "us/odc_xl2003_ta/html/odc_XMLLists.asp",


      "Importing XML Maps, XML Lists, and Dynamic Chart" +
      " Sources in Excel 2003");
   string[] arr;
   arr=ht.AllKeys;
   for (int i=0;i<arr.GetUpperBound(0);i++)
   {
      System.Web.UI.WebControls.HyperLink link=new HyperLink();
      link.NavigateUrl=arr[i].ToString();
      link.Text=ht.GetValues(arr[i].ToString())[0].ToString();
      output.RenderBeginTag("p");
      link.RenderControl(output);
      output.RenderEndTag();
   }
   output.RenderEndTag();
}

As you can see, the bulk of the code here is for populating the collection containing the key/value pairs for the articles, specifying their URLs and titles. Once the RenderWebPart method is complete, you configure the manifest and .dwp files, build the project, package it, and deploy it on a server running Windows SharePoint Services.

As noted earlier, the manifest file is important for the deployment of the Web Part. Here are the contents of this article's sample Web Part:

<WebPartManifest 
   xmlns="http://schemas.microsoft.com/WebPart/v2/Manifest">
   <Assemblies>
      <Assembly FileName="officeTalkWebPart.dll">
         <SafeControls>
            <SafeControl Namespace="officeTalkWebPart" TypeName="*"/>
         </SafeControls>
      </Assembly>
   </Assemblies>
   <DwpFiles>
      <DwpFile FileName="OfficeTalk.dwp"/>
   </DwpFiles>
</WebPartManifest>
NoteNote

More information about the Web Part manifest and the meaning of its contents can be found here: Packaging and Deploying Web Parts

What is most important is to verify that the file names are accurate and point to actual files. These paths are relative to the location of the manifest file.

The other file that you should review is the .dwp file. This is an XML file with a reference to the Web Part's assembly and the Web Part's class within the assembly. Here are the contents of this article's sample .dwp file:

<WebPart xmlns="http://schemas.microsoft.com/WebPart/v2">
   <Title>OfficeTalk</Title>
   <Description>
      This is an end-to-end Web Part solution 
      to help developers get started.</Description>
   <Assembly>officeTalkWebPart</Assembly>
   <TypeName>officeTalkWebPart.OfficeTalk</TypeName>
</WebPart>

Of primary concern is that the TypeName element contains a correct reference to the Web Part's namespace and class name. If there are any errors in the .dwp file or the manifest file, the Web Part does not deploy or run properly. If these files are correct, and the assembly is complete, the next step is to package the Web Part and prepare it for deployment.

The packaging process means putting all of the resources for the Web Part into a package that makes deployment easy and complete. Web Parts are comprised of more than just the compiled assembly. They may include things such as images, help files, and other supporting resources. In addition to these resources, you need to add your Web Part to the SafeControls list for the specific virtual server so it can be used.

Earlier, you added a setup project to your Web Part solution. Now, you need to configure this project to produce a .cab file that makes your deployment easier. First, you need to add the Web Part project output to the setup project.

To add the Web Part project output to the setup project

  1. In the Solution Explorer, right-click on the setup project you added earlier.

  2. In the shortcut menu that appears, point to Add and then click Project Output.

  3. In the Add Project Output Group dialog box, ensure that you select the correct project.

  4. Select Primary Output and Content Files and then click OK.

Choosing these categories ensures that the Manifest.xml file, the .dwp file, and the Web Part assembly are included in the .cab file.

With these steps complete, you should build the solution. Right-click on the solution in the Solution Explorer, and click Build Solution. This produces builds for two projects, the Web Part project itself and the deployment project with its corresponding .cab file.

NoteNote

It is wise to make your Web Part assembly a strong-named assembly. For more information about this see: Creating and Using Strong-Named Assemblies.

Deployment involves different steps depending on your deployment goals. Deploying to a server that is your playground for development is fairly easy. Deploying to a production server with more restrictions and administrative constraints is another matter. The deployment scenario in this latter case should not present barriers for administrators and should encourage confidence in the overall solution. The Web Part for this article requires no special permissions, so deployment is quite simple.

The basic milestones in the deployment process are the same irrespective of where you are planning to deploy the Web Part. When someone wants to add Web Parts to a Web Part Page, they can choose from different galleries (Figure 4). You need to deploy your Web Part into a Web Part gallery so that others can add the Web Part to a Web Part Page.

Figure 4. Choosing a Web Part from a gallery

Choosing a Web Part from a Web Part gallery

To get this Web Part into a gallery, you must import it using the .dwp file. A .dwp file contains basic information about the Web Part. It is an XML file containing a reference to the Web Part's assembly, namespace, and class name, plus optional property settings. Windows SharePoint Services knows how to process this XML file and get the Web Part ready for use.

Once the Web Part is added the page, the code inside the Web Part's assembly begins to run. Events begin to fire, and any other internal operations you designed in the Web Part's code will come to life. However, other things are going on behind the scenes.

Adding the Web Part to the gallery can be easily done using the stsadm.exe utility (located in \Program Files\Common Files\Microsoft Shared\web server extensions\60\bin), a command-line tool that you can use to manage some aspects of a server running Windows SharePoint Services. There are three main switches you use with the utility with respect to Web Part package management:

  • AddWPPack- Adds a Web Part package

  • DeleteWPPack- Deletes a Web Part package

  • EnumWPPacks- Lists installed Web Part packages

Because you are adding a Web Part package for this sample, you use AddWPPack. When you execute the stsadm.exe command, the utility copies the Web Part Pack into Windows SharePoint Services and makes it available to all Windows SharePoint Services-enabled virtual servers on the computer. If you want to target one virtual server, the stsadm.exe utility has a –url switch that allows for this.

The command to deploy this article's sample Web Part looks like this:

stsadm.exe -o addwppack -filename deployOfficeTalk.cab
NoteNote

The name of the resulting .cab file, by default, is fairly generic. You can alter the name of the output by right-clicking on the setup project and choosing Properties. You can set the file name by changing the value in the Output file name field.

Notice that this command references the deployment package for the Web Part and not the Web Part's assembly itself. The .cab file has all of the files, including the Web Part assembly, that are needed to deploy the Web Part on a server.

Figure 5. The deployed Web Part in use

Deployed Web Part displayed on a Web page

There is nearly no limit to what you can do with Web Parts. You can create Web Parts that access databases, Web services, and other resources. You can also develop Web Parts that can send messages to each other to provide a more cohesive, interactive Web experience for users. The instructions in this article are really designed to help you get a very basic (but nonetheless useful) Web Part created, packaged, and deployed. You should consult the following resources section to find ways to learn more about Web Parts.

Visit the MSDN Microsoft Office Development Center for links to more content, community, regarding SharePoint Products and Technologies and developing Web Parts.

For more advanced deployment help, consult the following articles:

Show:
© 2015 Microsoft