Web Parts

Web parts, at their most basic level, are a type of composite Web control called a server control. A Web part is a container for other Web controls, such as labels, text boxes, and buttons. In addition to containing child controls, Web parts are designed to exist on Web part pages and to allow customization and personalization of those pages. Figure 12-2 shows a basic example of a Web part page.

Web part page containing Web parts

Figure 12-2. Web part page containing Web parts

Web Part Infrastructure

With the release of ASP.NET 2.0, Web parts moved from being exclusive to Windows SharePoint Services to becoming part of the larger .NET framework. Consequently, Windows SharePoint Services 3.0 has introduced an entirely new model for Web parts, although it maintains backward compatibility with legacy Windows SharePoint Services 2.0 Web parts. In several instances, a SharePoint Product and Technologies–specific version of the infrastructure extends the base ASP.NET implementation.

Web Part Manager

The principal improvement in the new ASP.NET Web part infrastructure is the addition of a Web Part Manager. The Web Part Manager serves as a central hub that has awareness of all Web parts on a page. SharePoint Products and Technologies uses a Web Part Manager in the Microsoft.SharePoint namespace. The actual Web Part Manager class that is used is Microsoft.SharePoint.WebPartPages.SPWebPartManager, which is derived from the ASP.NET System.Web.UI.WebControls.WebParts.WebPartManager.

There must be one, and only one, Web Part Manager on a page that is to host Web parts. Furthermore, the Web parts should reside within Web part zones. Web parts that reside outside of a Web part zone will not provide full Web part functionality and will have limited interaction with the Web Part Manager.

The Web Part Manager provides the following functionality:

  • Tracks controls, including Web parts, Web part zones, and Web part connections

  • Manages adding, deleting, and closing Web parts on a page

  • Creates and manages connections between Web parts

  • Manages moving controls between zones

  • Allows personalization of which Web parts are on a page, where they are located, and per-user settings for the Web part’s properties.

  • Switches page views, allowing users to edit Web parts and move them between zones

  • Controls and raises all Web part life cycle events

  • Imports and exports Web part property XML files (.webpart or .dwp), allowing property settings to be persisted and shared among users

The SPWebPartManager is able to provide a path to Web part external resource files. The GetClassResourcePath method will return a path that assumes successful deployment to the appropriate standard location for the resources. It will not verify that the resources exist or search for them.

The following code snippet demonstrates retrieving the appropriate external resource path for a Web part assembly:

string webpartResourcePath = SPWebPartManager.GetClassResourcePath
  (Microsoft.SharePoint.SPContext.Current.Web,this.GetType());

With the notable exception of Application.master, all SharePoint Products and Technologies master pages include a SPWebPartManager. Therefore, other than application pages and pages that reference a custom master page, it is safe to assume that a Web Part Manager will be available. Unless business requirements dictate that a master page will never be used with Web parts, it is a best practice to include a SPWebPartManager when creating custom master pages.

Web Part Zone

One or more Web part zones should exist on a page that is to host Web parts. If a Web part is added to a page outside of a Web part zone, that Web part will not provide full Web part functionality. The fully qualified name of the Web part zone used by SharePoint Products and Technologies is Microsoft.SharePoint.WebPartPages.WebPartZone, and it inherits from the ASP.NET implementation System.Web.UI.WebControls.WebParts.WebPartZone. Note that, although the Web part zone does not have the SP prefix associated with many SharePoint Products and Technologies controls, it is in the Microsoft.SharePoint namespace. In addition to providing a container for Web parts, Web part zones work in conjunction with the Web Part Manager to serialize Web part property values to the content database. Finally, the Web part zone provides a common means for affecting the styles that frame Web parts within the zone (for instance, the appearance of borders around Web parts).

Editor Zone and Tool Parts

In addition to Web part zones, ASP.NET also implements tool zones. There are three varieties of tool zones: editor zones, connection zones, and catalog zones. Of particular interest to SharePoint Product and Technologies developers is the editor zone, from which the tool pane derives. The tool pane allows users to specify values to customize the appearance, behavior, and content of Web parts via tool parts. Tool parts are server controls that provide an interface for displaying and editing the values of Web part properties. By default, when a Web part is edited, the tool pane will display the WebPartToolPart and the CustomPropertyToolPart. The WebPartToolPart will display all of the base class properties of the Web part. The CustomPropertyToolPart will provide a default interface to display any custom properties of the Web part. It is possible to override the GetToolParts method of a Web part to return a custom set of tool parts. The GetToolParts method returns an array of tool parts that will be displayed in the order that they occur in the array. Therefore, when you override the GetToolParts method, you can display custom tool parts in place of or before the defaults. The default tool parts must be explicitly added to the array of tool parts if they are to be displayed when GetToolParts is overridden. It is a best practice to provide editor parts to facilitate configuration of Web parts that have non-trivial combinations of properties.

Web Parts

Web parts provide discrete, modular, reusable functionality that can be combined and connected and that allow users to configure their appearance, behavior, and content. Individual Web parts are not a replacement for either a traditional Web-based application or even most pages of an application. Web parts should be combined to provide complete Web-based solutions. It is a best practice to limit Web parts to provide a single function that is implemented as generically as possible to encourage re-use. One of the key concepts of Web parts is that they should be designed to allow as much user configuration as possible. To do so, careful consideration should be given to any requirements that may change over time and whether those requirements could be met using user-configurable properties. For instance, it might be valuable to use Web part properties to allow users to alter which columns are displayed from a database or the titles that are given to items within the Web part.

Web parts provide a tremendous maintenance advantage even when they cannot be serviced by power users. Because of their re-usable nature, an improvement to one Web part can be readily reflected in all existing instances of the Web part by updating the appropriate assemblies. To limit the scope of modifying a Web part, a new Web part can be created based on an existing one, and then selected Web parts can be replaced with the new version. Web part development should also leverage as much native SharePoint Product and Technologies capability as possible. A useful goal for Web part development is a solution that utilizes lists, views, and preexistent Web parts, whether native or custom.

ASP.NET and Windows SharePoint Services 3.0 Web Parts

Although SharePoint Products and Technologies utilizes a new Web part infrastructure based upon ASP.NET 2.0, there are several differences between their implementations. One of the greatest differences is that ASP.NET supports hosting non-Web part controls as Web parts when they are placed in a Web part zone. When a user control or server control is placed within an ASP.NET Web part zone, it is wrapped by the GenericWebPart wrapper class, which provides Web part functionality. The SharePoint Products and Technologies implementation of Web parts does not support automatically wrapping non-Web part controls so that they behave as Web parts, although this can be achieved through other means. SharePoint Products and Technologies does offer a preexistent, standardized method for implementing Web part personalization. ASP.NET implements the SQLPersonalizationProvider class, whereas SharePoint Products and Technologies implements a personalization provider that integrates with and leverages the Windows SharePoint Services infrastructure. Finally, remember that SharePoint Products and Technologies requires specific versions of the Web part infrastructure that are located within the Microsoft.SharePoint namespace.

Legacy and ASP.NET Web Parts

Within SharePoint Products and Technologies, there two different options for creating Web parts: ASP.NET 2.0 Web parts and Windows SharePoint Services 3.0–specific Web parts. To create a custom ASP.NET 2.0 Web part, a class should inherit from System.Web.UI.WebControls.WebParts.WebPart. Alternatively, a Windows SharePoint Services 3.0 Web part can be created by inheriting from Microsoft.SharePoint.WebPartPages.WebPart. It is always a best practice to fully qualify when inheriting, and the two possible Web part classes only underscore this general best practice for Web part development. Microsoft recommends using standard ASP.NET Web parts whenever possible, and you should consider that as a best practice. The Windows SharePoint Services 3.0 Web part implementation was created principally for backward compatibility, and Web parts that inherit from it will not work in a generic ASP.NET context. That said, Windows SharePoint Services 3.0 Web parts do provide functionality not included in ASP.NET Web parts, such as the following:

  • Cross-page connections

  • Connecting Web parts outside of Web part zones

  • Utilizing SharePoint content database caching

Rarely would any of the preceding functionalities justify creating a Windows SharePoint Services 3.0 Web part. If cross-page connections are desired, current ASP.NET Web parts should be engineered to provide the required functionality while remaining within the modern framework. If preexistent Web parts are to be connected across pages, you should consider modifying the existing Web parts to support the cross-page functionality. If it is not practical to modify Web parts that are already in use, then it might be possible to create proxy Web parts that would remain hidden on a page but would handle the cross-page connections.

Although Web parts can be connected outside of Web part zones, doing so is generally bad practice. Web parts that are outside of Web part zones will not provide full Web part functionality. If the layout of a page requires the placement of a Web part outside of a Web part zone, you should consider using a different page layout or altering the current layout to include a new Web part zone. Although every effort should be made to create Web parts that function efficiently, a Web part that cannot be made to perform effectively without the data caching abilities of the legacy-compliant Web part class is likely approaching the edge of current Web part technology. Such a Web part should be carefully vetted before its design is approved. It is a best practice to always create ASP.NET Web parts unless it is impossible to meet business requirements without using backward-compatible Web parts.

Web Part Connections

One of the most useful features of Web parts is their ability to be connected together. Prior to their inclusion in the ASP.NET 2.0 framework, Web part connections were delegate based, with Web parts directly raising events on the Web parts to which they were connected. With the creation of the Web Part Manager, Web parts are now controlled in a hub-based model, and the Web Part Manager is responsible for managing all connections. One of the principal differences that will be noticed in the new implementation is that Web parts can provide a connection to as many consumers as desired, but can consume only a single connection per named connection point. The Web part class in the Microsoft.SharePoint.WebPartPages namespace will allow unlimited consumer connections, but this would generally not be a reason to implement a backward-compatible Web part. However, if the decision is made to implement backward-compatible Web parts for the purposes of unlimited connections, it is a best practice to ensure that the Web part consumes unlimited providers in a meaningful way. For instance, it is acceptable to create a Web part that will consume an unlimited number of images and display them as a slide show or thumbnails. It is not acceptable to create a Web part that will accept an unlimited number of images but will display only the last image provided to it.

Creating multiple connections is not difficult when you use ASP.NET Web parts. Each connection point must simply have a unique ID. Unfortunately, one possible constructor for Web parts connection consumers provides a default ID of "Default." Because this is the simplest constructor to employ and because it works for the first consumer connection, you may become confused when you try to implement a second consumer connection. Therefore, it is a best practice to give every Web part connection an explicitly defined, unique ID. It is also possible to implement connections of more than one type per Web part. The following code snippet is taken from an ASP.NET Web part that implements five connections of four different types. The first consumer connection uses the constructor that provides a default ID and is not best practice. The second and third connections implement the same interface but provide two unique connection points. The fourth connection implements an alternate custom interface, and the fifth uses the IWebPartRow interface that is the standard for legacy Web parts. The public methods have been named NameDoesNotMatter for illustration only. It is, of course, strictly best practice to give any method a meaningful name.

// This is not best practice! This should have an explicit, unique ID!
[System.Web.UI.WebControls.WebParts.ConnectionConsumer
   ("Default Connection ID=Default")]
  public void NameDoesNotMatterOne(IDefault defaultInterface)
  {
    _defaultProvider = defaultInterface;
  }

// This is best practice, this provides an explicit unique ID.
[System.Web.UI.WebControls.WebParts.ConnectionConsumer
   ("Best Practice Connection 1","UniqueID_S")]
  public void NameDoesNotMatterTwo (IBestPractice aProviderInterface)
  {
    _aProvider = aProviderInterface;
  }

// Note that the name of the methods is not important.
[System.Web.UI.WebControls.WebParts.ConnectionConsumer
   ("Best Practice Connection 2", "UniqueID_D")]
  public void NameDoesNotMatterThree(IBestPractice bProviderInterface)
  {
    _bProvider = bProviderInterface;
  }

// Don't implement an alternate connection unless it will be meaningfully
// used. If the goal is to allow a Web part to use connections of Type A or
// Type B, implement a Web part transformer from Type B to Type A instead.
[System.Web.UI.WebControls.WebParts.ConnectionConsumer
   ("Alternate Connection", "Alt_UniqueID_G")]
  public void NameDoesNotMatterFour(IAlternate altProviderInterface)
  {
    _altProvider = altProviderInterface;
  }

// This is a legacy standard interface.
[System.Web.UI.WebControls.WebParts.ConnectionConsumer
   ("Web Part Row Connection","Row_UniqueID_JJ")]
  public void NameDoesNotMatterFive(IWebPartRow rowProviderInterface)
  {
    _rowProvider = rowProviderInterface;
  }

Finally, Web part connection points should be used for providing separate individual connections. They should not be used to allow connections of Type A or of Type B. If requirements dictate such a scenario, you should implement a Web part transformer instead. Web part transformers provide translation between interface types, allowing Type A to be converted to Type B. The transformation process is invisible to end-users when they create Web part connections. The only effect on the connection process that end-users will notice is the possibility of connecting Web parts in a greater number of ways. Web part transformers must be registered in the Web.config file of the appropriate Web application and will silently provide connection transformation once they are added.

Web Parts with User Controls

One of the most common requests for extended Web part functionality is the ability to host user controls (.ascx files) as Web parts. This is possible when you use Web parts in a generic ASP.NET setting, but not when you use Web parts in a SharePoint Products and Technologies context. The ability to leverage programmer experience with user controls when you create Web parts is compelling enough that generic user control Web part wrappers have been created for just that purpose. However, the process for hosting user controls within Web parts is simple enough that there is no reason that a generic wrapper must be used. To leverage user controls when creating Web parts, you should use the Page.LoadControl method to load the user control in the Web part’s class file. Use the this.FindControl method to reference controls from the user control’s code behind. An example of each is listed below:

// Use this in the Web part's class file to load the user control.
UserControl Yukon = Page.LoadControl("_controltemplates/BP/Yukon.ascx");

// Use this in the user control's code behind to reference
   // controls on the .ascx page.
Label bpLabel = this.FindControl("bestPracticeLabel") as Label;

If complete control over the code and security settings when creating Web parts is required, then you should consider creating Web parts that are fully owned by your organization to leverage user controls.

Web Part Verbs

One often-overlooked aspect of Web parts is the ability to add custom Web part verbs. Web part verbs are the actions that can be performed from a Web part’s menu. It is possible to add Web part verbs to a Web part by overriding the WebPartsVerbCollection of a Web part. Web part verbs can then be added to the Web part to fire either client side or server side. Web part verbs are an excellent way to allow users to perform discrete actions that integrate naturally with the SharePoint Products and Technologies look and feel. Consider using Web part verbs to perform actions such as refreshing the data in a Web part or allowing users to switch between custom display modes. Figure 12-3 shows an example of Web part verbs.

Web part verbs

Figure 12-3. Web part verbs

Customization and Personalization with Web Parts

When pages in SharePoint sites are discussed, the terms customization and personalization are often used. Customization refers to changes that are visible to all site members. Personalization refers to changes that are visible only to the site member making the change. The most common method of customizing a Web part page is the addition of a Web part to the page to display additional information. Other methods include removing Web parts and changing the order (left to right, top to bottom) of Web parts. Personalization usually involves reordering Web parts in order of relevance to the specific member and closing non-relevant Web parts.

Branding and Customization/Personalization

It is important to remember that neither customization nor personalizations are intended to change the branding of the site. When developing Web parts for use on Web part pages, you should use the class names as defined in the Microsoft Windows SharePoint Services 3.0 SDK. You can refer to the page titled Cascading Style Sheet Class Definitions for Windows SharePoint Services in the Reference section of the SDK.

Best practice mandates avoiding specifying style attributes directly on controls contained in a Web part if those attributes will override the branding specified in the page’s cascading style sheet or master page.

Provide a Consistent Method for Customizing and Personalizing a Web Part

Web part pages are used throughout the Windows SharePoint Services platform. Site members will be exposed to Web parts on almost every page. Users who have been exposed to the native Web part pages will have expectations about how Web parts are changed to suit their preferences. When developing custom Web parts, you should meet these expectations. For example:

  • Provide access to the properties that control the placement and relative order of the Web part.

  • Provide access to the properties that control the title and the page presented when the title is clicked.

  • Categorize your properties to distinguish them from common Web part properties.

  • Provide a custom tool part to contain your categories if you require multiple categories.

Figure 12-4 shows a Web part page in edit mode, which includes the tool pane on the right.

Web part tool pane

Figure 12-4. Web part tool pane

Properties and View/Control States

The ASP.NET framework provides a property bag to store the state of a control (or page) between page requests in a session. This facility is designed to work within the stateless nature of the HTTP protocol. Many properties of a control are placed into this property bag automatically, such as the initial value of a text box. The framework can then determine if a particular control has changed and act accordingly.

Web part properties are not designed to work in the same fashion. A property on a Web part control can be stored in a long-term fashion, not just between page requests in a session. Rather, they are persisted from one browser session to the next. Web part properties are changed via an EditorPart or a ToolPart in the Microsoft.SharePoint.WebPartPages.WebPart class and are not automatically set based on the current state of the Web part on the page.

Important

You should treat Web part properties like all other user input. One often-overlooked practice in Web part development is the validation of user-provided input. In this age of malicious code and denial-of-service attacks, it is important to use defensive techniques when dealing with user-provided data. You should validate the input to ensure that it falls within expected ranges and values. Data that is not valid should be rejected, and an appropriate message should be displayed in the ErrorUI section of the tool pane template.

Web Part Execution Environments

Web part assemblies run in a secure environment. This environment is controlled via Code Access Security (CAS) and is set on a Web application basis in the Web.config file. By default, Web applications in SharePoint are set to a minimum trust level. A medium trust level is provided in the CONFIG subfolder of the root SharePoint directory, also called the 12 hive. By default, the root folder is located at C:Program FilesCommon FilesMicrosoft SharedWeb server extensions12.

Web parts can be deployed in two different locations: the bin folder or the Global Assembly Cache (GAC). The bin folder is a subfolder of the Web application root directory. Web parts in the bin folder are subject to the CAS policy in effect for that Web application. A different policy can be specified for the Web part assembly. Web Parts in the GAC will always run with full trust. Please refer to Chapter 17, for details on creating and using CAS policies.

Resource Locations

When programming for SharePoint Products and Technologies, you should replicate the structure of resource locations within the Visual Studio environment. Doing so provides three major advantages. First, deployment can be easily accomplished using post-build events to XCOPY the contents of folders in the Visual Studio solution to the corresponding resource locations in the development environment. This provides a very quick development, test, and edit cycle by automating deployment as part of the build process. Second, it aids in production deployment by making the creation, interpretation, and debugging of Windows SharePoint Services 3.0 solutions considerably easier. When a project is ready for production deployment, the post-build events development deployment process has largely validated the solution resource locations. These locations can be easily referenced in Solution Explorer when you create and edit the Manifest.xml and .DDF files for Windows SharePoint Services Solution Package. Finally, replicating the structure of the resource locations in Visual Studio self-documents the solution. The replicated folder structure immediately identifies that the solution is SharePoint Products and Technologies–related and clearly demonstrates what sort of artifacts are being created. This self-documentation makes maintenance considerably easier for individuals unfamiliar with the original project, or when you return to a project after a long absence. It is a best practice to replicate the structure of SharePoint Products and Technologies resource locations in Visual Studio to aid deployment and maintenance of solutions. Figure 12-5 shows an example of the best practice.

Resource locations in Visual Studio

Figure 12-5. Resource locations in Visual Studio

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.41.214