Developing Web Parts for SharePoint Portal Server 2003 in .NET

Developing Web Parts for SharePoint Portal Server 2003 in .NET

harePoint allows information workers to create powerful personalized interfaces by simply dragging and dropping pre-defined Web Part Components. Web Parts are components that enable non programmers to gather information they care about and customize the appearance of Web pages. For example, one Web Part might display a user’s appointment calendar; another might create a graph showing current sales figures; and a third might show a list of new business topics, each of which functions as a link to a video or audio presentation. Developers can create these Web Part components and make them available to SharePoint users, letting them build customizable pages that meet their needs. This article shows you how to build and consume a simple Web Part.

Web Part Templates for Visual Studio .NET
Web Parts are standard ASP.NET custom controls, but Microsoft has provided a new template that simplifies the process of creating Web Parts. You can download the template here .

You need to install the template only once, after which it will be available permanently in the Visual Studio .NET environment.

Installing the Web Part Template.
After downloading the template, locate the file WebPartTemplates.exe, and double click on it to install the templates. The templates support both C# and VB.NET development?choose the target language or languages that fit your requirements. (see Figure 1)

Figure 1: During the Web Part template installation, you can elect to install the templates for either Visual C#, Visual Basic .NET, or both.

After selecting the Web Parts templates language, you’ll need to select the location of the Microsoft.SharePoint.dll file. By default, SharePoint installs the Microsoft.SharePoint.dll to local_drive:Program FilesCommon FilesMicrosoft SharedWeb server extensions60ISAPI; however, you may have installed SharePoint to a non-default location.

When you’re developing locally with Visual Studio .NET, the .NET Framework, and SharePoint installed on same machine, you can simply provide the path to the local copy of the DLL. On the other hand, if you’re developing on a local machine and connecting to a remote server hosting SharePoint, you’ll find it easier to copy the DLL to your local machine and use that local DLL location. This article assumes that you’re developing on a machine with both .NET and SharePoint installed locally (see Figure 2).

Figure 2: When asked to specify the Microsoft.SharePoint.dll path, provide the full path, but not the file name.

After installing the templates, every time you create a new Web Part application, Visual Studio will automatically add a reference to the SharePoint DLL to the Web Part project (see Figure 3).

Figure 3: The Solution Explorer in Visual Studio .NET after adding the Microsoft.SharePoint.dll reference.

On the other hand, if you don’t provide the location for the DLL during installation, VS .NET pops up the following message every time you create a new Web Part application (see Figure 4).

Figure 4: You’ll see this message if you don’t specify the correct Sharepoing.dll location during installation.

Despite the message text, all that really means is that you’ll have to add a reference to the DLL manually.

Creating a Simple Web Part in Visual Studio .NET
Installing the Web Part template adds a new template to the New Project dialog, Templates area (see Figure 5).

Figure 5: To create a new Web Part using the Web Part template in Visual Studio, select the Web Part Library template, and then enter a name and location for the project.

To begin a new Web Part Project, select the Web Part Library from the Templates panel. Like a normal .NET application, provide a name and a location for the application. Then click OK.

By default, VS .NET creates the application will be created with three files: WebPart1.cs, WebPart1.dwp and Manifest.xml files as shown in Figure 6.

Figure 6: Here’s how the Solution Explorer in Visual Studio .NET looks after you create a new Web Part project.

The Web Part Class File
The WebPart1.cs is the default name provided by VS .NET for the Web Part Class. You will write code against this file to develop a Web Part. The biggest difference between creating a Web Part and an ASP.NET Web Form is that there’s no design view and no graphical tools available for Web Part projects?in other words, there’s no way to drag and drop Server or HTML controls from the Toolbox.

The .dwp file
One of the new files added when you create a new Web Part project is WebPart1.dwp, an XML file that holds the reference to the assembly and class used to create it. In previous versions of Web Part technology, the .dwp file contained the code to implement the logic of Web Part. But in the current version, you implement Web Part logic in compiled.NET class files as part of managed assemblies, and the .dwp file contains the name of the assembly and class for each Web Part.

By default, the file contains Title, Description, Assembly and TypeName elements as shown in Figure 7. VS .NET uses the Title and Description properties to identify the Web Part when you add it to the SharePoint web page. You can specify the name of the Web Part in the Title element and a short description about the Web Part in the Description element. The description information displays as a tool tip.

Figure 7: This simple .dwp file image shows the overall XML structure for dwp files.

You specify the class name of the Web Part in the TypeName element. For example, the file in Figure 7 shows that MyWebPart1 is the namespace and WebPart1 is the class name, as exemplified in the following code fragment:

   namespace MyWebPart1   {      ///       /// Summary description for WebPart1.      ///       [DefaultProperty("Text"),ToolboxData(         "<{0}:WebPart1       runat=server>"),XmlRoot(         Namespace="MyWebPart1")]      public class WebPart1 :          Microsoft.SharePoint.WebPartPages.WebPart     {   // more code here
TIP: If you change the namespace or class name after creating the project, you will also need to update the same information in the .dwp file. You can confirm the name of the assembly by looking at the Property dialog for the application (see Figure 8).

Figure 8: You can confirm the name of the project assembly by retrieving the Assembly Name from the project’s Property Pages dialog.

The Manifest.xml file
VS .NET uses the Manifest.xml to populate CAB files when deploying the Web Part to a different location, such as from your development machine to a test or production environment.

Setting the Output Path for Your Web Part Application
It’s important to remember that you should set the Output Path property of the Web Part application to the bin folder of your SharePoint Portal site. If you’re developing in a local environment, click on the Output Path field in the project’s Property dialog and use the browse button to select the path. Typically, the output path will be


TIP: You can confirm this by opening the web.config file of the selected directory (Ex: wwwroot) and verify that it contains the SharePoint information.

If you are developing against a remote machine, you should set the output path to the remote location’s bin directory as shown in Figure 9.

Figure 9: When developing against a remote server, the output path should point to the remote machine.

Server_Name is the name of the remote server on which SharePoint Portal Server is running.

Web Parts and ASP.NET Custom Controls
Before writing any code you need to understand a bit about the structure of Web Parts. Web Parts are very similar to ASP.NET Custom controls. If you already have experience creating ASP.NET Custom controls, you will find it very easy to create Web Parts.

ASP.NET provides two abstractions for extending the server control framework: user controls and custom controls. User controls are essentially ASP.NET pages with an .ascx file extension that you can insert into standard .aspx Web Form pages. When you build user controls in VS .NET you can drag and drop server controls onto the user control design surface. Unfortunately, you can’t create Web Parts visually; instead, you must create ASP.NET custom controls?which don’t support VS .NET’s graphical design environment. Each custom control class inherits from System.Web.UI.WebControls.WebControl, which itself inherits from the System.Web.UI.Control class. You will generate the HTML for each control by overriding the base class’ RenderContents method. This method provides an HtmlTextWriter object as an input parameter that you can use to generate robust HTML rather than simply concatenating strings.

The difference between a Web Part and a custom control is that instead of creating a class which inherits from WebControl, you create a Web Part class by inheriting from the Microsoft.SharePoint.WebPartPages.WebPart class. The WebPart class?like WebControl?inherits from System.Web.UI.Control. The WebPart class handles interactions with WebPartPage and WebPartZone classes to support adding, deleting, customizing, connecting and personalizing Web Parts on a page. You need to override the RenderWebPart method rather than the RenderContents method when creating Web Parts.

The Web Parts infrastructure provides additional advantages over other ASP.NET custom controls. User can drag completed Web Parts from Web Part galleries and drop them onto Web Part Zones. User can modify personal or shared properties of your Web Part and make them persistent. The most interesting and important evolution is that Web Parts connect with each other using standard interfaces.

For this example, you’ll create a simple Web Part containing a Label control that will display “Hello World” in this section.

   ///    /// Render this Web Part to the output    /// parameter specified.   ///    ///  The HTML writer to    /// write out to    protected override void RenderWebPart(HtmlTextWriter output)   {      output.Write(SPEncode.HtmlEncode(Text));      //Create a Lable      Label myLabel = new Label();      //Write the Text      myLabel.Text = "Hello World";            //Add the lable control to the page      this.Controls.Add(myLabel);      //Render the Html output      myLabel.RenderControl(output);                  }
TIP: Don’t forget to add your controls to Controls list before you render the output.

Now build the project. VS. NET creates a MyWebPart1.dll and a MyWebPart1.pdb in the bin directory you specified for the project’s output location.

Creating SafeControls
Before you can add the Web Part to the Web page, you have to make the server trust your Web Part. You do this by adding some information to the web.config file’s SafeControls section. Each SafeControls entry identifies an Assembly that contains one or more trusted Web Parts. Each element has four attributes, as shown in Table 1.

Table 1: The SafeControl element accepts these attributes.

SafeControl Attribute Description
Assembly This is the name of the assembly that contains one or more Web Parts. For this application, the assembly name is MyWebPart1 (the same value that’s in the Assembly element in the .dwp file). The Assembly attribute can also contain version, culture, and public key token information.
Namespace The .NET namespace for the Web Part class. For this application, use MyWebPart1 (the same namespace specified in the TypeName element in the .dwp file.
TypeName This is the class name of the Web Part. It’s easier to use an asterisk (*) to include all Web Part classes within the specified assembly and namespace so that when you later add a new Web Part to the application, you don’t have to make any more changes to the web.config file.
Safe By default this element contains the value true. It must contain true to make your Web Part trusted. Administrators can set this value to false to make this Web Part unavailable.

After you make the changes to trust the Web Part, your web.config file will look similar to the following code:

TIP: Make sure that you save the web.config file after adding the SafeControl entry.

If the Web Part is not declared in the SafeControl section, you’ll see the error message shown in Figure 10 when you add the Web Part to the Web page.

Figure 10: If you add an untrusted Web Part to a page, you’ll see this error message.

Displaying a Web Part in a SharePoint Web Page
You need to import the .dwp file to add a Web Part to a SharePoint Web page. To do that, open your SharePoint Web site and navigate to the page where you want to add the Web Part. In the right top corner, you’ll see a Modify My Page (or Modify Shared Page if working in shared view) tab with an arrow?pointing down. Click the arrow and select Add Web Parts from the menu, and then select Import (see Figure 11).

Debugging Web Parts
You can use Visual Studio .NET’s debugging facilities to debug your Web Part applications either locally or remotely. Unfortunately, debugging Web Parts is not quite as seamless as debugging a Windows application.

Debugging Locally
In this situation, Visual Studio .NET and SharePoint are installed on the same machine. To debug:

  1. Open the Web Part project in Visual Studio .NET
  2. Ensure that the project Output Path is set to the following location in the project Property window: local_driveInetPubwwwrootin. (See the section Setting the Output Path for Web Part Applications section for more details)
  3. Make sure you have added the Web Part to the SafeControls list. (Refer to the section Creating SafeControls for more details)
  4. Open the Web Part class file you want to debug and add breakpoints just as you do in any Windows or ASP.NET application in VS .NET.

After successfully opening the project and attaching the necessary breakpoints, the next step is to attach the W3wp.exe Processor.

Attaching the w3wp.exe Process

  1. Click the Debug menu in VS .NET and select Processes. You’ll see the Processes dialog shown in Figure 16.
  2. devx-admin


    Share the Post:
    Remote Learning

    Revolutionizing Remote Learning for Success

    School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing

    Revolutionary SABERS Transforming

    SABERS Batteries Transforming Industries

    Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs

    Build a Website

    How Much Does It Cost to Build a Website?

    Are you wondering how much it costs to build a website? The approximated cost is based on several factors, including which add-ons and platforms you

    Iran Drone Expansion

    Iran’s Jet-Propelled Drone Reshapes Power Balance

    Iran has recently unveiled a jet-propelled variant of its Shahed series drone, marking a significant advancement in the nation’s drone technology. The new drone is poised to reshape the regional

    Solar Geoengineering

    Did the Overshoot Commission Shoot Down Geoengineering?

    The Overshoot Commission has recently released a comprehensive report that discusses the controversial topic of Solar Geoengineering, also known as Solar Radiation Modification (SRM). The Commission’s primary objective is to

    Remote Learning

    Revolutionizing Remote Learning for Success

    School districts are preparing to reveal a substantial technological upgrade designed to significantly improve remote learning experiences for both educators and students amid the ongoing pandemic. This major investment, which

    Revolutionary SABERS Transforming

    SABERS Batteries Transforming Industries

    Scientists John Connell and Yi Lin from NASA’s Solid-state Architecture Batteries for Enhanced Rechargeability and Safety (SABERS) project are working on experimental solid-state battery packs that could dramatically change the

    Build a Website

    How Much Does It Cost to Build a Website?

    Are you wondering how much it costs to build a website? The approximated cost is based on several factors, including which add-ons and platforms you choose. For example, a self-hosted

    Battery Investments

    Battery Startups Attract Billion-Dollar Investments

    In recent times, battery startups have experienced a significant boost in investments, with three businesses obtaining over $1 billion in funding within the last month. French company Verkor amassed $2.1

    Copilot Revolution

    Microsoft Copilot: A Suit of AI Features

    Microsoft’s latest offering, Microsoft Copilot, aims to revolutionize the way we interact with technology. By integrating various AI capabilities, this all-in-one tool provides users with an improved experience that not

    AI Girlfriend Craze

    AI Girlfriend Craze Threatens Relationships

    The surge in virtual AI girlfriends’ popularity is playing a role in the escalating issue of loneliness among young males, and this could have serious repercussions for America’s future. A

    AIOps Innovations

    Senser is Changing AIOps

    Senser, an AIOps platform based in Tel Aviv, has introduced its groundbreaking AI-powered observability solution to support developers and operations teams in promptly pinpointing the root causes of service disruptions

    Bebop Charging Stations

    Check Out The New Bebob Battery Charging Stations

    Bebob has introduced new 4- and 8-channel battery charging stations primarily aimed at rental companies, providing a convenient solution for clients with a large quantity of batteries. These wall-mountable and

    Malyasian Networks

    Malaysia’s Dual 5G Network Growth

    On Wednesday, Malaysia’s Prime Minister Anwar Ibrahim announced the country’s plan to implement a dual 5G network strategy. This move is designed to achieve a more equitable incorporation of both

    Advanced Drones Race

    Pentagon’s Bold Race for Advanced Drones

    The Pentagon has recently unveiled its ambitious strategy to acquire thousands of sophisticated drones within the next two years. This decision comes in response to Russia’s rapid utilization of airborne

    Important Updates

    You Need to See the New Microsoft Updates

    Microsoft has recently announced a series of new features and updates across their applications, including Outlook, Microsoft Teams, and SharePoint. These new developments are centered around improving user experience, streamlining

    Price Wars

    Inside Hyundai and Kia’s Price Wars

    South Korean automakers Hyundai and Kia are cutting the prices on a number of their electric vehicles (EVs) in response to growing price competition within the South Korean market. Many

    Solar Frenzy Surprises

    Solar Subsidy in Germany Causes Frenzy

    In a shocking turn of events, the German national KfW bank was forced to discontinue its home solar power subsidy program for charging electric vehicles (EVs) after just one day,

    Electric Spare

    Electric Cars Ditch Spare Tires for Efficiency

    Ira Newlander from West Los Angeles is thinking about trading in his old Ford Explorer for a contemporary hybrid or electric vehicle. However, he has observed that the majority of

    Solar Geoengineering Impacts

    Unraveling Solar Geoengineering’s Hidden Impacts

    As we continue to face the repercussions of climate change, scientists and experts seek innovative ways to mitigate its impacts. Solar geoengineering (SG), a technique involving the distribution of aerosols

    Razer Discount

    Unbelievable Razer Blade 17 Discount

    On September 24, 2023, it was reported that Razer, a popular brand in the premium gaming laptop industry, is offering an exceptional deal on their Razer Blade 17 model. Typically

    Innovation Ignition

    New Fintech Innovation Ignites Change

    The fintech sector continues to attract substantial interest, as demonstrated by a dedicated fintech stage at a recent event featuring panel discussions and informal conversations with industry professionals. The gathering,

    Import Easing

    Easing Import Rules for Big Tech

    India has chosen to ease its proposed restrictions on imports of laptops, tablets, and other IT hardware, allowing manufacturers like Apple Inc., HP Inc., and Dell Technologies Inc. more time

    Semiconductor Stock Plummet

    Dramatic Downturn in Semiconductor Stocks Looms

    Recent events show that the S&P Semiconductors Select Industry Index seems to be experiencing a downturn, which could result in a decline in semiconductor stocks. Known as a key indicator

    Anthropic Investment

    Amazon’s Bold Anthropic Investment

    On Monday, Amazon announced its plan to invest up to $4 billion in the AI firm Anthropic, acquiring a minority stake in the process. This decision demonstrates Amazon’s commitment to

    AI Experts Get Hired

    Tech Industry Rehiring Wave: AI Experts Wanted

    A few months ago, Big Tech companies were downsizing their workforce, but currently, many are considering rehiring some of these employees, especially in popular fields such as artificial intelligence. The

    Lagos Migration

    Middle-Class Migration: Undermining Democracy?

    As the middle class in Lagos, Nigeria, increasingly migrates to private communities, a PhD scholar from a leading technology institute has been investigating the impact of this development on democratic

    ©2023 Copyright DevX - All Rights Reserved. Registration or use of this site constitutes acceptance of our Terms of Service and Privacy Policy.