Chapter 25. Using Server-Side and Client-Side Web Parts

Introduction

Previous chapters introduced different types of SharePoint creations, including webs and web templates, Web Parts, lists, and basic customization of Web Part pages. This chapter develops the wonderful ecosystem of Web Parts. There are essentially two distinct reasons for the initial popularity of SharePoint Team Services (STS), the original precursor of Windows SharePoint Services (WSS). The first is the concept of lists and the second is Web Parts. Both features enabled power users to quickly assemble simple web-based applications without the need to engage expensive developer services.

Web Parts offer reuse on a scale that goes beyond traditional components and, as such, carry the promise of good return on investment for companies. Web Parts have grown up since the early days, to the point that they have fully influenced the ASP.NET platform. They are a major reason why the SharePoint platform continues to grow at such an incredible pace. Not only is the third-party Web Part market growing strong due to the enormous popularity of WSS 2.0 but, now that Web Parts are a part of ASP.NET 2.0, availability of third-party products and solutions will undoubtedly explode. A number of Web Parts have already been introduced in Chapter 8. In this chapter, we address Web Parts in a slightly different way. In addition to introducing the remaining Web Parts, we will look at the details of a Web Part and how to manage, create, package, and deploy custom Web Parts.

What exactly is a Web Part? It is a web component (similar to a “Portlet”) that exposes functionality and enables users to interact with the data, look-and-feel, and behavior of the site. Essentially it is a specialized ASP.NET Server Control (a type of component) that can be added to a page, typically to a specialized container called a Web Part zone that is exposed on an ASP.NET page hosted within WSS or Microsoft Office SharePoint Server 2007 (MOSS). These ASP.NET pages are called Web Part Pages. Although most Web Parts have some kind of user interface (UI) that exposes data or functionality to an end user, there could be Web Parts that are totally hidden from visual interaction with the users. Web Parts offer the following benefits:

  • Reusability and improved productivity

  • Increased ROI

  • Standardization and simplification of applications

  • Integration, where Web Parts can exchange information

  • Customization and personalization

  • Page Design

The entire Web Part ecosystem may seem complex to a beginner, but can be broken down into manageable chunks of knowledge that are easier to understand. There are several aspects of the Web Part ecosystem that are useful to know:

  • The Power User and Business User approach, which focuses on the existing Web Parts and means of utilizing them to the fullest

  • The Administrators and Operators approach, which focuses on architecture, maintenance, deployment, and troubleshooting of Web Parts

  • The Web Master and Web Developer approach, which focuses on advanced configuration and development of Web Parts

At the end of this chapter, you will be able to:

  • List and understand Web Parts that ship with WSS and MOSS

  • Place and configure Web Parts on pages

  • Understand the relationship between Web Parts and different elements of MOSS

  • Install Web Parts, including Windows SharePoint Services 2003 Web Parts, and make them available to users

  • Configure connected Web Parts with a browser and SharePoint Designer

  • Develop simple Web Parts with Visual Studio 2005

  • Use Visual Studio 2005 Extensions for WSS

  • Develop complex Web Parts with Visual Studio 2005

Web Parts for Power Users and Business Users

Although it may seem odd to mention a power/business user in a technology book, we have to realize that it is actually the business users that, in most circumstances, sponsor and approve the acquisition of MOSS. The business users also look at how effectively the technology can be applied to solve business problems. An in-depth knowledge of Web Parts can impact the decision between using MOSS or a competitive solution.

Tip

There are other forms of MOSS extensibility beyond the Web Services sitetTemplates and Web Parts discussed in this book. Some of the other extensibility elements include:

  • Controls

  • Custom actions and action groups

  • List instances and templates

  • Site definitions

  • Documents

  • Fields

  • Content types

  • Modules

  • Workflows

Web Parts and MOSS

Instead of drilling down into all of the Web Parts, we’ll describe the relationship between Web Parts and lists, which seems to be a common point of confusion. Most people, having played with WSS or MOSS for some time, have a tendency to ask why the number of Web Parts keeps changing.

When opening the Add Web Parts dialog, as in Figure 25-1, on an ordinary Web Part page, we will typically see the Lists and Libraries grouping. This grouping represents every single list and library that exists within the site and is currently visible to users (besides permissions, there is also a Hidden property for each list).

Tip

Lists are the major data storage element within MOSS. Every item that is created from within the Create page—Libraries, Communications, Tracking, and Custom Lists—inherits, in object-oriented speak, its functionality and behavior from the basic list. Also, the majority of lists and libraries implement some custom functionality to achieve its business purpose. The beauty of inheritance allows you to standardize a majority of the metadata programming against every single list style and template.

The list of Web Parts within the lists and libraries expands and contracts when new lists and libraries are added to or deleted from the site. Simply speaking, whenever a new list is added, a new ListViewWebPart Web Part is added with the same name as the added list, with a predetermined view, depending on the type of list created. In other words, each list view you create in SharePoint is actually an instance of a fundamental Web Part that is built into the MOSS framework—namely, the ListViewWebPart.

Tip

When someone wonders why there is no Issues Web Part on a particular site, it’s because there is no corresponding Issues list. This pretty much explains why some people can see more Web Parts than others within their sites—it’s just that there are more lists on some sites.

Add Web Parts dialog

Figure 25-1. Add Web Parts dialog

Built-in Web Parts

Building on the core Web Parts that were described in Chapter 8, we will add all of the remaining Web Parts that belong both in the WSS code base and in MOSS. For more details on the use of some of these Web Parts, consult their associated chapters. To maintain consistency, the Web Parts are listed in the same sections as they are organized in the catalog.

Additionally, the majority of the Web Parts listed in the following tables are available only with MOSS, and not with WSS. Web Parts for lists and libraries, as well as Web Parts in the Default and Miscellaneous sections, are provided with WSS. There are also other Microsoft Web Parts that integrate the SharePoint platform with other products (such as Project Server or Reporting Services Integration), and they either ship directly with the product or are available for download from the Microsoft Download site. Table 25-1 lists the Business Data Web Parts.

Table 25-1. Business Data Web Parts

Web Part

Description

Business Data Actions

Shows actions associated with BDC, tied to a Type and an Item

Business Data Item

Shows a single item from BDC

Business Data Item Builder

Allows for filtering and building parameters to be reused by other BDC Web Parts on profile Pages

Business Data List

Shows a list of items from BDC

Business Data Related List

Shows items that are configured as related entities within BDC and configured within the Web Part

Excel Web Access

Shows an Excel workbook based on the Excel Server and Excel Web Access

IView Web Part

Allows use of SAP iViews and integration with SAP portal servers

WSRP Consumer Web Part

Allows for reuse of external WSRP portlet providers that implement WSRP 1.1 specification, typically equivalent to backend Web Part technology in the Java portal world

Business Data Web Parts are utilized in conjunction with the Business Data Catalog, and require additional configuration of entities and actions within the BDC. Business Data Catalog is available with the Enterprise version of MOSS.

Table 25-2 lists the Content Rollup Web Part.

Table 25-2. Content Rollup Web Part

Web Part

Description

Site Aggregator

Allows for display of content from multiple sites via a simple tab-like interface, displaying Documents and Tasks assigned/owned by the user on the sites. Sites have to be added manually.

Site Aggregator, as seen in Figure 25-2, is typically used on a My Site to show a particular user bits and pieces of other sites that are specifically relevant to the user. Other forms of aggregators can be achieved via RSS aggregators, custom queries, and a number of third-party Web Parts.

Site Aggregator

Figure 25-2. Site Aggregator

Table 25-3 lists the Dashboard Web Parts.

Table 25-3. Dashboard Web Parts

Web Part

Description

Key Performance Indicators (KPIs)

Displays contents of a KPI-enabled list. You must create a KPI list and use an existing list as one of the KPIs in order to utilize an existing list. Additionally, this allows direct interaction with the KPI list, and a tie-in of KPIs from Excel Services, Microsoft SQL Server Analysis services, and manually entered values.

KPI Details

Displays details of a single KPI defined in a KPI list, along with a graphical version of the indicator (that can be different than the default).

Dashboard Web Parts, as seen in Figure 25-3, should be used instead of the default List View Web Parts whenever KPI lists are involved. These Web Parts provide rich interaction with KPI data sources and data as well as a very slick display. They are always a great hit during a demo, and are relatively easy to configure. KPI Web Parts and KPI lists are available only with a MOSS Enterprise license.

Dashboard Web Parts

Figure 25-3. Dashboard Web Parts

Default Web Parts are used on a typical collaboration portal and help organize some simple content that is not available via other parts (Table 25-4). These Web Parts, along with some of the Miscellaneous Web Parts, allow for creation of complex portal content and navigation without the need for any other tools.

Table 25-4. Default Web Parts

Web Part

Description

I need to…

Displays a drop-down list of tasks, typically shown on the Collaboration site

RSS Viewer

Displays data from an RSS feed

This Week in Pictures

Displays an image and ties in to a slide show based on an Image Library

Content Query Web Part

Shows a set of results based on a configured query, almost like a Data View that is capable of spanning multiple lists and libraries across the site collection

Summary Link Web Part

Allows the display and organization of a set of links

Table of Contents Web Part

Displays the navigation hierarchy of the site

Filter Web Parts are a staple of interactive Web Part pages, allowing the designer to relate one piece of data to another (Table 25-5). With a growing number of Web Parts supporting Web Part connections, the filters provide a very simple way of producing a variety of relationships on the pages. There are three types of Filter Connections: Automatic, User, and List-based, which support a variety of Data Types, from simple Text all the way to multiple values in a list.

Table 25-5. Filter Web Parts

Web Part

Description

Business Data Catalog Filter

Allows use of BDC as a basis for filtering data in other Web Parts

Choice Filter

Allows the designer to enter a selection of entries for use as a filter (entries cannot be modified as long as the filter is connected to another Web Part)

Current User Filter

Allows use one of the user’s profile fields to be used as a filter, or user NT ID

Date Filter

Allows use of the date as a filter, which can be current, specific, or an offset day (e.g., 7 days after today)

Filter Actions

Button that allows for users to apply a set of filters and save the connection settings

Page Field Filter

Allows one of the page metadata fields to be used as a filter (this is useful for pages that exist in libraries)

Query String Filter

Allows use of one of the parts of query string as a filter

SharePoint List Filter

Allows data stored in any list to be used as a filter

SQL Server 2005 Analysis Services Filter

Allows the selection of a data connection from a library

Text Filter

Allows the use of user-entered data to create a filter

Whereas the List View and Filter Web Parts provide designers the ability to display and glue content that is available on the site, the Miscellaneous Web Parts (Table 25-6) provide the ability to fill in the gaps with some interstitial content as well as external XML or web-based content.

Table 25-6. Miscellaneous Web Parts

Web Part

Description

Contact Details

Information about the contact person for a page or site

Content Editor Web Part

Allows designers to edit simple HTML content within the page

Form Web Part

Allows HTML form controls to be used on a page and to connect to other Web Parts

Image Web Part

Displays a single image on the page

Page Viewer Web Part

An IFrame control that can display external content, linked by file or HTTP protocol

Relevant Documents

Displays documents that are relevant to the current user based on some query that is defined in the Tool pane

Site Users

Displays a list of user members and their presence indicators

User Tasks

List of tasks for the user for all tasks within the site collection

User Display

Displays the username for currently logged on user

XML Web Part

Allows use of XML (including remote XML) and XSLT to display content

Tip

There are also some legacy Office Web Parts that were available with SharePoint Server 2003: Office Datasheet, Office PivotChart, PivotTable, PivotView, and Office Spreadsheet. Additionally, there is a free advanced Content Editor Web Part available from Telerik called r.a.d. editor; see http://www.telerik.com/products/sharepoint/overview.aspx.

Outlook Web Parts allow the use of Outlook Web Access (OWA) elements directly within the SharePoint portal, usually within My Site pages (Table 25-7). When the Outlook Web Access URL is populated in the profile, the user sees the My OWA button.

Table 25-7. Outlook Web Parts

Web Part

Description

My Calendar

Displays the user’s default calendar

My Contacts

Displays the user’s default contacts

My Inbox

Displays the contents of a user’s inbox folder

My Mail Folder

Displays an arbitrary Outlook folder for an end user

My Tasks

Displays the user’s tasks

Search Web Parts (Table 25-8) make up their own ecosystem, tailored specifically to serving search results, as seen in Figure 25-4. Overall, they are very flexible and provide a great degree of customization. There are more Web Parts available when the Knowledge NETwork components of SharePoint are installed. For more information, follow the KN blog at http://blogs.msdn.com/kn.

Table 25-8. Search Web Parts

Web Part

Description

Advanced Search Box

Used for searches on the Advanced Search page (an example of customization of this Web Part is provided later in the “Adding Custom Column to Search” section)

People Search Box

Used for people-specific searches

People Search Core Results

Displays core results for people-related searches

Search Action Links

Search action links, including RSS, Alert, and sorting links

Search Best Bets

Displays related Keyword, Best Bet, and High Relevancy items

Search Box

Standard Search Box that shows up on every page

Search Core Results

Displays results of most common searches (the most frequently customized Search Web Part)

Search High Confidence Results

Shows Keywords, Best Bets, and other high confidence results

Search Paging

Displays links for navigation between pages

Search Statistics

Displays basic search statistics, number of results, time

Search Summary

Web Part that shows auto-correction suggestions in a “Did you mean” format

Search Web Parts on a Search Results page

Figure 25-4. Search Web Parts on a Search Results page

Site Directory Web Parts provide an enhanced way of navigating through sites without the use of tabs or the lefthand-side tree structure (Table 25-9).

Table 25-9. Site Directory Web Parts

Web Part

Description

Categories

Displays categories stored in Site Directory in several flexible styles

Sites in Category

Displays sites in a specific category

Top Sites

Displays top level sites based on a fixed query but with a flexible location

Web Part Architecture

Web Part architecture is a nebulous domain of knowledge, depending on both administrative and developer skills. Knowledge of the Web Part architecture is useful to an administrator, who has to manage some custom Web Parts, and useful to the developer, who has to design custom Web Parts and package them for later deployment.

A Web Part can be as simple as a single configuration file, or a .webpart or .dwp file, or an installable package, which may include a number of assets. Understanding different elements of a Web Part is the key to best development practices and effective troubleshooting.

Although ASP.NET Web Parts work slightly differently, all SharePoint Web Parts must derive from one of two base classes, and they cannot utilize User Controls or Custom Controls directly as Web Parts:

  • System.Web.UI.WebControls.WebParts.WebPart

  • Microsoft.SharePoint.WebPartPages.WebPart

Tip

Although Microsoft.SharePoint.WebPartPages.WebPart-based Web Parts may be considered legacy, they do offer several features that are not possible to achieve with ASP.NET Web Parts, including:

  • Cross Page Connections

  • Connections to Web Parts placed on pages outside of Web Part zones

  • Client Side Connections

  • Data Caching infrastructure

Architecturally, Web Parts are most similar to .NET Custom Controls, but offer several important benefits and work with the underlying SharePoint Web Part infrastructure.

In order to use SharePoint Web Parts, you must have a web page that contains a WebPartManager object and one or more WebPartZone objects. Fortunately, in SharePoint, these objects are already present on every Web Part page. In other words, as a SharePoint developer, all you really need to worry about is creating Web Parts. The rest of the framework, although relevant for ASP.NET developers, is automatically provided by SharePoint.

Tip

There is a user community around a “Son of Smart Part” Web Part (created by Jan Tielens) that allows developers to utilize simple User Controls within WSS and MOSS. To find out more about this Web Part, go to http://www.smartpart.info/default.aspx.

User Controls are one of the easiest elements to build in ASP.NET that combine an intuitive UI and business logic.

Since WebPartManager is already built into the pages, the designer or developer does not have to worry about any plumbing associated with the implementation of the Web Part management pages, personalization, or storage.

Physical Resources

There can be a number of files associated with Web Parts, including a Web Part configuration file, an assembly, a registration for the web.config file, and occasionally additional resource files or policy settings.

Web Part XML configuration files are either .dwp files, representing the SharePoint 2003–style Web Parts, or .webpart files, representing the ASP.NET 2.0–style Web Parts. These files would typically be used as part of a site definition, as part of a Web Part Catalog (this is a wpcatalog folder underneath your web application root directory), uploaded to a Web Part library, or simply imported onto a page.

Next, the Web Part assemblies are the code compiled into a .dll file. Web Part assemblies may have some additional files associated with them, depending on the type of development performed. The .dll files will typically be installed into the web site’s /bin directory (e.g., C:InetpubwwwrootwssVirtualDirectories81in for a web application installed on port 81), or to the global assembly cache (GAC), which is located in the C:WINDOWSassembly directory, as seen in Figure 25-5. Assemblies that are deployed to the GAC are available to all applications running on the server, and require execution with full trust privileges. Deployment of assemblies into a bin directory typically allows for easier manual deployments than into GAC, and requires only partial trust security. Commonly, assemblies deployed into GAC may be locked by the application server, and may require an artificial stop of the application in order for these assemblies to be released.

Tip

The best overall .NET utility, Reflector for .NET, also has its use with Web Part deployments and reverse engineering of existing code. After an assembly is loaded into Reflector, you should be able to see the exact string required for the Assembly attribute below. Otherwise, you may have to jump through hoops to find the appropriate information. Reflector can be downloaded from http://www.aisto.com/roeder/dotnet/.

Each Web Part assembly also needs to be properly registered within the web.config file, and, if necessary, a Code Access Security (CAS) policy must be created. The web.config file holds Web Part registrations in the SafeControls section, with each Web Part or assembly registered as a SafeControl entry. Each element has the following attributes:

  • Assembly, which holds the exact assembly registration string as it would be deployed in the GAC, consisting of assembly name, version, culture, and a public Key Token

  • Namespace, which represents the exact namespace of our Web Part

    Global assembly cache

    Figure 25-5. Global assembly cache

  • TypeName, which represents the type within the Web Part (typically set to '*')

  • Safe (optional)

  • AllowRemoteDesigner (optional)

Without the SafeControl entry, an assembly used by the Web Part simply cannot be used within MOSS. Here is a sample entry that is actually used later in this chapter:

	<SafeControl Assembly="HelloMOSS, Version=1.0.0.0, Culture=neutral,
	PublicKeyToken=9f4da00116c38ec5" Namespace="HelloMOSS" TypeName="HelloMOSS"
	Safe="True" />

The security policy is defined in the web.config file as well. There are two entries, one where it is declared SecurityPolicy and another where it is actually used, called trust.

Tip

Custom CAS Policies are beyond the scope of this book. By default, a Web Part can only access resources within its own boundaries, and a few basic assemblies, but not external assemblies that, for instance, would allow the Web Part to access databases or files.

For the sake of being able to run and test any code, you can set the trust element to “Full”:

	<trust level="Full" originUrl="" />

This setting allows every Web Part to use any assembly, and thus a rogue piece of code could potentially do some damage with this setting.

Last, there are external resource files associated with the Web Parts (resources can also be embedded inside the assemblies). These are resources such as JavaScript files, images, and some other common elements that can be utilized at the client side. There are two potential locations where the extra resource files can be placed (Table 25-10); one of them is highlighted in Figure 25-6.

Table 25-10. Placement of resource files

Deployment style

Location and description

GAC

Resources deployed to the virtual _wpresources directory in the format of wpresources/assemblyName_publicKey/

bin

Resources deployed to the physical wpresources folder underneath the web server root folder

Web Part resources

Figure 25-6. Web Part resources

Additionally, a Web Part may rely on some other piece of MOSS infrastructure and contain references to some modules, lists, or controls. These other elements would be placed in some other appropriate directory dedicated to site definitions, modules, or user controls. Web Parts that carry dependencies on other parts of MOSS are typically bundled in .wsp files that define a full solution. In other words, if you are packaging a Web Part that acts as the center point of a particular page layout, you will package the full page definition with the Web Part. When the package is deployed and activated, users will see the custom Web Part and any of the additionally packaged assets.

Web Parts for Administrators

There are only a couple of activities related to the lifecycle of a Web Part performed by the operator or administrator of a site. Depending on how a Web Part is created and packaged and what technologies it utilizes, there are different tasks associated with each.

As explained in the previous section, Web Parts are comprised of different files and resources. These can sometimes come in “zipped” by the developer with some light instructions, or they can come in a specialized deployment package.

Installing Web Parts

There are a number of techniques and tools that can be used to install Web Parts in WSS and MOSS, listed in Table 25-11, ranging from a number of manual steps to full-blown MSI installers. Most of these approaches take pretty good care of the work behind the scenes, and typically deploy files into correct locations and update the web.config for the correct web application.

Table 25-11. Web Part installation options

Web Part package

Description

MS/ installer

An MSI installation file will probably come with some additional installation instructions. On onehand, it may be the easiest way to deploy Web Parts; on the other hand, you will have the leastamount of control over what you do.

CAB file

This is an older style of deployment that was available with WSS 2.0 and SPS 2003 platform. CAB files have to be installed on frontend servers by running the stsadm –o addwpppack –filename filename.cab command from the command prompt:

C:Program FilesCommon FilesMicrosoft Sharedweb server extensions12instsadm

There are a number of additional switches for this command:

  • lcid

  • url

  • globalinstall

  • force

  • nodeploy

WSP file

This is the new solution package file that can be used to deploy Web Parts and other solution elements. Behind the scenes, it is also a CAB file format, but contains different files. It is automatically created by Visual Studio, based on the Visual Studio extensions for WSS. The WSP packages are also installed with the stsadm utility mentioned earlier. Most WSP files typically also ship with a batch file that will automate all of the installation steps. If there is no batch file, you will use stsadm to add the solution, deploy the solution, and activate the feature contained in the solution:

	stsadm -o addsolution -filename filename.wsp
	stsadm -o deploysolution -name packagename" -local -
	allowGacDeployment -url urlname
	stsadm -o activatefeature -id featureid -url urlname

Just files, aka xcopydeployment

In some cases, you may simply be handed a bunch of assemblies and, potentially, some .webpart or .dwp files, which you will have to copy to the appropriate location.

The Web Part assembly will either go to the /bin directory or the GAC (c:Windowsassembly), and the .webpart will go inside the /wpcatalog directory. You will also be responsible for modification of the web.config file and for adding the Web Part information into the <SafeControls/> section. This is fully explained later in the “Developing Web Parts from Scratch” section.

Troubleshooting Web Parts for Administrators

There are a few things that an administrator has to be prepared for to support MOSS. Unfortunately, babysitting Web Parts may be one of the necessary duties. There can be many potential problems associated with the execution of Web Parts:

  • Improperly registered Web Parts will show an error: “The type could not be found or it is not registered as safe.” In order to fix this, you must fix the web.config file for the web application in question. Also, validate whether the SafeEntry is correct for this Web Part.

  • Web Parts might have improper security policies.

  • Slow-running Web Parts. If a majority of the pages run significantly faster than others, those pages may have problems with one or more of their Web Parts. There can be a number of reasons for the speed of execution, starting with business logic, volume of data to process, speed of data connections, and external dependencies on web services or external sites.

  • Slow Web Parts can be removed from the site either with the help of SharePoint Designer or directly from the page. You can enter append “?contents=1” to the end of the URL to open the Web Part Page Maintenance page, as seen in Figure 25-7.

    Web Part Page Maintenance page

    Figure 25-7. Web Part Page Maintenance page

The top toolbar shows whether you are using a personal or shared view, and the grid below displays all of the Web Parts, along with their type and status on the page. By selecting the checkbox and clicking Reset or Delete, you can easily control a misbehaving Web Part:

  • If the page will not open at all, or your Web Part or control may be outside of a Web Part zone, your next option is to modify the page, either using SharePoint Designer or by resetting the page or site to its original site definition, as seen in Figure 25-8. Before resetting to a site definition, you should always make a backup of the site. The Reset Page to Site Definition Version maintenance page is available directly from the Site Settings page in the Look and Feel column; you will have to enter the full address of the page. After you reset the page, all of the customizations outside of Web Part zones on the page will be removed.

    Tip

    Web Parts can exist outside of Web Parts zones, just because they are standard Server Controls. They can be placed on any part of the page as part of a Site Definition, or when editing a page outside of the web browser, as with Notepad or SharePoint Designer.

    Reset Page to Site Definition Version

    Figure 25-8. Reset Page to Site Definition Version

  • Certain Web Parts, such as the List View or the Data View Web Part, may be dependent on existing lists. This dependency is usually through a link to the target part’s GUIDs. When a list is moved, deleted and recreated, or moved with the use of the object model, the GUID may change without properly being reflected in the connected Web Part. The best way to solve the problem is to recreate the connections, or to use SharePoint Designer to locate GUID elements and fix them to the appropriate list or view GUID. Typically, the GUID element would be an element such as <ListName> that would be visible in the code pane of the window. You could find out the proper GUID by placing a similar Web Part tied to the same list.

  • Finally, you should really profile and stress test any custom developed Web Parts, and talk to the vendor who developed them (if it is a third-party Web Part) in case you see any problems. There are going to be many factors that impact the performance of a Web Part, starting with caching and personalization options, and ending with slow-running code, exception handling, and memory usage.

    Warning

    The Online Gallery, when enabled, pulls Web Parts out of MSNBC. This gallery acts just like one of the poorly behaving Web Parts, and adds 10–20 seconds to the call. If necessary, just import the Web Parts locally, and serve it by creating your custom gallery.

Web Parts for Web Masters and Web Developers

Using Web Parts on Pages

As mentioned before, Web Parts are typically instantiated within Web Part zones on a page, such as in Figure 25-4 earlier in the chapter, where six pages were seen within the screenshot. There are a number of ways in which Web Parts can be placed on the page, and there are a number of modes that Web Parts exhibit while interacting with the page:

  • Normal Mode

  • Edit Mode

  • Design Mode

  • Catalog Mode

Naturally, Web Parts are typically managed directly on the page, imported from the catalog, or uploaded. Web Parts can interact with a page in a number of modes and display different results. Once a Web Part exists on a page and a page is in Edit Mode, you can simply move the Web Part around with drag-and-drop or use properties to place Web Part in a different zone. MOSS’s standard master page handles zones that cover the Editor and Catalog zone automatically.

Zones can control whether users are allowed to add, delete, move, or resize the Web Parts, whether users can personalize Web Parts, and whether users can modify settings for all users. Once these properties are set, they can be changed only by the administrator or a designer using a tool such as SharePoint Designer.

Tip

There are many settings that can impact the ability to use and configure a Web Part on a page. Some portals may disallow editing of pages via policy, but this and other settings can also be set on a page or even a Web Part zone level. Common properties that can be set are the ability to personalize a Web Part, Web Part orientation, or some common Chrome properties, such as a Web Part frame or a title.

Web Part Configuration

Web Parts expose a number of properties that allow their simple configuration (Table 25-12). Although each Web Part can expose a number of custom properties directly in the configuration pane, as well as custom configuration sections, the built-in infrastructure provides three configuration panels for Appearance, Layout, and Advanced properties.

Table 25-12. Web Part configuration options

Web Part property page

Description

Appearance

Appearance controls Title, Height and Width, Chrome State, and Chrome Type. These settings basically allow you to override the way that your Web Part box area is displayed.

Layout

Layout controls where the Web Part is displayed on the page, and contains properties such as Visible On Page, Direction, Zone, and Zone Index.

Advanced

Advanced properties also control appearance and some additional behaviors. Its properties are: Allow Minimize, Allow Close, Allow Hide, Allow Zone Change, Allow Connections, Allow Editing in Personal View, Export Mode, Title URL, Description, Help URL, Help Mode, Catalog Icon Image URL, Import Error Message, and Target Audiences.

Default

Typically, the core of the configuration will be shown on the default property page. Most of the core MOSS Web Parts display their properties here.

Custom

There can be other property pages created for a Web Part, and the default order can be modified. If the Web Part requires complex configuration, it will expose this functionality either via some custom page or directly on the surface of the Web Part, when the Web Part is in the Edit or Design Mode.

Configuring Connected Web Parts

A more specialized element of configuration is the ability for Web Parts to connect with one another. Unlike other properties set within the Web Part property pages, connectivity is configured via an action tied to the title menu. Using Web Part connectivity is a great way to create dynamic web-based applications without necessarily using any development tools. Sample Web Part Connectivity is shown in Figure 25-9.

After a page or a Web Part is taken into an Edit Mode, you can click the Edit button, and expand the Connections submenu. Depending on the type of connectivity exposed by the Web Part, and on the availability of other Web Parts on the page, typically you will be able to see some choices from which to select. For instance, the Data View Web Part, as seen in the example, allows the use of Provide Row data, Provide Data, and Get Sort/Filter. After selecting one of the active items, you will see a choice of Web Parts that are capable of accepting a connection. If the choices are grayed out or inactive, there are no Web Parts on the page capable of accepting a connection. Different Web Parts will provide different connections and accept different data. Not all data types can be passed in a connection.

Web Part Connection

Figure 25-9. Web Part Connection

Additionally, Web Part connections can be configured in SharePoint Designer. Although use of SharePoint Designer “unghosts” the Web Part pages, it also allows greater flexibility in terms of Web Part connectivity. Whereas autogenerated connectivity between Web Parts created with the browser UI typically creates ugly radio buttons, SharePoint Designer allow you to create connections based on images, links, or other HTML elements.

Web Part connectivity also depends on the interface implemented by the Web Part, as well as availability of Web Parts that implement a complimentary interface. For the older style Web Parts, not only do you need a provider and a receiver, but you also need compatible interfaces. For the new WSS 3.0 Web Parts, communication is performed via a shared interface, and registration of this interface in two Web Parts is via ASP.NET attributes. Specific interfaces used to cover Web Part connectivity are covered later in the “Advance Web Part Development” section.

Development Environment for MOSS

Thus far, we have mainly dealt with existing Web Parts; for the remainder of this chapter, we will deal with creation of new Web Parts. Developing Web Parts requires a development environment.

Perhaps one of the weakest experiences with MOSS is that of the casual developer. Many user group meetings and conferences are filled with water cooler talk focused on configuration of the development environment (Table 25-13). Simply speaking, for the very best environment you will need to develop directly on the server. If you install all elements in a standalone environment (MOSS, SQL 2005, or Visual Studio 2005), you will get simplified deployment and debugging that you would not be able to achieve otherwise. Once you have built and tested your Web Part, you can package it and deploy it on your multiserver farm as part of a scheduled production release.

Table 25-13. Different development environments

Environment

Benefits and problems

Simple Windows XP or Vista

Although development is possible, you will not be able to debug a majority of the code, and you will have to go through a number of manual steps to configure and deploy code. MOSS 2007 and SQL 2007 are hosted on another machine, while you use Visual Studio 2005 to code and compile.

Virtual Machine

Probably the most common environment. Recommended configurations for host OS require at least 2 GB of RAM and a fast disk (possibly external). This is also very easy to fix if something breaks. You can install all elements on the Virtual Machine, or break it apart and reuse some existing infrastructure. Since SQL Server tends to eat up a lot of resources, it should be externalized if possible.

Windows 2003 Server

Similar to the Virtual Machine, but less resource-intensive. You will still need high-end hardware to run the server and desktop applications at the same time; at worst, you should be running MOSS 2007 and Visual Studio 2005 on the same machine.

There are also some external components in a typical environment, such as email and the domain server. They are definitely not required, but still nice to have from an infrastructure perspective. Visual Studio 2005 is certainly not a requirement for Web Part or SharePoint development, but it does make a few things easier. You would need some kind of an editor (Notepad) and .NET SDK to compile the code.

Tip

You will also have to create a reference to the SharePoint assemblies. These are stored on frontend servers at: [windows volume] Program FilesCommon FilesMicrosoft Sharedweb server extensions12ISAPI (or 60ISAPI for SPS 2003 assemblies). You will have to make a share on a server in order to access it from your development workstation (if working remotely), or just map it locally.

Developing Web Parts with Visual Studio 2005

Web Parts in MOSS 2007 have 2 distinct flavors, depending on whether the older or newer API is used. The older API is derived from legacy SharePoint 2003 technology (aka the Microsoft.SharePoint namespace), and since the Web Part technology has now been included directly in Windows, the new API is based on Microsoft ASP.NET 2.0. The new Web Parts are now a part of the System.Web.UI.WebControls.WebParts namespace.

Tip

Unless you have a specific reason for using SharePoint 2003–style Web Parts, stick to the new API, as it will make them compatible with other ASP.NET-based apps. The old API had an additional interpage and client-side connectivity capability, whereas the new API performs connections on the server side.

A typical approach to Web Part development and deployment is similar, regardless of whether the developer starts with a simple class project or with Visual Studio 2005 Extensions for WSS. The main difference would potentially lie in the deployment approach, where the developer can choose the xcopy deployment instead of the msp package automatically built by the Visual Studio. Actually, a majority of the Web Part’s inner workings are identical to that of an ASP.NET Server Control. For a simple Web Part, the process looks as follows:

  1. Create a project (class or Web Part).

  2. Create a class file that will inherit from base WebPart.

  3. Override the Render method if you want your Web Part to display something.

  4. Override other methods as needed to use other controls, handle events, create properties, and edit screens.

  5. Create an snk key file and enter it in the AssemblyInfo.cs file to sign the assembly.

  6. Build your Web Part.

  7. Deploy your Web Part using the xcopy approach, or create a secondary project that creates an MSP deployment project (Visual Studio 2005 Extensions for WSS handle it for you).

  8. Place the Web Part on the page.

  9. The next sections cover this process in more detail.

Visual Studio 2005 Extensions for WSS

Visual Studio 2005 Extensions for WSS provide a collection of tools and project templates that create simple starting point for development of Web Part–style projects. Literally, the Web Part template provides sufficient code for the simplest Web Part and for its deployment with a simple F5 click. This code, as well as some additional plumbing steps, would work as a standard “Hello World” sample.

	using System.Runtime.InteropServices;
	using System.Web.UI;
	using System.Web.UI.WebControls.WebParts;

	namespace SimpleWebPart
	{
	    [Guid("25ed441d-9c4a-4892-8a71-99edc1f2a1d2")]
	    public class SimpleWebPart : WebPart
	    {
	        protected override void Render(HtmlTextWriter writer)
	        {
	            writer.Write("Hello to Bob from Piotr");
	        }
	    }
	}

Tip

Visual Studio 2005 Extensions package is available to download from:

http://www.microsoft.com/downloads/detailsaspx?familyid=19F21E5EB715-4F0C-B9598C6DCBDC1057&displaylang=en

These Extensions provide a number of useful project templates.

There is also an older version of the toolkit for SharePoint Server 2003,which provides a SharePoint Web Part template. It may make sense to keep Visual Studio 2003 handy to support older Web Parts, or at least to copy the project template.

The following steps create a simple “Hello MOSS” Web Part in Visual Studio 2005, with Visual Studio 2005 Extensions for WSS on a development machine with MOSS 2007 installed on the default port 80:

  1. With Visual Studio 2005 opened, click File → New → Project (Figure 25-10).

  2. From the New Project dialog box, select Visual C# and Web Part, fill in the Name and Location, and click OK (Figure 25-11).

  3. Navigate the HelloMOSS.cs code file, and edit the Render method (Figure 25-12) so that the body is:

    	protected override void Render(HtmlTextWriter writer)
    	{
    	     writer.Write("Hello MOSS");
    	}
    
  4. Study the contents of the Solutions Explorer window. When you expand the Properties section you will notice AssemblyInfo.cs and Temporary.snk.Temporary.snk is a Strong-Name-Key file, which allows .NET to sign an assembly so that it can be checked for tampering, and the AssemblyInfo.cs file allows the developer to embed some additional metadata about the assembly and associate the .snk file to the project. The References section does not contain anything extraordinary other than the addition of the Microsoft.SharePoint assembly as a reference. You will need this reference if you use the SharePoint WSS API, which would refer to something within the site.

    Open a new project

    Figure 25-10. Open a new project

    New Web Part project

    Figure 25-11. New Web Part project

    Render method

    Figure 25-12. Render method

  5. Expand the Output window on the bottom of Visual Studio screen, and hit F5 to watch the progress of building the project and its deployment. Depending on the speed of your development server and whether your machine has been warmed up, this process can take from 30 seconds to 5 minutes. We will go through the details of each step taken later on, and identify exactly what changes have taken place behind the scenes.

    Looking at the detailed steps in the output window, you can observe the following, which save a lot of time:

    1. Compilation is completed.

    2. Deployment project is created.

    3. Solution is created.

    4. Batch file for management of the solution is created.

    5. Solution is added.

    6. Solution is deployed.

    7. Features are activated.

    8. IIS is restarted.

    Warning

    During subsequent build-and-deploy sessions with the project, your Web Part will additionally be Deactivated, Uninstalled, Retracted, and Deleted, but it will still remain on the page. This is because a .webpart or a .dwp file is totally independent from the Web Part that exists in the form of an assembly.

  6. Next, you need to add your Web Part to the page. Open your portal or site, go to the page where you want to add the Web Part, open it in Edit Mode, and click “Add a Web Part” (see Figure 25-13).

    Warning

    By default, the Web Part built with this method is created as a solution containing features. This solution is tied at a Site Collection scope. As a result, going to a different site collection or a different Web Application will not show the Web Part as available in the catalog, unless it is added, deployed, and activated.

    Edit Mode and Add a Web Part

    Figure 25-13. Edit Mode and Add a Web Part

  7. The Web Part you create with the F5 button will automatically register for the default portal, and will be inside the Miscellaneous Web Parts catalog section. It will also have the same name as the project you have created. In this case it is the HelloMOSS Web Part (Figure 25-14). Select the checkbox and click Add. Exit the Edit Mode if necessary.

    HelloMOSS in the Web Part catalog

    Figure 25-14. HelloMOSS in the Web Part catalog

  8. Finally, the fruit of your labors, the HelloMOSS Web Part, appears near the top of the page (Figure 25-15).

    HelloMOSS Web Part on a page

    Figure 25-15. HelloMOSS Web Part on a page

Behind the scenes

The magic of hitting F5 in Visual Studio takes care of a number of other steps that you would otherwise have to handle manually. Later on, we’ll develop a simple Web Part without using any tools, but it is equally important to know what the tools have done.

Besides the necessary template files, the Web Part project has some other settings (some of them are editable from the Project Properties page, in the SharePoint Solution section). Basically, it allows automated deployment of Web Parts into a local server.

First, you should look at the directories where the project was created and built. In our example, this was the C:ProjectsCh25HelloMOSS directory, which contains the Visual Studio solution file. The DEBUG build directory and the code are under-neath in the C:ProjectsCh25HelloMOSSHelloMOSSinDebug directory, as seen in Figure 25-16. There are several files that are of significant interest to us:

  • HelloMOSS.wsp

  • Setup.bat

  • Solution directory

    Project Debug directory

    Figure 25-16. Project Debug directory

These files are created by the Web Part project template. HelloMOSS.wsp is the deployment package, and the setup.bat is the command prompt setup utility that interacts with MOSS via the stsadm utility and takes care of Adding, Deploying, and Activating the solution (as well as subsequent uninstallation steps). You can also see that there is a solution directory, which actually represents the internal contents of the HelloMOSS.wsp file. There are a couple of XML files, our Web Part assembly, and the .webpart file. If you look at the manifest.xml and feature.xml files, you will notice that they represent a unique solution file, and similarly a unique feature, where the feature ID is tied to the GUID attribute of the HelloMOSS class, as declared in the project (also visible in Figure 25-16).

The next element that may be of interest is the setup.bat file, which manages the registration of the assembly within the server. Using the command prompt, as seen in Figure 25-17, we open the location of the setup.bat file and execute setup -? to look at the available options. Using this tool, you can control solution installation and uninstallation as well as the activation and deployment of the solution to a particular site collection of your choice. This provides a decent level of flexibility, as it may be tedious to open so many sites to activate a feature.

Command prompt options of setup.bat

Figure 25-17. Command prompt options of setup.bat

Since the setup.bat tool was used, next we can look at how and where the files included in the solution were deployed. Based on previous experience, we know these can be deployed to the GAC or to the bin directory, and additionally, we know that these are deployed as full-blown features.

First, we can look at the Site Collection’s set of features. I used the setup.bat tool to activate the feature in another site collection (e.g., http://localhost/sites/collab). Now, to open the site:

  1. Click the Site Actions drop-down list.

  2. Click Site Settings (and optionally All Site Settings, depending on the template).

  3. In the Site Collection Administration section, click Site Collection Features. (Note that there is also a Site Features button, which is tied into a web and not into a site collection.)

  4. The Site Collection Features page (as seen in Figure 25-18) shows a HelloMOSS feature that is already activated.

  5. Going back to the Site Settings page, click the Web Parts link in the Galleries section.

    Site Collection Features

    Figure 25-18. Site Collection Features

  6. The Web Part Gallery page shows an entry for the HelloMOSS.webpart; you can click the name of the Web Part to see its preview. You can also click the Edit icon to modify the Web Part Properties, as seen in Figure 25-19.

Next, we can verify that the Web Part has been deployed to the GAC (which implies it was deployed globally) and check its registration in the web.config file. To navigate to the GAC, simply open Windows Explorer and open c:WINDOWSassembly, where c:WINDOWS represents the place where your OS has been installed by default, as seen in Figure 25-20.

Finally, we validate the SafeControls section inside the web.config file (Figure 25-21), which, by default, exists in the c:inetpubwwwroot directory. Our Web Part’s registration is shown in the following line:

	<SafeControl Assembly="HelloMOSS, Version=1.0.0.0, Culture=neutral,
	PublicKeyToken=9f4da00116c38ec5" Namespace="HelloMOSS" TypeName="HelloMOSS"
	Safe="True" />

Building Web Parts from Scratch

Obviously, if you are not working with the Visual Studio 2005 Extensions, you will have to complete all of the behind-the-scenes work yourself. Typically, there are a few more steps before the code shown earlier becomes a real Hello World–style Web Part on a page. To develop a simple Web Part from scratch, you will most likely follow these steps:

Web Part Gallery displaying properties of a Web Part

Figure 25-19. Web Part Gallery displaying properties of a Web Part

HelloMOSS inside GAC

Figure 25-20. HelloMOSS inside GAC

  1. Select a class project template to create your Web Part.

  2. Add references to necessary assemblies in your project, and declare the namespaces in the Using section of your Web Part. Instead of the typical System.Data, you will typically add Microsoft.SharePoint and System.Web. Similarly, you can add references to other assemblies, and then declare the namespaces in the Using section.

    The SafeControls section in web.config

    Figure 25-21. The SafeControls section in web.config

    Since Web Parts can be derived from Microsoft.SharePoint or from System.Web, you should probably alias one of these namespaces to make it clear:

    	using System.Runtime.InteropServices;
    	using System.Web.UI;
    	using System.Web.UI.WebControls.WebParts;
    
  3. Implement the methods and properties necessary for a Web Part lifecycle. First, you will inherit from a WebPart (make a choice between a System.WebWebPart and a Microsoft.SharePoint one), and then standard methods would be very similar to the Server Control implementation, you should override CreateChildControl and RenderWebPart or Render methods. If you want to use ASP.NET controls in your code, first you have to declare them, and then use CreateChildControl to add them to the Controls collection used by the Web Part. The example here shows the use of a label, but a similar approach is used with any other control:

    	private Label lblMessage;
    	protected override void CreateChildControls ()
    	{
    
    	       lblMessage = new Label ();
    	       lblMessage.Width = Unit.Percentage (100);
    	       lblMessage.Font.Name = "arial";
    	       lblMessage.Text = "";
    	       Controls.Add (lblMessage);
    	}
    	protected override void RenderWebPart (HtmlTextWriter output)
    	{
    
    	       lblMessage.RenderControl(output);
    	}
    
  4. Create a key file to sign your assembly and compile the code. This can easily be achieved in Visual Studio, as you can create .snk files in the Signing section of your project properties (or manually with the snk.exe utility). You have to sign your assemblies if you deploy them to the GAC, but it is not necessary if it is deployed to the bin directory.

  5. Deploy the assembly. Here you can simply copy the .dll file to the GAC or bin directories. Note that if your assembly is in both locations, by default it should be retrieved from the bin directory first.

  6. Set security (if necessary); for simple development, you can set the trust level to “Full.” For more complex development, you will have to create a Code Access Security (CAS) configuration:

    	<trust level="Full" originUrl="" />
    
  7. Modify web.config as shown before, by adding your Web Part information to the SafeControls section.

  8. Create a .webpart or .dwp file. You can either create this file by hand or have it be generated automatically for you. From the Web Part Gallery page, click New, and then click the Populate Gallery button. This Web Part is obviously not installed as a feature and does not have to be activated. A sample structure of a .dwp file is shown here:

    	<?xml version="1.0" encoding="utf-8"?>
    	<WebPart xmlns="http://schemas.microsoft.com/WebPart/v2" >
    	    <Title>title</Title>
    	    <Description>description</Description>
    	    <Assembly>assemblyname</Assembly>
    	    <TypeName>typeName</TypeName>
    	    <!-- Specify initial values for any additional base class or custom
    	properties here. -->
    	</WebPart>
    
  9. Add the Web Part to the page—this is the same as for any other Web Part.

  10. Configure any settings for the Web Part.

Developing Complex Web Parts

Examples in the previous sections have shown all of the necessary steps to develop a Web Part. For hardcore ASP.NET developers, this is probably very familiar, as it is similar to the development of Server Controls.

Tip

When looking at the API and the documentation, carefully observe any new members that have been inherited versus any older members that are marked as obsolete. Members marked as obsolete will typically suggest a new member or interface that should be used instead.

Even if you use a tool such as Reflector to study the Object model, you will be able to read the developer’s comments about most types and even link within the reverse-engineered members.

Table 25-14 lists common Web Part samples and tricks.

Table 25-14. Common Web Part samples and tricks

How To

Sample and description

Access external resources

The following snippet allows you to access resources that are deployed in the wpresources or _wpresources folders:

	SPWeb cWeb = SPControl.GetContextWeb(Context);
	Type cType = BaseWebPart.GetType();
	string classPath = SPWebPartManager.
	GetClassResourcePath(ccWeb, ccType);

Access embedded resources

The following allows you to retrieve files that have been embedded inside the assembly itself:

	string filePath = Page.ClientScript.GetWebResourceUrl(this.
	GetType(), "AssemblyName.folder.filenname.gif");

Develop with a user control

Some people find it easier to develop with a designer pane. As such, you can easily add user controls. In your project, click Add New Item. Then, from the C# section, select User Control. Once your user control is created, simply add it to the page, just like any other server control.

Provide ASP.NET-style Web Part communication

ASP.NET-style communication is done in two distinct ways, depending on whether you want to support existing interfaces or just develop something custom that is specific to your solution. As you can see from the SDK, all of the SharePoint-style communication methods are marked as obsolete. New styles of communication are:

  • Filters: System.Web.UI.WebControls.WebParts.IWebPartParameters

  • Cells: System.Web.UI.WebControls.WebParts.IWebPartField

  • Lists: System.Web.UI.WebControls.WebParts.IWebPartTable

    These interfaces obviously are implemented by other elements of MOSS and provide on-page communication.

    To create a custom Web Part communication, you can simply create a custom interface used for exchange of data, and then mark two methods (one in a receiver Web Part, one in a sender Web Part) as ConnectionConsumer and ConnectionProvider, where the provider returns the shared interface and the consumer accepts it as a parameter.

Conclusion

Web Parts are clearly the technology that makes the SharePoint platform so useful and easy to operate. Whether you develop your own Web Parts or reuse existing Web Parts, you should be aware of where the Web Parts come from, how they interact with the rest of the application, and which Web Parts ship with MOSS. There is no sense in developing new functionality if it already exists!

Also, solid knowledge of what happens behind the scenes is key for administrators as well as developers. You need to know how to troubleshoot your Web Parts, how to deploy them, and, for developers, all of the different pieces and development methods.

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

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