Working with ASP.NET 2.0 Web Parts and Windows SharePoint Services 3.0

Summary: Explore the advantages of creating ASP.NET 2.0 Web Parts and hosting them by using Windows SharePoint Services 3.0. Learn best practices for deploying the custom Web Parts to SharePoint sites. (19 printed pages)

Erika Ehrli, Microsoft Corporation

Jo-Anne West, Microsoft Corporation

March 2007

Applies to: Microsoft Office SharePoint Server 2007, Microsoft Office SharePoint Portal Server 2003, Windows SharePoint Services 3.0, ASP.NET 2.0.

Contents

  • Overview

  • Web Part Frameworks

  • Choosing Between ASP.NET 2.0 Web Parts and Windows SharePoint Services 3.0 Web Parts

  • Overview of the ASP.NET 2.0 Web Part Infrastructure

  • Choosing Between the Bin or Global Assembly Cache

  • Walkthrough: Building and Deploying an ASP.NET 2.0 Virtual Earth Web Part to a SharePoint Site

  • Conclusion

  • Additional Resources

  • Acknowledgements

Overview

Microsoft ASP.NET 2.0 provides a Web Part infrastructure that helps you build custom Web Parts and deploy them to Web sites built using Windows SharePoint Services 3.0.

This article provides recommendations for best practices to choose between ASP.NET 2.0 Web Parts and Windows SharePoint Services 3.0 Web Parts according to business needs, reviews ASP.NET 2.0 Web Part infrastructure, and walks you through how to build custom Web Parts that work in both standard ASP.NET 2.0 Web sites and Windows SharePoint Services 3.0. The article also outlines deployment and security considerations to address before adding Web Parts to SharePoint sites. Finally, we walk through a code sample that creates and deploys a Virtual Earth Web Part to a SharePoint site.

  • If you are a SharePoint developer, this article can help you to understand relevant concepts related to the ASP.NET 2.0 Web Part infrastructure. It also walks through how to build custom Web Parts.

  • If you are an ASP.NET developer, this article helps you understand how to repurpose your knowledge to create custom Web Parts for SharePoint sites.

Web Part Frameworks

SharePoint Web Parts are UI elements that support both customization and personalization. A Web Part is an ASP.NET server control designed to be edited and modified by knowledge workers in the browser. It works as a component of a SharePoint site that presents information pulled from multiple data sources. With Web Parts, you can create information dashboards on corporate portals and Web sites. Web Part pages allow you to personalize information relevant to your needs by updating the value of specific Web Part properties.

The Web Part infrastructure in Windows SharePoint Services 2.0 and Microsoft Office SharePoint Portal Server 2003 allowed you to build custom Web Parts targeted to Microsoft SharePoint Products and Technologies by using managed code.

ASP.NET 2.0 includes a new Web Part control set that allows site customization and personalization on custom Web sites that are independent of SharePoint Products and Technologies.

The Web Part infrastructure in Windows SharePoint Services 3.0 exists on a layer above the ASP.NET 2.0 Web Part infrastructure. This introduces a next-generation Web Part infrastructure for the Windows Server 2003 platform as shown in the following figure.

Figure 1. ASP.NET 2.0 Web Part infrastructure

Choosing Between ASP.NET 2.0 Web Parts and Windows SharePoint Services 3.0 Web Parts

Office SharePoint Server 2007 and Windows SharePoint Services 3.0 are built on top of the ASP.NET 2.0 Framework. Windows SharePoint Services 3.0 uses the ASP.NET 2.0 Web Part infrastructure to take advantage of features such as master pages and custom Web Part development while providing a complete set of Windows SharePoint Services features, such as document services, events, workflow, search, site columns, content types and more.

You can build Web Parts for Windows SharePoint Services 3.0 in two ways:

  • Create custom ASP.NET 2.0 Web Parts.

  • Create SharePoint-based Web Parts.

You should create ASP.NET 2.0 Web Parts whenever you can. However, there are a few exceptions where using SharePoint-based Web Parts might offer advantages.. The following table provides a decision matrix to help you choose the best option depending on your business needs.

Table 1. Decision matrix for creating Web Parts

Create a custom ASP.NET 2.0 Web Part

Create a SharePoint-based Web Part

  • For most business needs.

  • To distribute your Web Part to sites that run ASP.NET 2.0 or SharePoint sites.

  • When you want to reuse one or more Web Parts created for ASP.NET 2.0 sites on SharePoint sites.

  • To use data or functionality provided by Windows SharePoint Services 3.0. For example, you are creating a a Web Part that works with site or list data.

  • When you want to migrate a set of Web Parts using the SharePoint-based Web Part infrastructure to Windows SharePoint Services 3.0.

  • To create cross page connections.

  • To create connections between Web Parts that are outside of a Web Part zone.

  • To work with client-side connections (Web Part Page Services Component).

  • To use a data-caching infrastructure that allows caching to the content database.

Note

The Windows SharePoint Services 3.0 Software Development Kit provides information and programming tasks that introduce you to how Web Parts are implemented in Windows SharePoint Services 3.0.

Overview of the ASP.NET 2.0 Web Part Infrastructure

ASP.NET 2.0 Web Part controls are a new generation of integrated server controls that enable users to personalize the content, appearance, and behavior of Web pages directly from application pages—without developer or administrator intervention.

The System.Web.UI.WebControls.WebParts namespace contains the Web Parts control set, a set of classes and interfaces that enable you to create Web Parts. The following classes enable you to build simple Web Part Pages.

  • WebPartManager: The central class of the Web Parts control set, managing all the Web Parts controls, functionality, and events that occur on a Web page.

  • WebZone: The base class for all controls that act as containers for server controls (including Web Part controls, server controls, and user controls) in Web Parts applications.

    • WebPartZone: The primary control in the Web Parts control set for hosting Web Part controls on a Web page.

    • EditorZone: The primary control in the Web Parts control set for hosting Editor Part controls on a Web page.

    • CatalogZone: The primary control in the Web Parts control set for hosting Catalog Part controls on a Web page.

    • ConnectionZone: A user interface (UI) that enables users to form connections between Web Part and other server controls that reside in WebPartZoneBase zones.

  • Part: The base class for all Web Parts part controls, which render a modular UI on a Web Forms page.

    • EditorPart: The base class for controls that reside in EditorZoneBase zones. Used to edit Web Part controls.

    • CatalogPart: The base class for controls that reside in CatalogZoneBase zones, and that provide catalogs of available Web server controls (especially Web Part controls) that users can add to a Web page.

    • WebPart: The base class for custom ASP.NET 2.0 Web Parts controls, adding to the base Part class features some additional UI properties, the ability to create connections, and personalization behavior.

For a complete reference of the classes and interfaces that belong to the System.Web.UI.WebControls.WebParts namespace, see the System.Web.UI.WebControls.WebParts Namespace reference documentation.

Creating a Simple ASP.NET 2.0 Web Part Page

ASP.NET 2.0 Web Parts are special category of controls. If you want to display them in ASP.NET 2.0 Web sites, you need to build a Web Part Page. This is the same process you follow when you need to render ASP.NET 2.0 controls.

To build a Web Part Page, start with a single instance of a WebPartManager control. Next, add one or many instances of the WebPartZone control. Each instance of the WebPartZone control hosts one or more Web Part controls. Using a browser, you can drag Web Parts to different Web Part zones. Optionally, you can add the following:

  • An EditorZone control with one or more EditorParts to enable users to personalize the behavior and appearance of Web Parts.

  • A CatalogZone with one or more CatalogParts to enable users to select which Web Parts appear on the page.

  • A ConnectionZone to provide a UI to enable users to connect Web Parts with other server controls.

The following figure shows a simple page with different Web Part components.

Figure 2. ASP.NET 2.0 Web Part page

The following code sample creates a simple ASP.NET 2.0 Web Part Page. Notice how we nest objects to build a page with Web Parts.

<%@ Page Language="C#" %>
<%@ Register Assembly="WebPartLibrary" Namespace="MyWebParts" TagPrefix="cc1" %>
<html>
<head id="Head1" >
    <title>My Web Part Page</title>
</head>
<body>
    <form id="form1" >
<asp:WebPartManager ID="WebPartManager1" />
        <asp:WebPartZone ID="WebPartZone1" >
            <ZoneTemplate>
                <cc1:MyWebPart ID="WebPart1" />
            </ZoneTemplate>
        </asp:WebPartZone>
    </form>
</body>
</html>

Note

The previous code sample shows how to create a simple ASP.NET 2.0 page with Web Parts. However, it does not work in Windows SharePoint Services 3.0.

When you are working with ASP.NET 2.0, you can create Web Parts using two different approaches:

  • Create a custom class library project that contains a control that inherits from the System.Web.UI.WebControls.WebParts.WebPart class. In your class, override the RenderContents method to render HTML. After you have the class, compile the project and add a reference to the Web Part project's .dll in your Web project. Finally, add the control to a WebPartZone.

  • Create a user control (.ascx) and place the control into a WebPartZone. ASP.NET 2.0 wraps the control automatically using the GenericWebPart wrapper class.

    Note

    Windows SharePoint Services 3.0 does not support this approach. Only ASP.NET 2.0 Web Parts that derive from the System.Web.UI.WebControls.WebParts.WebPart class can be used to host Web Parts on a Web Part Page in Windows SharePoint Services 3.0 or Microsoft Office SharePoint Server 2007.

About Web Part Personalization

Microsoft Office SharePoint Server 2007 enables users to share information, encourages collaboration, builds and promotes expertise, and targets relevant content to the people who need to see it. You can tailor content to each user in any organization, while enabling administrators to set policies to protect privacy.

The Microsoft Office SharePoint Server 2007 and ASP.NET 2.0 use different personalization services. Microsoft Office SharePoint Server 2007 uses a built-in personalization service that provides personalization features by design. For more information on Microsoft Office SharePoint Server 2007, see the Plan for Personalized Web Parts article. However, ASP.NET 2.0 sites require special configuration to enable personalization.

ASP.NET 2.0 provides a personalization service that enables users to save the state of Web Part controls in long-term storage by using the SqlPersonalizationProvider class. When you create a Web page that contains Web Parts, the ASP.NET 2.0 personalization service saves user selections to a Microsoft SQL Server 2005 database during run time.

Web Part personalization has a dependency on Microsoft SQL Server Express 2005. By default, Microsoft Visual Studio 2005 and Microsoft Visual Web Developer 2005 install SQL Server Express 2005. However, if you did not choose to install SQL Server Express, you can run the Aspnet_regsql.exe command to install it if you choose to later. For more information, see ASP.NET 2.0 SQL Server Registration Tool (Aspnet_regsql.exe).

Note

To access a different database or authentication server, you can create a provider for it by using the ASP.NET Provider Toolkit.

ASP.NET 2.0 Display Mode and Scope

The display mode and scope help you to personalize layout, content, and behavior for your users. A WebPartManager control enables users to select the display mode and page scope.

If you are working with Web Parts, it is important to understand the display mode and scope concepts.

The display mode defines the elements of the Web Part UI that are hidden or displayed as well as user modifications that are enabled or disabled.

The WebPartManager control contains the implementation for the display modes that are available in the Web Parts control set, and manages the display modes for a page.

  • BrowseDisplayMode: Represents the default display mode.

  • CatalogDisplayMode: Used for adding controls from a catalog of controls to a Web page.

  • ConnectDisplayMode: Displays a special UI for users to manage connections between Web Part controls.

  • DesignDisplayMode: Used for changing the layout of Web pages containing Web Part controls.

  • EditDisplayMode: Displays a UI from which end users can edit and modify server controls.

Personalization scope refers to whether personalization data is applicable to only a specific user and control on a page or to all users who view a site. Personalization scope indicates the set of data to retrieve and display.

A page can run in two scopes:

  • Shared: Indicates that only the personalization data for a specific control applies and should be loaded for all users viewing the control. Changes made by any user are saved to the data store.

  • User: Indicates that only the personalization data for a specific control applies and should be loaded for the currently executing user. Changes made by the currently executing user are saved to the data store.

For more information about Web Parts personalization, see Web Parts Personalization Overview.

Choosing Between the Bin or Global Assembly Cache

Within a SharePoint site, you can deploy a Web Part assembly to one of two locations:

  • Bin directory: Stored in your Web application root directory.

  • Global assembly cache: Automatically installed with the common language runtime. Enables you to share assemblies across numerous applications. Components are typically stored in C:\WINNT\Assembly.

Each location has advantages and disadvantages, as described in the following table.

Deployment location

Advantages

Disadvantages

Bin directory

A partial trust location. By default, code that runs from this directory has a low level of code access security permissions. Administrator must explicitly raise permissions granted to a Web Part so it can function properly. Because of this level of control and defense-in-depth, administrators tend to prefer that assemblies they get can run in the bin directory, with a known set of required code access security permissions.

A Bin directory is also specific to a Web application. This makes it possible to isolate code to a particular Web application.

To run your Web Part everywhere, you must deploy your Bin assembly.

Global assembly cache

A global location where you can deploy signed assemblies. Assemblies run with full trust by default. They are installed globally, so they work in any Web application.

Generally, there are no code access security restrictions on code installed to the global assembly cache; therefore, you lose the defense-in-depth security benefit.

Also, it can be difficult to deploy your .PDB files (program databases) to assemblies in the global assembly cache.

Setting Special Security Attributes

ASP.NET 2.0 Web Parts that you store in the Bin directory have special constraints for security. You can choose whether to set special security attributes for your filter Web Part, depending on how you plan to use it.

The Bin directory is a partial trust location. Therefore, your Web Part does not automatically grant full trust code permissions when it is executed. Because the code that calls into your Web Part is granted only partial trust permissions, you must set the AllowPartiallyTrustedCallers attribute on your ASP.NET 2.0 Web Part. You can set this attribute at the assembly level.

Note

Marking an assembly as safe to AllowPartiallyTrustedCallers puts the responsibility for safe implementation on the developers.

Another issue is that the code access security permissions for the Bin directory are very low by default; only pure execution is allowed. You must almost certainly elevate these permissions to make your assembly run correctly.

You can elevate permissions in two ways:

  • (Recommended) Create a trust policy file, and point your web.config file at the new file. This option is more complicated but it gives you a precise attribution of permissions for your Web Parts.

  • Raise the overall trust level of the Bin directory. In the web.config file in the Web application root, locate the trust element tag. The default value for the trust element's level attribute is WSS_Minimal. You can change this level to WSS_Medium.

    Note

    While this option is simpler, it grants arbitrary new permissions you may not need and is less secure than creating a trust policy file.

Safe Controls List

A fundamental assumption of the Windows SharePoint Services technology is that "un-trusted users" can upload and create ASPX pages within the system on which Windows SharePoint Services is running. These users should be prevented from adding server-side code within ASPX pages, but there should be a list of approved controls that those un-trusted users can use. In Windows SharePoint Services, this is provided by the Safe Controls list.

The Safe Controls list is a list of controls and Web Parts specific to your SharePoint site that you designate as safe for invocation on any ASPX page within your site. You store this list in the web.config file in your Web application root.

Walkthrough: Building and Deploying an ASP.NET 2.0 Virtual Earth Web Part to a SharePoint Site

You can build Web Parts that display data from different data sources. You can use a Web service, database, Microsoft Office Excel workbook, XML file, or any other data source you need to pull data and display information in a Web Part. In this walkthrough, you create a Web Part that displays driving directions on a Virtual Earth map. The Web Part provides a Start property that you can personalize. This section walks you through how to build an ASP.NET 2.0 Web Part and export it to a site based on Office SharePoint Server 2007. This process has five basic steps:

  1. Create an ASP.NET 2.0 Web Part Assembly.

  2. (Optional) Run and Test the Web Part in an ASP.NET 2.0 Web Page.

  3. Deploy the Web Part to Office SharePoint Server 2007.

  4. Create a .webpart File for your Web Part.

  5. Add the Web Part to a SharePoint Page.

    Note

    This Web Part will work in both standard ASP.NET 2.0 and Office SharePoint Server 2007 Web sites.

Step 1: Create an ASP.NET 2.0 Web Part Assembly

To create a simple Web Part, you must develop an ASP.NET 2.0 Web Part assembly. To start, you can create a class library project with a class that derives from the System.Web.UI.WebControls.WebParts.WebPart base class.

Next, build a VirtualEarthDirectionsWebPart class that allows uses to personalize content through a property (Start). The Web Part runs a script that connects to Virtual Earth and returns an image file that displays information with driving directions. In the VirtualEarthDirectionsWebPart class, override the RenderContents method and use an HTMLTextWriter object to write the HTML source code that your Web Part renders to the browser.

To create the Virtual Earth Directions Web Part

  1. In Visual Studio 2005, on the File menu, point to New, and then click Project.

  2. In Project types, under C#, select Windows.

  3. Under Templates, select Web Control Library. In the Name field, type MySampleWebParts, and then click OK.

  4. Rename Class1.cs to VirtualEarthDirectionsWebPart.cs.

  5. Add the following code to VirtualEarthDirectionsWebPart.cs.

    using System;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    
    namespace MySampleWebParts {
        public class VirtualEarthDirectionsWebPart : WebPart {
    
            private const string HtmlFormat = @"<div>
    <P>&nbsp;</P>
    <P>
    <TABLE id='Table1' cellSpacing='1' cellPadding='1' width='300' border='0'>
    <TR>
    <TD><FONT face='Verdana' size='2'><STRONG>Destination: </STRONG></FONT>
    </TD>
    <TD><INPUT id='tbDestination' type='text' size='23' value='Space Needle' name='Text1'></TD>
    <TD><INPUT id='Button1' type='button' value='Get Directions' name='Button1' onclick='GetRouteMap()'></TD>
    </TR>
    </TABLE>
    </P>
    <script src='http://dev.virtualearth.net/mapcontrol/v4/mapcontrol.js'></script>
    <script language='javascript' id='clientEventHandlersJS'>
    <!--
             var map = null;
    
             function GetRouteMap() {{
    
                map = new VEMap('myMap');
                map.LoadMap();
    
                var destination=document.getElementById('tbDestination').value;
    
                if (destination!=null) {{
                   map.GetRoute('{0}', destination);
                }}
             }}   
    
    //-->
    </script>
    <div id='myMap' style='WIDTH:400px; POSITION:relative; HEIGHT:400px'></div>
    </div>";
    
            private string _start = String.Empty;
    
            public VirtualEarthDirectionsWebPart() {
                this.Title = "Virtual Earth Driving Directions Web Part";
                this.ExportMode = WebPartExportMode.All;
            }
    
            // Property to personalize the start location
            [Personalizable]
            [WebBrowsable]
            public string Start {
                get {
                    return _start;
                }
                set {
                    _start = value;
                }
            }
    
            // Render a Virtual Earth Map as a Web part
            protected override void RenderContents(HtmlTextWriter writer) {
    
                if (String.IsNullOrEmpty(_start)) {
                    writer.Write("Select a start point by personalizing this WebPart.");
                }
                else {
                    base.RenderContents(writer);
    
                    writer.Write(String.Format(HtmlFormat, _start));
                }
            }
        }
    }
    
  6. Compile the VirtualEarthDirectionsWebPart solution.

Note

This walkthrough describes how to create the Web Part class manually. Creating a Web Part is now even easier than before because of the Web Part project templates included inWindows SharePoint Services 3.0 Tools: Visual Studio 2005 Extensions. For more information, see Creating a Windows SharePoint Services 3.0 Web Part Using Visual Studio 2005 Extensions.

Step 2: Run and Test the Web Part in an ASP.NET 2.0 Web Page

After you build the VirtualEarthDirectionsWebPart class, you can build an ASP.NET 2.0 page to host your Web Part and run the page to test the Web Part.

Note

This step is optional if you want to only deploy your Web Part to a SharePoint site. However, you can perform the following steps to run and test the same Web Part in ASP.NET 2.0 sites.

To test the MyVirtualEarthDirectionsWebPart in an ASP.NET 2.0 page

  1. In Visual Studio 2005, on the File menu, point to New, and then click Web Site.

  2. In Visual Studio installed templates, select ASP.NET 2.0 Web Site.

  3. Select File System, and type C:\MyWebPartsTest for the Location.

  4. On the Project menu, click Add Reference.

  5. On the Browse tab, navigate to and select VirtualEarthDirectionsWebPart.dll, and then click OK.

  6. Replace the code in Default.aspx with the following code.

    <%@ Page Language="C#" %>
    <%@ Register Assembly="MySampleWebParts" Namespace="MySampleWebParts" TagPrefix="wpc" %>
    
    <script >
        protected void editModeLink_Click(object sender, EventArgs e)
        {
            Mgr.DisplayMode = WebPartManager.EditDisplayMode;
        }
    </script>
    
    <html>
    <head id="Head1" >
        <title>My Web Parts Page</title>
    </head>
    <body>
        <form id="form1" >
            <div>
                &nbsp;
                <br />
                <table border="0" cellpadding="0" cellspacing="0" style="width: 100%; height: 100%">
                    <tr>
                        <td colspan="2" style="height: 50px">
                            <asp:LinkButton  Text="Edit Mode" ID="editModeLink" OnClick="editModeLink_Click" />
                            <asp:WebPartManager  ID="Mgr" Personalization-Enabled="true" />
                        </td>
                    </tr>
                    <tr>
                        <td valign="top" width="70%">
                            <asp:WebPartZone ID="WebPartZone1"  BorderColor="#CCCCCC" Font-Names="Verdana"
                                Padding="6">
                                <ZoneTemplate>
                                    <wpc:VirtualEarthDirectionsWebPart ID="MyWebPart"  ExportMode="All" />
                                </ZoneTemplate>
                                <PartChromeStyle BackColor="#F7F6F3" BorderColor="#E2DED6" Font-Names="Verdana" ForeColor="White" />
                                <MenuLabelHoverStyle ForeColor="#E2DED6" />
                                <EmptyZoneTextStyle Font-Size="0.8em" />
                                <MenuLabelStyle ForeColor="White" />
                                <MenuVerbHoverStyle BackColor="#F7F6F3" BorderColor="#CCCCCC" BorderStyle="Solid"
                                    BorderWidth="1px" ForeColor="#333333" />
                                <HeaderStyle Font-Size="0.7em" ForeColor="#CCCCCC" HorizontalAlign="Center" />
                                <MenuVerbStyle BorderColor="#5D7B9D" BorderStyle="Solid" BorderWidth="1px" ForeColor="White" />
                                <PartStyle Font-Size="0.8em" ForeColor="#333333" />
                                <TitleBarVerbStyle Font-Size="0.6em" Font-Underline="False" ForeColor="White" />
                                <MenuPopupStyle BackColor="#5D7B9D" BorderColor="#CCCCCC" BorderWidth="1px" Font-Names="Verdana"
                                    Font-Size="0.6em" />
                                <PartTitleStyle BackColor="#5D7B9D" Font-Bold="True" Font-Size="0.8em" ForeColor="White" />
                            </asp:WebPartZone>
                        </td>
                        <td valign="top" width="30%">
                            &nbsp;<asp:EditorZone ID="EditorZone1" HeaderText="Edit WebParts" Width="50px" 
                                PartChromeType="TitleOnly" CssClass="EditorZoneBody" BackColor="#F7F6F3" BorderColor="#CCCCCC"
                                BorderWidth="1px" Font-Names="Verdana" Padding="6">
                                <ZoneTemplate>
                                    <asp:AppearanceEditorPart ID="AppearanceEditorPart1"  />
                                    <asp:PropertyGridEditorPart ID="PropertyGridEditorPart1" Title="Custom Settings"
                                         />
                                    <asp:BehaviorEditorPart ID="BehaviorEditorPart1"  />
                                </ZoneTemplate>
                                <HeaderStyle BackColor="#E2DED6" Font-Bold="True" Font-Size="0.8em" ForeColor="#333333" />
                                <LabelStyle Font-Size="0.8em" ForeColor="#333333" />
                                <HeaderVerbStyle Font-Bold="False" Font-Size="0.8em" Font-Underline="False" ForeColor="#333333" />
                                <PartChromeStyle BorderColor="#E2DED6" BorderStyle="Solid" BorderWidth="1px" />
                                <PartStyle BorderColor="#F7F6F3" BorderWidth="5px" />
                                <FooterStyle BackColor="#E2DED6" HorizontalAlign="Right" />
                                <EditUIStyle Font-Names="Verdana" Font-Size="0.8em" ForeColor="#333333" />
                                <InstructionTextStyle Font-Size="0.8em" ForeColor="#333333" />
                                <ErrorStyle Font-Size="0.8em" />
                                <VerbStyle Font-Names="Verdana" Font-Size="0.8em" ForeColor="#333333" />
                                <EmptyZoneTextStyle Font-Size="0.8em" ForeColor="#333333" />
                                <PartTitleStyle Font-Bold="True" Font-Size="0.8em" ForeColor="#333333" />
                            </asp:EditorZone>
                        </td>
                    </tr>
                </table>
                <br />
            </div>
        </form>
    </body>
    </html>
    
  7. Add the following code to the web.config file to enable personalization.

    <connectionStrings>
        <add name="MyDb" connectionString="Data Source=YourServer;Initial Catalog=aspnetdb;Integrated Security=True" providerName="System.Data.SQLClient"/>
      </connectionStrings>
    <system.web>
      <webParts enableExport="true">
          <personalization defaultProvider="MyWebPartsProvider">
            <providers>
              <add name="MyWebPartsProvider" connectionStringName="MyDb" type="System.Web.UI.WebControls.WebParts.SqlPersonalizationProvider"/>
            </providers>
          </personalization>
        </webParts>
    </system.web>
    

    Note

    You must enable personalization to allow users to modify the Web Part properties. For more information, review the Web Part personalization section of this article.

  8. Compile the MyWebPartsTest Web site solution.

Now if you view Default.aspx in a Web browser, you should see the MyVirtualEarthDirectionsWebPart Web Part display, similar to the following figure.

Figure 3. Web Part on a ASP.NET 2.0 Web page

Step 3: Deploy the Web Part to Office SharePoint Server 2007

Because this walkthrough is used only for demonstration purposes, we suggest placing the assembly in the bin directory.

Note

By default, code access security permissions for the bin directory are low; only pure execution is allowed. This is sufficient permissions for this sample, so no further configuration is required here. If you have a Web Part that requires more permissions, you must perform additional configuration here. For more information about this, see Setting Special Security Attributes.

To deploy the Web Part

  1. Copy the MySampleWebParts.dll assembly in the project's bin directory to the bin directory in your SharePoint application root.

  2. Locate the web.config file in your application root and open it for editing.

  3. Add a safe control entry for your custom assembly to the web.config file as shown.

    <SafeControl 
    Assembly="MySampleWebParts" 
    Namespace="MySampleWebParts" 
    TypeName="*" 
    Safe="True" 
    />
    

Step 4: Create a .webpart File for your Web Part

Every Web Part should have a .webpart file, which is an XML file that describes the Web Part. The .webpart file also makes your Web Part appear in the Web Part Gallery. This procedure describes the easiest way to create a .webpart file after you deploy your Web Part and register it in the Safe Control list.

To create a .webpart file

  1. Navigate to http://MyServer/_layouts/newdwp.aspx, where MyServer is the name of the server on which your SharePoint site is deployed.

  2. Select the check box beside MySampleWebParts.VirtualEarthDirectionsWebPart.

  3. Click Populate Gallery to add the VirtualEarthDirectionsWebPart Web Part to the Team Site Gallery.

Note

To create a .webpart file for your Web Part, you can select Edit for the Web Part in the Web Part Gallery, and then click Export. You are prompted to provide a location in which to put the .webpart file. You can also export ASP.NET 2.0 Web Parts and import them to SharePoint sites.

Step 5: Add the Web Part to a SharePoint Page

The last step is importing the Web Part to a page in any SharePoint site.

To add the Web Part to a SharePoint page

  1. Navigate to the Web Part Page on your SharePoint site where you want to add the Web Part.

  2. In the Web Part Page, click Site Actions, and select Edit Page.

  3. In the Web Part zone where you want to add the VirtualEarthDirectionsWebPart, click Add a Web Part to open the Add Web Parts dialog box, as shown in the following figure.

    Figure 4. Add Web Parts - WebPage Dialog

  4. In the Web Part zone, click Edit, and select Modify Shared Web Part to personalize the Start property, as shown in the following figure.

    Figure 5. Personalizing Web Parts on a SharePoint site

  5. Select a Start address or place and then click OK.

  6. The VirtualEarthDirectionsWebPart should now be displayed on the page, as shown in the following figure.

    Figure 6. Choose a destination in a Web Part

  7. The VirtualEarthDirectionsWebPart allows you to choose a destination and get a Virtual Earth Map with directions, as shown in the previous figure.

Conclusion

Microsoft ASP.NET 2.0 provides a new set of extensibility options for SharePoint sites. The ASP.NET 2.0 Web Part infrastructure helps you build custom Web Parts and deploy them to Web sites built using Windows SharePoint Services 3.0. You can build custom Web Parts using different approaches and this article provides information to help choose the best approach for creating and deploying Web Parts. It also describes the steps for creating and deploying a custom ASP.NET 2.0 Web Part that works in both standard ASP.NET 2.0 and Office SharePoint Server 2007 Web sites.

This article describes how to create the Web Part class manually. Keep in mind that creating a Web Part is now even easier than before because of the Web Part project templates included in Windows SharePoint Services 3.0 Tools: Visual Studio 2005 Extensions. For more information, see Creating a Windows SharePoint Services 3.0 Web Part Using Visual Studio 2005 Extensions.

Additional Resources

Acknowledgements

Thank you to Mike Ammerlaan and Carlos Aguilar Mares for their contributions to this article.