Export (0) Print
Expand All
Add a Recycle Bin to Windows SharePoint Services for Easy Document Recovery
Use Windows SharePoint Services as a Platform for Building Collaborative Applications
Use Windows SharePoint Services as a Platform for Building Collaborative Apps, Part 2
Expand Minimize

Converting Dashboard Web Parts to the Web Part Infrastructure for Microsoft SharePoint Products and Technologies

SharePoint 2003
 

Andrew Miller
Michael Herzfeld
Scott Ruble
Microsoft Corporation

August 2003

Applies to:
     Microsoft® Windows SharePoint™ Services 2.0
     Microsoft® Office SharePoint Portal Server 2003

Summary: Learn to convert dashboard Web Parts to the Web Part infrastructure. Read an overview of Digital Dashboard technology and the Web Part infrastructure, including the dashboard features implemented in the Web Part infrastructure and the enhancements introduced in the new architecture.

This paper assumes that you have a solid understanding of Web-based technologies such as Hypertext Markup Language (HTML), Extensible Markup Language (XML), Extensible Stylesheet Language (XSL), Microsoft .NET Framework technologies such as ASP.NET, and programming languages such as Microsoft Visual C# .NET or Microsoft Visual Basic® .NET.

This paper is intended to be a developer reference that you can use with the Microsoft SharePoint™ Products and Technologies Software Development Kit (SDK). The SharePoint Products and Technologies SDK contains additional reference material that is not included in this paper. (24 printed pages)

Contents

Introduction
Web Part Infrastructure
Converting Web Parts to the Web Part Infrastructure
Developing Dashboard Web Parts that Are Easy to Convert
Conclusion

Introduction

Web Parts were introduced as a part of Microsoft Digital Dashboard technology. The first version of the Web Part Development Kit provided the tools, documentation, and sample code that developers needed to build Web Parts for Microsoft SharePoint Portal Server 2001 or to build custom dashboards based on Microsoft SQL Server™ Digital Dashboard 3.0 or the Exchange dashboard template included in Microsoft Office XP Developer.

Microsoft Windows SharePoint Services extends Web Part technology by using the Web Part infrastructure. The Web Part infrastructure is available in Windows SharePoint Services-based solutions created by Microsoft and Microsoft partners, such as Microsoft Office SharePoint Portal Server and Microsoft Office 2003. The Web Part infrastructure is based on ASP.NET technology. This paper describes how to convert dashboard Web Parts to the Web Part infrastructure.

Web Part Infrastructure

Dashboard Web Parts

The previous version of Web Parts consisted of a dashboard server and a store interface. The dashboard server was a Web server that included a dashboard factory (a processing engine that generated HTML pages that contained presentation information for assembling Web Parts into a dashboard), a Digital Dashboard Service Component (DDSC) object reference, and schema information. Dashboard and Web Part definitions were stored in a database, such as Microsoft® SQL Server™ 2000 or the Microsoft SharePoint Portal Server 2001 store. Dashboards implemented the document store interface as an Active Server Page (ASP).

In the dashboard context, the ContentType property specified the type of the Web Part and determined how the Web Part was rendered, so type data and instance data were the same thing. This model facilitated exporting and reusing a Web Part on another computer. However, it also encouraged the existence of multiple copies of your Web Part logic, which made deploying updates to your Web Part difficult.

Web Parts in the Web Part Infrastructure

The Web Part infrastructure introduces several significant changes in the Web Part rendering model. Rendering in the Web Part infrastructure is based on the ASP.NET architecture. Web Part type data and instance data are separate. The logic for all Web Parts is located within the class, which always derives from the Microsoft.SharePoint.WebPartPages.WebPart base class.

There is one class for each type of Web Part on the server. However, the instance data varies from instance to instance of a Web Part, and it is stored in a database, similar to earlier dashboard applications such as SharePoint Portal Server 2001.

In addition to improving Web Part compatibility with ASP.NET server controls, this architecture change improves security and manageability.

Web Part Pages Overview

To ensure compatibility with ASP.NET, the Web Part infrastructure replaces dashboards with the new WebPartPage object. Instead of using a Dashboard folder to store the Web Parts associated with a Web page, you now use the WebPartPage object.

Web Part Class Overview

For the ContentType property, Web Part classes provide an infrastructure for rendering that is similar to dashboard Web Parts. You may need to adapt existing .dwp files before you can use them with the new Web Part infrastructure. For more information about how to do this, see the "Modifying .dwp Files" section in this white paper.

Converting Web Parts to the Web Part Infrastructure

To convert a dashboard Web Part to the Web Part infrastructure, you must first create a new Web Part class. You can either choose an existing Web Part class or write a new Web Part class. If the ContentType property in the legacy Web Part equals HTML or XML, one of the built-in classes listed in the "Using Built-In Web Parts" section of this white paper may be appropriate. If the ContentType property equals VBScript or JavaScript, you must write a new Web Part class and install it on the server. All built-in Web Parts are server-side controls.

Using Built-In Web Parts

The following Web Part infrastructure-based Web Parts are included in Windows SharePoint Services and SharePoint Portal Server 2003:

  • Content Editor Web Part
  • XML Web Part
  • Page Viewer Web Part
  • Image Web Part

    Note   These Web Parts are sealed classes. You cannot derive new classes from them.

If you have any of the following requirements, consider using the built-in Web Parts.

  • Minimizing installation and deployment costs - Blank versions of the built-in Web Parts are available in the Web Part Gallery. For built-in Web Parts that contain prepopulated content, administrators need to make only the .dwp file available to users. They do not need to install a separate dynamic-link library (DLL) and add it as a safe server control.
  • Minimizing maintenance costs - Changes to the Web Part are applied only to the .dwp file, so changes do not require you to recompile and reinstall the DLL.
  • Increasing portability for a Web Part - To share a Web Part, you can simply export and send the .dwp file to other users in an e-mail message.

Review the following descriptions to determine which specific Web Part to use.

Content Editor Web Part

The Content Editor Web Part (class: Microsoft.SharePoint.WebPartPages.ContentEditorWebPart) displays both HTML content and script-based content. The Web Part may store the content in a property or it may link to content in a source file. A rich text editor provides quick text formatting.

Use this Web Part if the ContentType property for your dashboard Web Part was equal to HTML or XML and the RequiresIsolation property was set to False. Use this Web Part for the following requirements:

  • You want to permit users to quickly enter richly formatted text
  • You want to display content that is editable by users with the appropriate permissions.
  • You want to use Microsoft JScript® or Microsoft Visual Basic Scripting Edition (VBScript) to develop the functionality of the Web Part.
  • You want to incorporate existing JScript or VBScript files into a Web Part.
  • You do not need to use the built-in Web Part connection interfaces to connect your Web Part.
  • Client-side script is not a security concern.

XML Web Part

The XML Web Part (class: Microsoft.SharePoint.WebPartPages.XmlWebPart) displays XML that has been transformed on the server by using XSL. The Web Part stores the content in a property or links to a source file. Use this Web Part for the following requirements:

  • You want to represent existing structured data as XML and transform it by using XSL on the server.
  • You want to display content that is editable by users with the appropriate permissions.

Page Viewer Web Part

Use this Web Part if the ContentType property for your dashboard Web Part was equal to HTML and the RequiresIsolation property was set to True. Use this Web Part for the following requirements:

  • You want to incorporate existing content (such as a Web site or document) into a Web Part.
  • You want to display existing content with no additional functionality.
  • You want to display an entire Web page within a Web Part.
  • You want to isolate a Web Part from the rest of the Web Part Page. The IFRAME element prevents script that runs in the Web Part from interfering with other Web Parts on the same page.
  • You want to use nested forms. Web Part Pages are ASPX pages that use ASP.NET server controls. Nested forms are not permitted inside of an ASP.NET server control unless they are isolated with an IFRAME element. Because the Page Viewer renders content within an IFRAME element, you can use it to display pages that contain a <form> tag.
  • You want to retrieve data from a server that requires authentication. In this case, the Page Viewer Web Part forwards authentication credentials from the client.

Image Web Part

The Image Web Part (class: Microsoft.SharePoint.WebPartPages.ImageWebPart) displays a linked image. It also supports Web Part Connections between compatible Web Parts. Use this Web Part for the following requirements:

  • You want to link to and display existing images by using a Web Part with no additional functionality.
  • You want to connect the Image Web Part to other Web Parts that use Web Part connections. For example, you want to connect an Image Web Part to a list of team contacts that includes image paths. When you select a contact, the Team Contacts Web Part passes the Image Path through the connection to the Image Web Part.

Writing Custom Web Parts

If the built-in Web Parts do not meet your needs, you can write a custom Web Part. Writing a custom Web Part requires a development tool such as Microsoft Visual Studio® .NET. Custom Web Parts must derive from the Microsoft.SharePoint.WebPartPages.WebPart base class. For more information about how to create a Web Part, see the SharePoint Products and Technologies SDK.

You can write custom Web Parts for any of the following purposes:

  • Creating custom properties and using the Web Part infrastructure to display them in the tool pane.
  • Creating custom Tool Parts in the tool pane.
  • Creating a base class for other Web Parts to extend. For example, to create a collection of Web Parts with similar features and functionality, create a custom base class from which multiple Web Parts can inherit. This reduces the overall cost of developing and testing subsequent Web Parts.
  • Improving performance and scalability. A compiled custom Web Part runs faster than a script.
  • Securing and controlling access to content within the Web Part. The built-in Web Parts allow any users with appropriate permissions to change content and alter Web Part functionality. With a custom Web Part, you can determine the content or properties to display to users, regardless of their permissions.
  • Making your Web Part connectable by implementing one or more of the defined Web Part Connection interfaces. This allows the custom Web Part to provide or access data from other connectable Web Parts.
  • Interacting with the object models that are exposed in SharePoint Products and Technologies. For example, you can create a custom Web Part to save documents to a Windows SharePoint Services document library.
  • Controlling the cache for the Web Part by using built-in cache tools. For example, you can use these tools to specify when to read, write, or invalidate the Web Part cache.
  • Benefiting from a rich development environment with debugging features that are provided by tools such as Visual Studio .NET.
  • Implementing proprietary code without disclosing the source code.
  • Controlling the implementation of the Web Part. For example, you can write a custom server side Web Part that connects to a back-end database, or you can create a Web Part that is compatible with a broader range of Web browsers.

Creating Custom Parts

This section outlines some considerations for creating custom Web Parts. For thorough documentation of steps and programming tasks, refer to the "Web Part Infrastructure" section of the SharePoint Products and Technologies SDK.

All custom Web Parts are derived from the Microsoft.SharePoint.WebPartPages.WebPart base class. This class provides basic properties that are common to all Web Parts, such as Title, Description, AllowRemove, and so on. You can add any necessary custom properties to your derived class. At run time, the two sets of properties are presented and run as a single set of properties.

Some Web Part properties function differently in the Web Part infrastructure than they did in the Digital Dashboard technology. Additionally, some properties from dashboard Web Parts are obsolete.

ContentType Property and Content Property

The ContentType property and Content property in dashboard Web Parts no longer exist in the Microsoft.SharePoint.WebPartPages.WebPart base class in the Web Part infrastructure. The content type is now inferred from the built-in Web Part class that you choose for your Web Part. When the Web Part is displayed, the Web Part infrastructure creates an instance of the appropriate class, which manages and displays the instance data for the Web Part.

If the ContentType property in your dashboard Web Part equals VBScript or JScript, use the appropriate managed language (such as C# or Visual Basic .NET) to create a new class to display the content. The code in the Init function in Digital Dashboard is now executed in the PreRender event in the Web Part infrastructure. Additionally, the code in the getContent function in Digital Dashboard is now executed in the overridden RenderWebPart method in the Web Part infrastructure.

To execute code in the PreRender event, add an event handler to the derived class as in the following example:

private void OnPreRender(object sender, EventArgs e)
{
// Do init() work here
}

Next, attach the OnPreRender handler by adding the following line of code to the constructor for the Web Part:

this.PreRender += new EventHandler(OnPreRender);

Every derived Web Part must implement the RenderWebPart method, as in the following example:

protected override void RenderWebPart (HtmlTextWriter writer)
{
// Do getContent() work here
}

Developers who are familiar with implementing dashboard Web Parts know that the Init and getContent functions take a single argument. This argument is the XML Document Object Model (DOM) for the specific Web Part instance. When working with a dashboard Web Part, a developer can use the XML DOM to inspect or change the properties of the Web Part during run time. In the Web Part infrastructure, the XML DOM is no longer required. To inspect or change the properties for the current Web Part instance, use the this keyword in C#, or the Me keyword in Visual Basic .NET.

Zone Property

With Digital Dashboard technology, a Web Part was located in one of five hard-coded zones. These zones always retained the same position in the layout of a Web page. The zones were referred to by number. The ASP.NET model provides greater flexibility within the Web Part infrastructure. You can create as few or many zones as necessary and change their position in the page layout.

The Zone property is no longer supported in the Web Part infrastructure. Consistent with ASP.NET, Web Parts no longer refer to a specific zone number. Instead, Web Parts store the ID of the associated zone in the ZoneID property. The Web Part infrastructure renders the Web Part instances within the appropriate Zone as child controls.

XSL Property and XSLLink Property

With dashboard technology, you could write a Web Part that used a VBScript function or a JScript function in the Content property to generate XML . You could then have that XML transformed by XSL located in the XSL property or by XSL that was linked by using the XSLLink property.

To implement this functionality in the Web Part infrastructure, you can either use the built-in XML Web Part or create a custom Web Part. The base class in the Web Parts infrastructure no longer contains the XSL property and XSLLink property, because these properties are no longer required. To expose these properties to your users, you must add these custom properties to a derived class. Alternatively, you can include the XSL in your assembly or load the XSL directly from the file system.

After you choose a storage option for the XSL, you must apply it to the XML. If the XSL is in a string variable, use the XslTransform object to perform the transform in the RenderWebPart method. You may experience a time delay before result of the xslt.Load function is returned. A good practice is to implement the code in a secondary thread with a timeout mechanism. The following example shows how to apply an XSL transform to XML data.

internal string ApplyXslt (string contents, string transform, string transformLink)
{
    // Create a new transform object.
    XslTransform xslt = new XslTransform();   
    try
    {
        if (transformLink != null && transformLink.Length > 0)
        {
        // attempt to perform XSLT transform using transformLink.
            xslt.Load(transformLink);
        }
        else
        {
            if (transform != null && transform.Length > 0)
            {
                // attempt to perform XSLT transform using transform.
                xslt.Load(new XmlTextReader(new 
                    StringReader(transform)));
            }
            else
            {
                // return the original content if there is nothing toprocess
                return contents; 
            }
        }

    // Read the current contents of the part into an XPathDocument.
    XPathDocument xml = new XPathDocument(new
         StringReader(contents)); 

    // Create a stream on top of a string builder for output.
    StringWriter stmOut = new StringWriter(new StringBuilder());

    // Transform and return.
    xslt.Transform(xml, null, stmOut);
    return stmOut.ToString();
    }
    catch
    {
        // return error message.
        return "Failed to load or apply XSLT.";
    }
}

PartStorage Property

In dashboard Web Parts, the PartStorage property provided flexible storage. However, as the Web Part author, you had to manage the property and its data. For example, to use the PartStorage property to store three pieces of data you had to serialize each piece of data into a string and deserialize it out of the string.

The Web Part infrastructure identifies each piece of data as a separate property of the derived class. The PartStorage property that existed in dashboard Web Parts no longer exists in the base class in the Web Part infrastructure. This change provides type safety. For example, you can create a custom property with a specific data type. Additionally, the Web Part infrastructure can serialize Web Part properties automatically and display them in the built-in property sheet.

MasterPartLink Property

With Digital Dashboard technology, you could use the MasterPartLink property to update the properties of a specific Web Part from a source Web Part. The MasterPartLink property is not supported in the Web Parts infrastructure.

To emulate this functionality in the Web Part infrastructure, implement the following in a custom Web Part class:

  1. Sink the Init event.
  2. At the start of the Init event, use the WebClient object to get the data for the source Web Part.
    Note   The source Web Part must be stored as a .dwp file.
  3. Load the returned .dwp file into an XML DOM object.
  4. Parse the XML DOM object and set properties for the Web Part.

Resources

Dashboard Web Parts included Web Part Resources (WPR), which you could use to associate file-based resources with a specific Web Part instance. The resources remained with the Web Part when it was imported and exported. Additionally, the dashboard Web Part used a special token to resolve Uniform Resource Locators (URLs) to the WPR. For example, if a Web Part required an image file, you could associate the image with the Web Part as a WPR, and you could refer to the image by using the _WPR_ token. However, customers frequently used WPRs to store identical data with every instance of a Web Part, which created multiple copies of WPRs. The Web Part infrastructure resolves this issue by using class resources instead of instance resources.

Class resources are file-based resources that do not change from instance to instance and that you can associate with multiple Web Parts. Using the Web Part infrastructure, you can store class resources in two places: the Global Assembly Cache (GAC) or the BIN folder.

If you store an assembly in the GAC:

  • Store the resources in the following directory: local_drive:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\wpresources\assembly_name\Ver_PubKey
  • The Web Part uses the following URL for the resource: http://server_name/_wpresources/assembly_name/Ver_PubKey

If you store your assembly in the BIN folder:

  • Store the resources in the following directory: local_drive:\inetpub\wwwroot\wpresources\assembly_name
  • The Web Part uses the following URL for the resource: http://server_name/wpresources/assembly_name

Regardless of where you store the class resources, the ClassResourceUrl property of the base class of the Web Part returns the full URL for the class resource directory. For example, if an Expedia Travel Web Part that is stored in the GAC requests the Class Resource URL, the ClassResourceUrl property returns the following value:

http://server_name/_wpresources/ExpediaTravelParts

The Web Part uses this information to form the URL to the class resource. To use the Web Part class to access a culture-specific resource, you must manually concatenate the resource URL and the culture string. You can use the _WPR_ token to refer to this URL-addressable location by using a method similar to the method for dashboard Web Parts within a dashboard.

Tokens

The token-replacement scheme in the Web Part infrastructure introduces significant changes from the dashboard token-replacement scheme.

Dashboard Web Parts resolved several tokens automatically when the Web Part was rendered. For example, if you set the DetailLink property to "_WPR_/detail.htm?user=_LogonUser_", the Digital Dashboard technology converted this string to the following URL when it rendered the Web Part:

http://server_name/dashboard_name/Webpart_files/detail.htm?user=domain\username

Several of the tokens used in dashboards are no longer supported in the Web Part infrastructure. Most of these tokens were associated with the Dashboard object, which no longer exists in the Web Part infrastructure

The following table shows a list of descriptions and recommendations for possible substitutions for tokens that are no longer supported in the Web Part infrastructure.

TokenDescriptionSubstitution
_CanPersonalizeWebPart_Returns 1 if the current user is permitted to personalize the current Web Part; otherwise, 0.Write a custom Web Part class and refer to the Permissions property of the Web Part base class.
_CanModifyWebPart_Returns 1 if the current user is permitted to customize the current Web Part; otherwise, 0.Write a custom Web Part class and refer to the Permissions property of the Web Part base class.
_LogonUserJS_Returns the current LogonUser variable, encoded for JavaScript.Write a custom Web Part class and refer to HttpServer.Variables("LOGON_USER")function. After the value is retrieved, encode it manually.
_DashboardID_Returns the opaque ID of the current dashboard.No substitution. The concept of a dashboard does not exist in Web Part infrastructure.
_WPC_Returns the content of the current Web Part.No substitution. This was a store-specific attribute of the Web Part. It is not applicable in the Web Part infrastructure.
_PartNamespace_Returns the namespace for the part.No substitution. The namespace was removed, so this token has no meaning in the Web Part infrastructure.
Note   The WebPartCaption_WPQ_ token is still supported. However, it is implemented as an ID that makes use of the _WPQ_ token.

Base Class Properties

The following table shows properties that are no longer supported in the base class. To emulate these properties, create a custom class or (if possible) use a built-in Web Part class that includes the required property.

Unsupported PropertyComment
CacheBehavior 
CacheTimeout 
ContentSupported by the Content Editor Web Part.
ContentLinkSupported by the Content Editor Web Part and the Page Viewer Web Part.
ContentType 
CustomizationLink 
LastModified 
MasterPartLink 
Namespace 
PartStorageSupported in the built-in Content Editor Web Part and XML Web Part.
RequiresIsolation 
Resource 
XSLSupported in the built-in XML Web Part.
XSLLinkSupported in the built-in XML Web Part.

The following table shows the old names and new names for the Base Class properties that are still supported in the Web Part infrastructure.

Dashboard propertyWeb Part infrastructure propertyComment
HasFrameFrameTypeHasFrame was a Boolean property. FrameType is an enumerated property that provides four different settings: None, Standard, TitleBarOnly, and Default. The NoOverride enumeration is replaced by the Default enumeration. Standard is referred to as "Title Bar and Border" in Windows SharePoint Services.
ZoneZoneID 

Converting Dashboards

This section describes how to convert dashboards for use in the Web Part infrastructure.

Web Part Service Component (WPSC) Object Name Change

The WPSC is the top-level object that provides access to all of the client-side components. In the Web Part infrastructure, Web Part Pages are the equivalent of dashboards in the Digital Dashboard infrastructure.

To be consistent with the new naming scheme, the Digital Dashboard Service Component (DDSC) is now named the Web Part Service Component (WPSC). You must use the Web Part Service Component to refer to all properties and methods of this client-side component, as shown in the following example:

WPSC.RegisterForEvent "urn:testchange", "onUpdate", GetRef ("ChangePic_WPQ_")

Dashboard Object Name Change

For consistency with the new naming scheme, the Dashboard object is now named the WebPartPage object. You must use the WebPartPage object to refer to all properties, methods, and collections of the Dashboard object, as shown in the following example:

intPartsCount = WPSC.WebPartPage.Parts.Count

WebPartID Property Name Change

For consistency with the new naming scheme, the WebPartID property of the Part object is now named the StorageKey property. If your code uses this property, you must update your code to use the StorageKey property.

LoadItem Method

The LoadItem method of the DDSC loaded a dashboard or Web Part from the store, even if it was not part of the current dashboard. The LoadItem method returned a pointer or handle to an Item object, which provided generic access to the content of an object in a store and to the collection of properties for the item. For example, you could use this method to build an administration page for a Web Part. In the Web Part infrastructure, the architecture for the administration of Web Parts has changed. Because of this, the LoadItem method and the Item object are meaningless in the Web Part infrastructure.

The following tables show the properties, methods, and collections of the Item object that are no longer supported.

PropertyDescription
ContentA string containing the content of an Item object.
IDA string identifier for an Item object.
ParentA handle to the parent of the current Item object.
MethodDescription
EditSecurityEnabled editing of the security descriptor or access control list (ACL) for the item.
SaveSaved new and changed property values to the store.
CollectionDescription
Properties CollectionReturned a pointer to a collection of Property objects that defined the state and characteristics of an Item object.
Contents CollectionReturned a pointer to a collection of child items for an Item object.

The following tables show the members of the Properties Collection of the Item object.

PropertyDescription
CountReturned the number of objects in a collection.
ItemReferenced an object in a collection by name or position.
_NewEnumReferenced objects in an enumerated collection.
MethodDescription
AddAdded a Property object to a collection.
RemoveDeleted a Property object from a collection.

The following tables show the members of the Content Collection of the Item object.

PropertyDescription
CountReturned the number of objects in a collection.
ItemReferenced an object in a collection by name or position.
_NewEnumReferenced objects in an enumerated collection.
MethodDescription
AddAdded a Property object to a collection.
RemoveDeleted a Property object from a collection.

"For Each. . .Next" VBScript Syntax

In the Digital Dashboard technology, two versions of the DDSC were available: the JScript version and the ActiveX version. In the Web Part infrastructure, only the JScript version of the WPSC is available. JScript does not support the _NewEnum property. Because of this, the _NewEnum property is not supported in the WPSC.

The _NewEnum property is not referred to directly, but most programming and scripting languages use it to support the enumeration of object collections in COM and COM+ libraries and assemblies. For example, in VBScript, the _NewEnum property supports the For Each...Next syntax. Because the Web Part infrastructure no longer supports the _NewEnum property, you must convert any VBScript code that uses the For Each. . .Next syntax to use the For. . .Next syntax or some other mechanism for looping through a collection.

Example: Dashboard

<SCRIPT language="VBScript">
    'Parts on the Web Part Page
    Dim objParts_WPQ_
    Dim objPart_WPQ_
    Dim intCounter_WPQ_
    'Initialize values
    objParts_WPQ_ = DDSC.Dashboard.Parts
    intCounter_WPQ_= 0
    'Loop through parts
    For Each objPart_WPQ_ in objParts_WPQ_
        Document.Write "<br>"
        Document.Write intCounter_WPQ_
        intCounter_WPQ_= intCounter_WPQ_+ 1
    Next
</SCRIPT>

Example: Web Part infrastructure

<SCRIPT language="VBScript">
    'Parts on the Web Part Page
    Dim objParts_WPQ_
    Dim intPartsCount_WPQ_
    Dim intCounter_WPQ_

    'Initialize values
    intPartsCount_WPQ_= WPSC.WebPartPage.Parts.Count

    'Loop through parts
    For intCounter_WPQ_= 0 to intPartsCount_WPQ_ - 1
        Document.Write "<br>"
        Document.Write intCounter_WPQ_
    Next
</SCRIPT>

Additionally, to step through a collection, you must state the Item property (for example, collection.Item(index)).

Example: Dashboard

varPart_WPQ_.Properties(iProp_WPQ_).Value 

Example: Web Part infrastructure

varPart_WPQ_.Properties.Item(iProp_WPQ_).Value

Session State

The following table describes session state methods that are no longer supported. To emulate this functionality, you must use cookies.

MethodDescription
GetSessionStateMemory session data that was previously saved in the current session.
PutSessionStateMemory session data so that it was available to all Web Parts in a dashboard.
ClearSessionStateMemory session data that was previously saved.

The following examples show how to use cookies to emulate session state functionality.

PutSessionState

function PutSessionState(Namespace URN, Name, Value)
{
    document.cookie = NamespaceURN + "::" + Name + "=" + escape(Value);
}

GetSessionState

function GetSessionState(NamespaceURN, Name)
{
//This function searches through the document cookie
//for a crumb matching the provided Namespace and Name
//and returns its value.
//split crumbs into an array 
    var aCookie = document.cookie.split(";");
    for (var i=0; i < aCookie.length; i++)
    {
        //Split name and value of crumb into an array
        var aCrumb = aCookie[i].split("=");

        //Trim spaces
        var sCookie = Trim(aCrumb[0]);
        if (sCookie == NamespaceURN + "::" + Name)
            return unescape(aCrumb[1]);
    }
    //cookie not found
    return;
}
function Trim(sIn)
{
    var c;
    var sOut;
    for(var i=0, c=sIn.charAt(i); i<sIn.length, c==" "; i++,
        c=sIn.charAt(i));
        sOut = sIn.substr(i);
        for(i=sOut.length-1, c=sOut.charAt(i); i>=0, c==" "; i--, 
            c=sOut.charAt(i));
            sOut = sOut.substr(0, i+1);
    return sOut;
}

ClearSessionState

function ClearSessionState(NamespaceURN, Name)
{
    document.cookie = NamespaceURN + "::" + Name + "=; expires=" + "1/1/1980".toGMTString;
}

Add and Remove Methods

In dashboard Web Parts, you used the Add method to add an object to the Content Collection or Properties Collection. You also used the Remove method to remove an object from these collections. The Content Collection does not exist in the Web Part infrastructure. Because of this, you cannot dynamically add or remove these properties. You must specify properties as part of the class definition.

Save Method Parameters

In dashboard Web Parts, you used the Save method to save a new or modified property to the store. In the Web Part infrastructure, this method applies to the WebPart object. The Web Part infrastructure improves the behavior and functionality of this method. However, the parameters for this method have changed. For more information about these changes, see the Microsoft.SharePoint.WebPartPages namespace reference page in the SharePoint Products and Technologies SDK.

Web Part Property Namespace Change

Do not use the "urn:schemas-microsoft-com:webpart:" namespace to get or set properties. Instead, use the following new namespace: "http://schemas.microsoft.com/WebPart/v2".

Element Referencing in a Form

HTML requires that you use the document.all collection to add a form ID or reference ID for every element in a form, as shown in the following JavaScript example:

<form id="MyForm" >
<input type="text" id="MyText" />
<input type="button" id="MyButton" onClick="buttonClicked"/>
<script>
function buttonClicked()
{
    MyForm.MyText.value = "Hello World!";
}
</script>
</form>

In the previous example, you could replace the element reference with the following line:

document.all("MyText").value= "Hello World!" 

You could not remove the MyForm element from the script.

Dashboard Web Parts did not reside within a form, so you could use scripts to refer to elements in a Web Part directly. Most legacy Web Parts did not use the document.all reference. To use a dashboard Web Part on a Web Part Page, make sure that the dashboard Web Part uses a form ID to refer to each element or that the dashboard Web Part uses document.all to refer to elements if the Web Part uses and references an <input> tag. When you create a new Web Part, you can use the document.all["mycontrol"] collection or the document.forms[0].mycontrol collection.

Form Migration

A Web Part Page uses a form to contain all Web Parts. Web Part Pages are ASP.NET pages, and Web Parts are a variation of an ASP.NET server control.

Nested Forms

As an ASP.NET server control, a Web Part should not include <form> tags because these tags are not compatible with Web Part Pages. For server-side script Web Parts, use the appropriate ASP.NET server controls for input boxes, as specified in the guidelines for building ASP.NET pages. For client-side script Web Parts, use <form> tags in an inline frame. For example, the built-in Page Viewer Web Part uses an inline frame to isolate content.

Modifying .dwp Files

The .dwp format for the Web Part infrastructure is similar to the format that was used in dashboards. Each .dwp file is an XML file. The top node is the <WebPart> tag. You must convert dashboard .dwp files to use them in the Web Part infrastructure.

Custom properties in the built-in parts have unique namespaces. For example, in a .dwp file used with dashboard Web Parts, the Content property of the Content Editor Web Part might be similar to the following:

<Content>This is my content</Content>

With the new namespaces in the Web Part infrastructure .dwp files, the Content property might be similar to the following:

<Content xmlns="http://schemas.microsoft.com/WebPart/v2/ContentEditor">This is my Content</Content>

This change affects the Content Editor, Page Viewer, and XML Web Parts. The following table shows the namespace changes and the affected Web Parts.

Web PartNamespaceCustom Properties
Content Editorhttp://schemas.microsoft.com/WebPart/v2/ContentEditorContent, ContentLink, PartStorage
Page Viewerhttp://schemas.microsoft.com/WebPart/v2/PageViewerContentLink, SourceType
XML http://schemas.microsoft.com/WebPart/v2/XmlXML, XMLLink, XSL, XSLLink, PartStorage

To convert a .dwp file, follow these steps:

  1. Change the namespace to reflect the change from Digital Dashboard technology to the Web Part infrastructure. For example:

    Digital Dashboard:

    <WebPart xmlns="urn:schemas-microsoft-com:webpart:">
    
    

    Web Part infrastructure:

    <WebPart xmlns="http://schemas.microsoft.com/WebPart/v2">
    
    
  2. Use the <Assembly> node to specify the name of the assembly.

    Use the <TypeName> node to specify the name of the class for your Web Part. For example:

    <WebPart xmlns="http://schemas.microsoft.com/WebPart/v2">
        <Assembly>Company.Product.dll</Assembly>
    <TypeName>Company.Product.MyWebPart</TypeName>
    ...
    </WebPart>
    
    
    Note   You must complete this step to associate the instance data with a class. For example, the following list shows the type names for the Content Editor Web Part, the Page Viewer Web Part, and the XML Web Part.
    • Microsoft.SharePoint.WebPartPages.ContentEditorWebPart
    • Microsoft.SharePoint.WebPartPages.PageViewerWebPart
    • Microsoft.SharePoint.WebPartPages.XmlWebPart
  3. Change enumerated property values from numeric format to text format as specified in the .NET framework. For example:

    Digital Dashboard:

    <WebPart xmlns="urn:schemas-microsoft-com:Webpart:">
    <Assembly>Company.Product.dll</Assembly>
    <TypeName>Company.Product.MyWebPart</TypeName>
    <IsIncluded>1</IsIncluded>
    <AllowMinimize>0</AllowMinimize>
    <FrameState>0</FrameState>
    ...
    </WebPart>
    
    

    Web Part infrastructure:

    <WebPart xmlns="http://schemas.microsoft.com/WebPart/v2">
    <Assembly>Company.Product.dll</Assembly>
    <TypeName>Company.Product.MyWebPart</TypeName>
    <IsIncluded>true</IsIncluded>
    <AllowMinimize>false</AllowMinimize>
    <FrameState>Normal</FrameState>
    ...
    </WebPart>
    
    
  4. Convert any legacy XSL to XSL/T for compatibility with the XSL transform engine in the .NET Framework.
  5. Remove unsupported properties from the .dwp file to prevent an import failure. For a list of obsolete or unsupported properties, see the "Base Class Properties" section of this white paper.
  6. Rename properties as specified in the list of renamed properties in the "Base Class Properties" section of this white paper.
  7. Remove the <Resource> nodes from the .dwp file to remove the Web Part Resources that are associated with the Web Part instance.

Examples of .dwp Files

The dashboard version of a .dwp file for the Content Web Part may be similar to the following example:

<?xml version="1.0"?>
<WebPart xmlns="urn:schemas-microsoft-com:webpart:">
    <Title>Content Editor Web Part</Title>
    <Description></Description>
    <Content><![CDATA[Hello, world.]]></Content>
    <ContentLink></ContentLink>
    <XSL></XSL>
    <XSLLink></XSLLink>
    <MasterPartLink></MasterPartLink>
    <RequiresIsolation>0</RequiresIsolation>
    <ContentType>0</ContentType>
    <IsIncluded>1</IsIncluded>
    <AllowRemove>1</AllowRemove>
    <IsVisible>1</IsVisible>
    <FrameState>0</FrameState>
    <AllowMinimize>1</AllowMinimize>
    <HasFrame>1</HasFrame>
    <Zone>3</Zone>
    <PartOrder>0</PartOrder>
    <PartImageSmall></PartImageSmall>
    <PartImageLarge></PartImageLarge>
    <CustomizationLink></CustomizationLink>
    <CacheBehavior>0</CacheBehavior>
    <CacheTimeout>0</CacheTimeout>
    <PartStorage></PartStorage>
    <Namespace></Namespace>
    <Height></Height>
    <Width></Width>
    <DetailLink></DetailLink>
    <HelpLink></HelpLink>
</WebPart>

The Web Part infrastructure version of a .dwp file for the Content Web Part may be similar to the following example:

<?xml version="1.0" encoding="utf-8"?>
<WebPart xmlns="http://schemas.microsoft.com/WebPart/v2">
<Assembly>Microsoft.SharePoint, Version=11.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c</Assembly>
<TypeName>Microsoft.SharePoint.WebPartPages.ContentEditorWebPart</TypeName>
<Title>Content Editor Web Part</Title>
<Description />
<Content xmlns="http://schemas.microsoft.com/WebPart/v2/ContentEditor" />
<ContentLink xmlns="http://schemas.microsoft.com/WebPart/v2/ContentEditor" />
<IsIncluded>true</IsIncluded>
<AllowRemove>true</AllowRemove>
<IsVisible>true</IsVisible>
<FrameState>Normal</FrameState>
<AllowMinimize>true</AllowMinimize>

Developing Dashboard Web Parts that Are Easy to Convert

As you continue to develop dashboard Web Parts for SharePoint Portal Server 2001, use the following recommendations to facilitate moving to the Web Part infrastructure.

  • Keep the following general recommendations in mind:
    • Use XSL/T instead of XSL.
    • Do not use deprecated DDSC objects, properties, or methods.
    • Do not use deprecated base class properties.
    • Do not use deprecated tokens.
  • Be aware of the caching behavior changes in the Web Parts architecture.
  • Use .NET code as much as possible to reduce or eliminate server-side script code in your Web Parts. To do this, use one of the following methods.

Using a Web Service for Data Manipulation:

To use a Web Service for data manipulation, design your dashboard Web Parts to separate the presentation code from the nonpresentation code. To do this, follow these steps:

  1. Use a Web Service to encapsulate your nonpresentation code.
  2. Create a script-based dashboard Web Part that uses the ServerXMLHTTP object to obtain data from the Web Service.
  3. Format your data with XSL/T. Avoid using the Digital Dashboard factory XML formatting functions, which expect XSL-formatted data.

When you move to the Web Part infrastructure in Windows SharePoint Services and SharePoint Portal Server 2003, you can retain the Web Service and the custom XSL/T data manipulation. However, you must use the WebPart base class or one of the built-in Web Parts in the Web Part infrastructure to rewrite the client-side script and the user interface.

Note   Depending on an external Web Service may have scalability implications, depending on frequency of data access, caching behavior, and other factors.

Using an ASP.NET Page for Data Manipulation:

This method represents a larger departure from the dashboard Web Parts programming model, but it presents far fewer migration challenges. To use an ASP.NET page for data manipulation, follow these steps:

  1. Create an ASP.NET server control that contains as much nonpresentation code and as much presentation code as you want.
  2. Embed this server control in an otherwise empty ASP.NET page and set the margins for the page to zero.
  3. Specify the ASP.NET page as the content link in your dashboard Web Part.
  4. Configure the dashboard Web Part as "isolated." When you do this, the Web Part is rendered in an IFrame.

When you move to the Web Part infrastructure, you only have to modify the server control to inherit from the new WebPart base class.

Conclusion

The Web Part infrastructure introduces several significant changes in the Web Part rendering model. Rendering in the Web Part infrastructure is now based on the ASP.NET architecture. Because of these changes, you may need to modify your dashboard Web Parts to run in the new Web Part infrastructure. Depending on the nature of your legacy Web Part, you may be able to use a built-in Web Part such as the Content Editor Web Part, XML Web Part, Page Viewer Web Part, or Image Web Part, or you might have to write a custom Web Part. To successfully convert your dashboard Web Parts to the Web Part infrastructure, you must understand the changes to properties, namespace, resource handling, tokens, DDSC, and .dwp files that are described in this document. If you need to continue developing dashboard Web Parts, design them for easy future conversion to the Web Part infrastructure.

Show:
© 2014 Microsoft