Chapter 11. Developing Web Parts

Since its early editions, Microsoft SharePoint has been famous and popular for the capability to compose pages through Web Parts. First introduced in SharePoint Team Services 2001, Web Parts are simply user-customizable regions hosted by a SharePoint webpage; they have been widely adopted by the market over the years. With Microsoft .NET 2.0, the infrastructure for Web Parts moved from SharePoint to the official ASP.NET web development platform, making the use of Web Parts possible in many kinds of ASP.NET applications. As reliable as ever, Web Parts are still available in SharePoint 2013 and can be useful in many solutions, especially when working on-premises.

To users, a Web Part is simply a piece of a webpage that they can customize from a web browser interface. For example, users can even add and remove Web Parts from pages (often called Web Part pages) by choosing Web Parts from a server gallery or from an online public gallery.

For developers, a Web Part is a class that defines code for rendering its content in the browser, for handling custom configuration, layout, positioning, and so on, within the SharePoint or ASP.NET environment. More importantly, developers can reuse Web Parts in many different pages and sites, simplifying custom solution development, deployment, and maintenance. In fact, many SharePoint solutions are based on a set of custom Web Parts that are referenced in pages.

This chapter explains how Web Parts work and how to develop custom Web Parts, as well as more advanced topics about Web Part development.

Web Part architecture

A Web Part is an ASP.NET custom control that inherits from the base class WebPart from the System.Web.UI.WebControls.WebParts namespace. To be able to fully use a Web Part in a page, you need to define a WebPartZone control, which is a container for a set of Web Parts. The WebPartZone control provides a common rendering pattern to all its constituent Web Parts. Another fundamental control in the Web Parts architecture is the WebPartManager, which handles all the tasks related to Web Part lifetime management—such as loading and unloading them, as well as serializing and deserializing their state within the current page and connecting Web Parts into Web Part zones. SharePoint has its own WebPartZone controls that give you the ability to define a set of SharePoint-specific rendering zones, such as the WebPartZone class for standard Web Part rendering and the EditorZone class to render parts responsible for editing other Web Parts. (Editor Parts will be covered later in this chapter.) Also, the WebPartManager control has been redefined in SharePoint into a custom implementation called SPWebPartManager, which handles some specific activities exclusively available in SharePoint. In order to take advantage of these controls, SharePoint also provides a custom page type called WebPartPage (available in the Microsoft.SharePoint.WebPartPages namespace) that includes a preconfigured and unique instance of an SPWebPartManager control and the main Web Part zones, which are useful for rendering a page made of Web Parts. Figure 11-1 illustrates the overall architectural schema of such a page.

A diagram depicting the architecture of a Web Part page in SharePoint, compared with ASP.NET. Every single Web Part is owned and skinned by its parent Web Part zone, while a unique SPWebPartManager control manages all the various Web Part instances.

Figure 11-1. Overall architecture of a Web Part page in SharePoint and ASP.NET.

In everyday solutions, you will mainly work with Web Parts, and you will rarely have to directly interact with WebPartZone controls and the WebPartManager control.

A Hello World Web Part

It’s time to start developing your first Web Part. Microsoft Visual Studio 2012 provides some project templates (Silverlight Web Part and Visual Web Part) and utilities that can help you to rapidly develop custom Web Parts. Suppose that you need to develop a Hello World Web Part that simply welcomes the current user, writing his or her name and the current DateTime value in the browser. You will begin creating a new project of type SharePoint 2013 - Empty Project. This project template simply starts with a set of assembly references, useful for developing any kind of SharePoint solution, and with a predefined deployment configuration. When you create a new SharePoint project, Visual Studio asks you for the URL of the website where it will deploy the solution. It also asks you what kind of deployment you want to build (farm solution or sandboxed solution). For this example, choose a farm solution deployment. You will see more about deployment later, in the “Web Part deployment” section. For now, you need to concentrate on the Web Part itself.

To develop your sample Web Part, you need to add a new file item of type Web Part to the project. Name the new item HelloWorldWebPart. A new class file is added, together with a set of configuration files, which will be discussed later. Figure 11-2 shows the project layout after you have added the Web Part item.

A screen shot illustrating the outline of a project declaring a new Web Part instance. It includes references to the SharePoint environment, as well as a feature for deploying a custom Web Part, together with its configuration and parameters.

Figure 11-2. The project layout of the sample Web Part solution.

The startup class file for the Hello World Web Part displays the content of the HelloWorldWebPart.cs file, just after you add the Web Part item to the project.

Looking at this code, the first thing you should notice is that the class inherits from the base class WebPart, as mentioned in the previous section. The key point, however, is the override of the CreateChildControls method, where, as with any other ASP.NET custom control, you should create the web control’s tree, which defines the rendering of the Web Part. The code for the sample Hello World Web Part adds a couple of instances of LiteralControl to display the welcome message text inside an <h1> tag and the current date time in a <div> element.

At the beginning of the CreateChildControls method implementation, the code also requests the current SPWeb instance from the SPControl class, through the current HttpContext, so it can get the current user’s login name.

More Info

For further details about the SPWeb and SPControl classes, refer to Chapter 5

As you can see from this introductory example, to be a good Web Part developer, you first need to be a good ASP.NET developer. At the same time, every ASP.NET developer should be very comfortable developing Web Parts.

Figure 11-3 presents the output of the Hello World Web Part, inserted into the home page of a web application.

A screen shot of the output of the custom Hello World Web Part while inserted in the home page of a team site in SharePoint 2013.

Figure 11-3. The output of the Hello World Web Part within a SharePoint 2013 site.

Note

Another way of implementing a Web Part is to inherit from the class WebPart of namespace Microsoft.SharePoint.WebPartPages; however, this class internally inherits from the ASP.NET WebPart base class and is primarily provided for backward compatibility with older versions of SharePoint. If you decide to inherit your Web Parts from the SharePoint WebPart base class, these Web Parts will target only SharePoint sites; you cannot use them in standard ASP.NET websites. By using the SharePoint custom base class, you can take advantage of some additional functionalities that are not available in standard Web Part infrastructure. Although these additional capabilities have extremely limited uses, their few benefits will be discussed at the end of this chapter.

Web Part deployment

Following is the list of actions that occurs while deploying a Web Part:

  1. Build the class into a .NET assembly of type DLL.

  2. Make the assembly available to the web application (putting it into the GAC [Global Assembly Cache], or into the web application local bin folder, or into the Solution Gallery of the current site collection).

    Note

    The GAC is the centralized and shared repository of trusted and digitally signed .NET assemblies. For further details about .NET development and deployment, consult Applied Microsoft .NET Framework Programming, by Jeffrey Richter (Microsoft Press, 2002).

  3. Authorize the Web Part to execute within the current SharePoint environment.

  4. Load the Web Part into the Web Parts Gallery of the current site so that it is available to the end user.

Visual Studio 2012 makes it easy to complete all these deployment steps. Simply select Build | Deploy Solution to automatically deploy the Web Part on the website that you configured while creating the project. Behind the scenes, Visual Studio packages a Web Part solution package (WSP) for you and deploys it on the target environment, following the previously outlined steps.

Take a look at these steps from a practical perspective. Building the .NET assembly is trivial, so I will not cover it here; however, consider that if you ever want to put it into the GAC, you need to give it a strong name (including the name, version, culture, and public key token). Fortunately, Visual Studio 2012 does this for you, automatically adding a set of signing keys to the project. Putting the assembly into the GAC or web application bin folder is also trivial for any .NET developer. Conversely, installing the assembly into the Solution Gallery of the current site collection requires you to know about sandboxed solutions. However, in SharePoint 2013, you should prefer developing apps instead of using sandboxed solutions, in particular when they are used for deploying custom code—and a Web Part is mainly made of custom code. Thus, the deployment of a Web Part through a sandboxed solution will not be covered in this book.

To authorize the Web Part to execute within the SharePoint environment, you need to add a specific configuration item into the web.config file of the current web application, declaring the Web Part as a SafeControl object. At the end of this chapter, you can find more details about the SafeControls configuration section. The custom configuration needed to make the Hello World Web Part safe for SharePoint presents an excerpt of the custom configuration that you need to apply.

Making the Web Part available in the Web Part Gallery requires that you add the Web Part definition to the current site collection. This definition is a .webpart file that Visual Studio 2012 automatically generates when you add a Web Part item to a project. The .webpart file to deploy the Hello World Web Part illustrates the default content of this file in the example.

The key aspect of the .webpart file is the declaration of the type (a .NET type) corresponding to the current Web Part. Notice that a single .webpart file can declare many Web Parts, even if by default Visual Studio 2012 creates a .webpart file for each Web Part definition. The type name of the Hello World Web Part is declared as a full name (namespace plus class name), together with the containing assembly name. In this code example, the assembly name is defined using an alias ($SharePoint.Project.AssemblyFullName$), which Visual Studio 2012 will automatically replace with the real assembly name during the deployment process.

In addition, the .webpart file declares the default values for some of the properties of the Web Part. For instance, you can see that the Title and Description properties of the Web Part are defined as custom property elements within a properties wrapper element.

You can change the values of these properties as well as define some other properties by simply editing the .webpart file in Visual Studio. Table 11-1 provides a list of the most useful properties that you can define.

Table 11-1. Some of the main configurable properties of a .webpart file

Property name

Description

Title

Defines the title of the Web Part. The title will be shown to the end user in the Web Parts Gallery as well as when the Web Part is inserted in a page, and it will be the default title of a newly inserted Web Part.

Description

Describes the current Web Part. This will be shown to the end user in the Web Parts Gallery and when the Web Part is inserted in a page.

TitleIconImageUrl

Specifies the URL to an image used to represent the Web Part in its title bar. The default value is an empty string (“”).

CatalogIconImageUrl

Specifies the URL to an image used to represent the Web Part in the Web Parts Catalog, which is the catalog for browsing available Web Part controls during Web Part insertion within a target page. The default value is an empty string (“”).

ChromeType

Defines the type of border that frames the Web Part. It can assume the following values (the default value is Default):

  • Default. Inherits its behavior from the containing Web Part zone

  • TitleAndBorder. Displays a title bar with a border

  • None. Will not display a border or title bar

  • TitleOnly. Displays a title bar without a border

  • BorderOnly. Displays a border without a title bar

ChromeState

Determines whether the Web Part will appear minimized or normal (not minimized).

AllowClose

Defines whether the Web Part can be closed by an end user.

AllowConnect

Defines whether the Web Part can be connected to another by an end user.

AllowEdit

Defines whether the Web Part can be edited by an end user.

AllowHide

Defines whether the Web Part can be hidden by an end user.

AllowMinimize

Defines whether the Web Part can be minimized by an end user.

AllowZoneChange

Defines whether the Web Part can be moved between different Web Part zones by an end user.

ExportMode

Allows defining if the current Web Part configuration can be exported for reuse on another website.

The .webpart file to deploy the configured Hello World Web Part demonstrates how you can customize the .webpart file for the Hello World Web Part sample: by adding a CatalogImageUrl property to provide a custom image for the Web Part, by changing the ChromeType property, and by enabling editing through the AllowEdit property.

Figure 11-4 illustrates the output of the customized Hello World Web Part. You can also customize the group in which the Web Part will be presented to the end user within the Web Part Gallery. To achieve this result, you need to edit the Elements.xml file related to the Web Part and change the value of the Group property defined in that XML file. Notice the custom category, the custom icon in the Web Parts Catalog, the customized description, and the customized ChromeType property (TitleAndBorder).

A screen shot illustrating the custom Hello World Web Part presented in a custom category, named DevLeap Web Parts, with a custom icon.

Figure 11-4. The output of the customized Hello World Web Part within a SharePoint 2013 site.

As you will see in the “Configurable Web Parts” section later in the chapter, developers can also define Web Part properties that are customizable by site owners or site members with the appropriate permissions. Such properties will be configurable with default values while deploying Web Parts—in exactly the same way as the standard Web Part properties just described.

Real Web Parts

Of course, real Web Parts are a little bit more complex than the Hello World example, and are equipped with a richer set of controls and behaviors. In this section, you will explore two kinds of Web Parts: classic Web Parts made of custom code, and Visual Web Parts, which are designed using the graphical designer of Visual Studio 2012.

Classic Web Parts

A standard classic Web Part is a control that is made up of a set of ASP.NET controls, interacts with the end user through events, and controls behavior. In this section, you will build a data entry Web Part that will collect data from the end user and insert that data into a target SharePoint list. The core engine of this Web Part will use the SharePoint Server Object Model as the means to insert items into the target list. The UI will be built using ASP.NET server controls.

Imagine that you have a target list of requests for contacts available in your SharePoint site, and you want to collect users’ requests using your custom Web Part implementation. Name the Web Part InsertRequestForContactWebPart and create a SharePoint project in Visual Studio 2012 to host it. Next, choose a farm solution project type. The Web Part provides a small set of fields (for the reason of the request for contact and for requesting the user’s full name and email address) to describe the request. These fields correspond to the Requests for Contacts target list that you manually defined in the current website.

Note

In Chapter 3 you learned how to programmatically define and provision data structures of lists like Requests for Contacts. In an actual professional solution, you will probably need to define the list, as well as the Web Parts working on it, in a common SharePoint solution that you will be able to deploy “at once.”

Internally, the Web Part will have a set of ASP.NET controls that correspond to the input fields, and will use the SharePoint Server Object Model (see Chapter 5 for further details) to insert the new item into the list. The whole implementation of the InsertRequestForContactWebPart displays the whole implementation of the Web Part, while Figure 11-5 shows its final output.

A screen shot depicting the UI of the InsertRequestForContactWebPart. It contains a form with fields for the requester’s name, their email address, and the reason for the request, as well as command buttons to control the form.

Figure 11-5. The output of the InsertRequestForContactWebPart within a SharePoint 2013 site.

In The whole implementation of the InsertRequestForContactWebPart, the code highlighted in bold declares the protected variables that hold the ASP.NET server controls. The code inside the CreateChildControls method override instantiates these controls. In particular, notice the binding between the Click server-side event of the button named SubmitRequestForContact and the SubmitRequestForContact_Click method. Within this last event-handling method, you create a new instance of an SPListItem representing a single contact request, compile its fields, and then feed the SPList instance with this new item.

Starting from this second example, it’s easy to imagine that you can build whatever you need, using some ASP.NET code and custom controls, together with some .NET code. For instance, you can develop a Web Part that allows the user to interact with a back-end database, or you can define a Web Part that talks with an external SOAP service provided by a third party. As you let your creativity wander, keep in mind that SharePoint is a strong and secure environment—thus, every kind of customization or solution must be approved and authorized. Later, in the “Deployment and versioning” section, you will learn about the security aspects of developing and deploying custom SharePoint Web Parts that comply with the security infrastructure of SharePoint.

Visual Web Parts

The whole implementation of the InsertRequestForContactWebPart defines all the ASP.NET server controls that make up the Web Part, using a lot of custom .NET code. Designing a Web Part by code is not always convenient, however, because in some scenarios you need to declare UI attributes (such as CSS styles), control positioning and alignment, and so on. In addition, writing and maintaining all the code and controls you create inside a Web Part can be difficult.

Luckily, Visual Studio 2012 offers an out-of-the-box solution for this problem: the Visual Web Part item template defines a Web Part that loads its UI from a custom ASCX control. This kind of Web Part internally creates a dynamic partial class of your Web Part, providing the .NET code for creating what you design in the designer. The basic implementation of the VisualInsertRequestForContactWebPart shows the core implementation of a Visual Web Part that is called VisualInsertRequestForContactWebPart. The invocation of method InitializeControl takes care of loading all the .NET code for defining the UI of the Web Part, which will be designed in the visual designer of Visual Studio 2012.

In the Web Part source code, you need to place not only the code related to the dynamic loading of the UI, but also the event handlers and custom procedures. You can assign all the other aspects of the controls’ tree in the ASCX file, as shown in The ASCX file for the VisualInsertRequestForContactWebPart.

Of course, the benefit of having an ASCX file instead of standard .NET code is that an ASCX file can be defined using the Visual Studio 2012 designer, as shown in Figure 11-6.

A screen shot of the visual designer of Visual Studio 2012 for editing and designing the UI of a Visual Web Part. At the left, the toolbox contains icons for the many standard controls that can be added to the interface, shown at the right.

Figure 11-6. The visual layout of the ASCX file of the VisualInsertRequestForContactWebPart in the Visual Studio 2012 designer.

Configurable Web Parts

In the previous examples, you used a predefined target list for inserting items. In real-world SharePoint solutions, however, authorized users can configure Web Parts. In this section, you will see how to develop configurable Web Parts and how to present a user-friendly interface for Web Part configuration.

Configurable parameters

The first step in creating configurable Web Parts is to define the properties that can be altered. To do so, you simply need to declare a public property in the Web Part class definition, tagging the property with the WebBrowsableAttribute attribute and optionally with the PersonalizableAttribute attribute. A Web Part that provides a configurable property shows a Web Part that declares a configurable property.

The WebBrowsableAttribute class instructs the Web Part infrastructure that the property has to be made available in the configuration panel for the Web Part, which is called the tool pane. This attribute accepts a Boolean parameter named Browsable that is assigned a value of true when the attribute is declared through its default constructor. The PersonalizableAttribute class declares that the property can be personalized and defines the scope of the personalization. It accepts a scope of type User, which means that the property can be personalized on a per-user basis, or a scope of type Shared, which means the property personalization will be shared between all users.

Some other useful attributes can help you better define the configurable property, improving the end-user experience. For instance, you can define a custom category for the property by tagging it with the CategoryAttribute attribute. You can change the caption of the property by tagging it with the WebDisplayAttribute attribute, and you can change the tooltip shown to the end user by tagging the property with the WebDescriptionAttribute attribute. You can provide a default value for the property via the DefaultValueAttribute attribute. A Web Part that provides a configurable property, with all the useful attributes displays a complete definition for the TargetListTitle property.

Figure 11-7 illustrates the UI presented to the user by a configurable property.

A screen shot showing the configuration panel for the custom Web Part. It highlights the Data Foundation group, where the end user can configure the Target List property value.

Figure 11-7. The tool pane of the sample Web Part.

The Web Part editor area in Figure 11-7 is provided by the SharePoint infrastructure and is based on a set of SharePoint-specific classes, called Tool Parts, which can be customized by user code. By default, SharePoint provides a WebPartToolPart class that provides the UI for editing the standard properties of Web Parts (title, chrome type, size, and so on) and a CustomPropertyToolPart class, which automatically allows editing custom properties.

Table 11-2 covers how the CustomPropertyToolPart class usually behaves when rendering custom properties.

Table 11-2. The standard behavior of the CustomPropertyToolPart class while rendering custom properties

Custom property type

Behavior

Boolean

Renders a check box

Enum

Renders a drop-down list

Integer

Renders a text box

String

Renders a text box

DateTime

Renders a text box

You can implement custom Tool Part classes by simply inheriting from the ToolPart base abstract class provided by the Microsoft.SharePoint.WebPartPages namespace. To make a custom Tool Part available to SharePoint, however, you need to inherit the Web Part class from the Microsoft.SharePoint.WebPartPages.WebPart base abstract class provided by SharePoint, instead of using the common System.Web.UI.WebControls.WebParts.WebPart base abstract class provided by ASP.NET. To do so, you need to override the GetToolParts method, returning a custom collection of Tool Parts. This kind of customization works only in SharePoint, due to the dependency on the Microsoft.SharePoint.dll assembly. But developing a Web Part that inherits from Microsoft.SharePoint.WebPartPages.WebPart is not considered a best practice. You should always implement ASP.NET Web Parts, which inherit from System.Web.UI.WebControls.WebParts.WebPart, unless you really need any of the few features available only in SharePoint Web Parts; this will be the focus of the section “The SharePoint-specific WebPart class,” later in the chapter.

Editor Parts

A Web Part that provides a configurable property, with all the useful attributes defined a property that requires the end user to configure the Web Part manually, typing the target list name autonomously. You made use of the standard behavior of SharePoint and the out-of-the-box CustomPropertyToolPart. However, even if it were possible to publish such a Web Part, you would probably agree that this is not a user-friendly and error-free approach. A better solution is to provide a drop-down list with all the lists available in the current website, thereby avoiding typographical errors and the consequent time-consuming debugging tasks. To customize the configuration UI of the Web Parts this way, you can create custom classes called Editor Parts, provided by the Web Part infrastructure of ASP.NET. Editor Parts are controls hosted in a specific WebPartZone control called EditorZone. They are nearly the same as standard Web Parts, except that they inherit from the base class EditorPart instead of inheriting from the WebPart class. This specific base class provides the link between the Editor Part itself and the Web Part currently being edited. To provide a Web Part with a custom Editor Part, you need to override the implementation of the IWebEditable interface, which is implemented by the Web Part base class. The IWebEditable interface definition provides the definition of this interface.

The interface declares a method with the name CreateEditorParts that should return a collection of Editor Parts that support Web Parts with a wide set of Editor Parts. The interface also defines a public read-only property to get a reference to the configurable object that the Editor Parts will target. Usually, the WebBrowsableObject property returns the current Web Part instance (this). The new custom Web Part, implementing the IWebEditable interface displays the new implementation of the custom Web Part.

In The new custom Web Part, implementing the IWebEditable interface, the property TargetListTitle of type String has been changed into the property TargetListID of type Guid so that it can store the unique ID of the target list, and that ID is used to look up the list instance in the SubmitRequestForContact_Click event handler. The code in the listing also turns off the WebBrowsable attribute on the property to hide it from the standard property grid of the Web Part editor. This property will be handled using the custom Editor Part.

Important

If you do not turn off the WebBrowsable attribute of a property that is also configurable through a custom Editor Part, your end user will have both the custom Editor Part and the standard property grid for editing that property, provided by the CustomPropertyToolPart of SharePoint. This is, of course, confusing for the end user and should be avoided.

Next, the code overrides the CreateEditorParts method to invoke the base class method implementation and to add a custom Editor Part, named RequestForContactEditorPart, to the collection of available Editor Parts of the current Web Part. Notice also the definition of a custom ID for the Editor Part instance, based on the uniqueness of the current Web Part ID, to make the Editor Part ID unique as well.

EditorPart is a base abstract class that provides some virtual or abstract methods and properties that are useful for managing the editing of the target Web Part. For instance, every class inherited from EditorPart has a WebPartToEdit property that references the Web Part instance that the Editor Part is currently editing. There are also a couple of abstract methods, called ApplyChanges and SyncChanges, that can be used to save any changes to the Web Part currently being edited, and to load the current configuration from it, respectively.

The RequestForContactEditorPart class implementation gives you an opportunity to evaluate the implementation of the RequestForContactEditorPart class.

As with any other Web Part, an Editor Part must create its controls graph to render its content. In The RequestForContactEditorPart class implementation, the CreateChildControls method override creates a drop-down list and binds it to the collection of lists of the current website.

Then, the ApplyChanges method override saves the currently selected list ID into the TargetListID property of the current Web Part instance. Similarly, the SyncChanges method override autoselects the list with ID equal to the current TargetListID property value in the drop-down list. Figure 11-8 depicts the output of the custom Editor Part.

A screen shot of the configuration panel of the custom Web Part, highlighting the custom Editor Part, which is a drop-down list of all available lists.

Figure 11-8. The configuration panel of the sample Web Part, with the Editor Part in place.

In an actual SharePoint solution, all of the Web Parts will typically provide a rich and complete set of configuration parameters, configurable and customizable through custom Editor Parts.

Handling display modes

During the course of developing real-world Web Parts, sooner or later you will probably face the need to change the rendering of your custom Web Parts, based on the status of the page that hosts them. A page hosting one or more Web Parts can be rendered in display mode (when the end user is browsing the site), in design mode (when the user can design the page layout), or in edit mode (when the end user is configuring or customizing the page and its controls).

To query the page display mode and render a Web Part accordingly, you need to query the DisplayMode property of the WebPartManager (SPWebPartManager in SharePoint). The sample Web Part in A Web Part rendering its content relative to the current page DisplayMode property of the WebPartManager class adapts its rendering based on the current DisplayMode property of the WebPartManager class.

Any class inheriting from WebPart has a shortcut property referencing the current WebPartManager instance. Through this property, you can check the DisplayMode and many other context properties. You can also use the WebPartManager to subscribe to events related to DisplayMode changes. For instance, you can monitor the DisplayMode status with the DisplayModeChanging and DisplayModeChanged events.

Custom Web Part verbs

Another Web Part customization capability that is sometimes useful is the definition of custom Web Part verbs. Web Part verbs are menu items that are displayed in the Web Part menu, as shown in Figure 11-9.

To configure custom verbs, you need to override the read-only Verbs property provided by the base WebPart class. This property returns a WebPartVerbCollection and can be used to completely redefine the menu of a Web Part. Verbs are objects of type WebPartVerb and can be of three different kinds:

  • Server-side. Verbs that require a POST-back to carry out their job; they work on the server side

  • Client-side. Verbs that simply use JavaScript syntax to do their job; they work on the client side

  • Client and server-side. Verbs that first execute some client-side JavaScript, and then can execute some server-side code, unless the client-side code cancels the request

A screen shot showing the contextual Verbs menu provided by a custom Web Part. The menu options are Minimize, Close, and Edit Web Part, and the menu offers three custom verbs for testing: Server-Side Verb, Client-Side Verb, and Client And Server-Side Verb.

Figure 11-9. Sample custom verbs rendered in a custom Web Part.

A custom Web Part with custom verbs presents an excerpt of the sample Web Part, which supports all three kinds of custom verbs.

The interesting aspect of this sample code is the implementation of the Verbs property, where you manually define and configure verbs, and then add them to the resulting collection of Web Part verbs.

Usually, custom verbs are defined in Intranet/extranet solutions to provide support for custom functionalities, such as refreshing content, opening custom pop-up windows, and so forth. In general, they are not used in web content management (WCM) solutions, because the user experience is usually different in these public-facing Internet sites.

Connectable Web Parts

A Web Part is defined as connectable when it can be connected with another Web Part, within the same page, in a provider-consumer relationship. Connectable Web Parts are useful for creating filters and master-detail pages, where one Web Part—the provider—typically renders a selectable list of items or a single master item, and other Web Parts—the consumers—render filtered contents based on the provider’s current item. What happens behind the scenes is that the provider and the consumer share some data, based on a shared communication contract. As a concrete example, you will see how to develop a provider Web Part that offers a selectable list of product categories, and a consumer Web Part that shows the products belonging to the currently selected category.

First, to develop the sample connectable Web Parts solution, you need to define a data source. For the sake of simplicity, The XML data source file for the connectable Web Parts sample example uses an XML data source file, containing both categories and products, so you don’t need to have access to a DBMS to build the example.

The provider Web Part that shows the categories will render a grid containing all the product categories, along with a link button that allows users to select a specific category. The products (or consumer) Web Part will render a grid of products, filtered by the selected category. The provider and the consumer need to share a communication contract, which is an interface that will be implemented by the provider and consumed by the consumer. Thanks to the smart architecture of ASP.NET connectable Web Parts, you can define that interface freely, without any constraints on its properties, methods, and signature. In addition, a typical interface for connecting Web Parts defines only properties that correspond to the data shared between provider and consumer. The communication contract shared between the provider and the consumer Web Parts shows the interface defined for this example.

To make the connection available, you need to implement the interface in a custom type and include a public method in the provider Web Part that returns an instance of that type. Then, to make SharePoint and ASP.NET aware that the method can be assumed as a connection provider, you decorate it with the ConnectionProviderAttribute attribute. An excerpt of the provider Web Part contains an excerpt of an example implementation of the provider Web Part.

As shown in An excerpt of the provider Web Part, the interface is generally implemented directly in the provider Web Part, returning an instance of the Web Part through the method decorated with the ConnectionProvider attribute. The GetCategoryProvider method simply returns this (the instance of the current Web Part), and is marked as ConnectionProvider, with a specific name for the data provided. That name will be shown to the end user while connecting Web Parts.

The other side of this connection—the consumer Web Part—looks like An excerpt of the consumer Web Part.

As its name implies, the consumer Web Part consumes the data presented by the provider Web Part through a specific public method, named SetCategoryProvider, which is decorated with the ConnectionConsumerAttribute attribute.

SharePoint automatically matches the provider method, marked as ConnectionProvider, and the consumer method, marked as ConnectionConsumer, invoking the former to get a reference to the provider instance, and the latter to set the reference. This way, the consumer, which is in its own OnPreRender event method, will be able to check if a reference to a specific data provider exists, and, if so, will query it to get back the currently selected product category.

Figure 11-10 shows the output of these Web Parts connected in a common Web Part page.

A screen shot that illustrates the category and products Web Parts connected in a master-detail configuration.

Figure 11-10. The output of the connected Web Parts within a SharePoint 2013 Web Part page.

Note

It is strategic to query the data provider in the OnPreRender method of the consumer Web Part, instead of, for instance, invoking it in the CreateChildControls method. In fact, in the CreateChildControls method stage, the provider Web Part shouldn’t be ready to provide the currently selected item, while in the OnPreRender stage, the current selection, if any, will be available.

Figure 11-11 shows the configuration interface natively provided by SharePoint to connect a couple of connectable Web Parts.

A screen shot of the Verb menu that SharePoint provides to connect a Web Part with another. The Send Category To menu item, which is automatically provided by SharePoint on a connection provider Web Part, is highlighted.

Figure 11-11. The native interface of SharePoint to connect a couple of connectable Web Parts.

Notice in Figure 11-11 how the Send Category To menu item goes into the Products Web Part item. The Category word is defined in the constructor of the ConnectionProviderAttribute in An excerpt of the provider Web Part.

In the interest of being thorough, Table 11-3 lists the configurable properties of ConnectionProviderAttribute and ConnectionConsumerAttribute. Some of these properties can be configured only through the constructors of these attributes.

Table 11-3. The configurable properties of ConnectionProviderAttribute and ConnectionConsumerAttribute

Property name

Description

AllowsMultipleConnections

In both attributes, indicates whether the connection point allows multiple connections.

ConnectionPointType

Represents a Type corresponding to the ConnectionPoint between the provider and the consumer. Generally, it is automatically assigned; however, it can be created and assigned using a custom type.

DisplayName

Represents the user-friendly name of the connection, used also in the browser UI when connecting Web Parts.

ID

Defines the unique ID of a connection provider and allows a provider to publish multiple unique connections, as well as a consumer to specify its target provider.

As is evident from the properties shown in Table 11-3, you can define a provider Web Part that provides data to multiple consumers, which can prove useful. As an example, if you build custom dashboards—typically for business intelligence solutions—you might have a provider Web Part that supplies the currently selected product, business unit, or whatever you need to monitor, and a set of consumer Web Parts that show detailed information about the currently selected item.

SharePoint by itself provides some native interfaces that correspond to Web Parts connection contracts, as listed in Table 11-4. These interfaces are considered obsolete, however, and you should rely on them only when you need to provide backward compatibility in your Web Parts.

Table 11-4. The SharePoint native connectable interfaces

Interfaces

Description

ICellProvider, ICellConsumer

Contract to provide or consume a single value, like a field or a cell.

IRowProvider, IRowConsumer

Contract to provide or consume a single row or a set of rows.

IListProvider, IListConsumer

Contract to provide or consume an entire list of items.

IFilterProvider, IFilterConsumer

Contract to provide or consume a filter in a master-detail scenario.

IParametersInProvider, IParametersInConsumer

Contract to provide or consume a set of parameters for a Web Part. In this situation, the consumer gives the values of the parameters to the provider.

IParametersOutProvider, IParametersOutConsumer

Contract to provide or consume a set of parameters for a Web Part. In this situation, the provider gives the values of the parameters to the consumer.

More Info

Sometimes, you’ll come across situations in which you would like to connect a provider Web Part, based on a specific provider contract interface, to a consumer Web Part that can’t directly consume that contract, but can consume a different interface. The infrastructure of connectable Web Parts allows you to define interface transformers, which allow you to connect incompatible interfaces. This book does not cover this topic; however, it is important to be aware of its existence. You can find further details about this topic at http://msdn.microsoft.com/en-us/library/ms469765.aspx.

Deployment and versioning

In SharePoint 2013, you can deploy a Web Part in three locations:

  • The Solution Gallery. This allows deploying Web Parts in a sandboxed environment. Although introduced in SharePoint 2010, it is now deprecated in SharePoint 2013. Thus, this chapter will not cover it.

  • The bin directory of the hosting web application. Using this deployment, you can release a Web Part locally to a specific web application, with local maintenance and configuration.

  • The GAC. Code libraries and Web Parts are deployed here so that they can be shared by all the web applications in the current server farm. Code installed in the GAC has full-trust rights on the hosting server.

Regardless of which deployment location you choose, a Web Part is deployed through a .webpart file that’s either included in a SharePoint solution or manually deployed by an authorized user. However, deployment includes not only installing from scratch, but also upgrading from one version to another.

To upgrade a Web Part, one useful suggestion is to release upgrades only through strongly named assemblies. A strongly named assembly can be checked against its signature when .NET loads it, to prevent tampering. In addition, the strong name also declares the assembly version clearly, better supporting upgrade paths.

Note

The .NET Common Language Runtime (CLR) checks the digital signature of a strongly named assembly whenever it loads such an assembly deployed in the bin directory of the hosting application. However, the signature of an assembly deployed in the GAC is checked only when it’s inserted into the GAC. This behavior may sound strange, but only administrators (local or domain) can add assemblies to the GAC. If an administrator inserts an assembly into the GAC, and that assembly has a valid signature, then only another user with administrative rights could change (tamper with) that binary file. So, unless your administrators become hackers, that situation should never happen!

If your upgrade process involves only internal code modification without changes to any public property of the Web Part, and you did not change the assembly version, you can simply substitute the assembly in the deployment location. If you changed some of the public properties of the Web Part, you need to adapt older versions of your Web Part to the last version. If a Web Part page or a wiki page contains an old instance of your Web Part, as soon as someone opens the page, the old Web Part will load, and SharePoint infrastructure will look for its assembly and type. If you replaced the old one with a new version, however, SharePoint will not find the old assembly, and the type load will fail. Similarly, if you renamed, removed, or otherwise changed some properties, the serialization of the old Web Part will not match the new type.

To solve the assembly-versioning issue, you can use the .NET native assembly binding redirect infrastructure. By manually adding a few lines of XML to the web.config file of the web application, you can instruct the .NET CLR to load the new assembly in place of the old one. An excerpt of a web.config file with an assembly-binding redirect directive shows an example of assembly-binding redirect.

This small piece of XML declares that when the CLR needs to load the assembly with name DevLeap.SP2013.VersionableWebPart and a PublicKeyToken value of 6acae404adfa82c3, and with neutral culture and version 1.0.0.0 (oldVersion), it should instead try to load version 2.0.0.0 (newVersion) of the same assembly. Of course, the new assembly must be available in the web application bin folder or in the GAC.

On the other hand, migrating properties from one Web Part version into another is not a trivial feat. If you are upgrading an old SharePoint native Web Part to an ASP.NET Web Part, you can override the AfterDeserialize() method to migrate properties from the old version to the new one. This method will be invoked the first time SharePoint loads a page with an older version of your Web Part in it. For subsequent loads, the Web Part will already be upgraded, and the AfterDeserialize() method will not be invoked again.

Keep in mind that when you are upgrading ASP.NET Web Parts, you cannot use this method. For versioning personalization data in ASP.NET Web Parts, you should instead use the IVersioningPersonalizable interface defined in the namespace System.Web.UI.WebControls.WebParts. The IVersioningPersonalizable interface for Web Part versioning shows the signature of this interface.

The only method defined in this interface is Load, which receives a list of all the unknown properties that should be deserialized, but for which the Web Part environment does not know where to store their values. You can implement this interface to migrate personalization while the framework loads the Web Parts.

For clarity, consider the simple Web Part in A very simple Web Part to show how Web Part versioning works, which has one customizable property.

This Web Part is deployed within an assembly with the following strong name:

DevLeap.SP2013.VersionableWebPart, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=6acae404adfa82c3

Now suppose that you define a new version of this Web Part, changing the assembly version, renaming the public property TextToRender to TextToRenderTimes, and adding a new property, NumberOfTimes. First, you need to define a corresponding binding redirect in the web.config file. Then you must install the new assembly into the GAC, and finally, you need to implement the versioning interface (IVersioningPersonalizable).

The second version of the simple Web Part from A very simple Web Part to show how Web Part versioning works shows an example of a new Web Part that transparently migrates unknown properties.

The Load method of IVersioningPersonalizable receives a dictionary of all the unmatched properties, which lets you match or migrate them to the corresponding new property, if it exists.

Security: Safe controls and cross-site-scripting safeguards

From a security point of view, every Web Part acts in the context of the current user; thus, its security against SharePoint data is based on the current user’s permissions. However, SharePoint data security may not be the ultimate measure of a secure solution. For example, an authorized user could insert a Web Part that represents a risk for the client browser or for the server environment hosting the SharePoint solution. Imagine what would happen if a user uploads a custom Web Part that consumes a lot of CPU resources (perhaps 100 percent) due to a bug or even malicious intent. Any SharePoint front-end server that loads and executes this Web Part would block any further functionality—or at least have its performance seriously degraded.

To avoid such issues, SharePoint provides safe controls. In fact, SharePoint will load and execute only authorized Web Parts, based on a list of SafeControl elements declared in the web.config file of the current web application. When you deploy a Web Part solution at the farm level, the Web Part class is marked as a SafeControl in the web.config file of the site where the control is deployed. If you try to load a page that hosts a Web Part or a control not marked as a SafeControl, the load will fail, but the SharePoint environment will remain stable and secure. A SafeControl declaration for the RSSFeedDynamicViewerWebPart control contains an example of a SafeControl declaration for one of the Web Parts defined previously in this chapter.

Notice that the SafeControl tag references the safe Web Part in terms of assembly, including its strong name, namespace, and type name. The SafeControl tag also defines a SafeAgainstScript attribute with a Boolean value that allows configuring a feature called Cross-Site-Scripting SafeGuard, which was introduced in SharePoint 2010.

Through this feature, only users with the role of designer or higher can customize Web Parts via configuration properties. This means that, by default, a site contributor cannot configure or customize Web Part properties, while prior to SharePoint 2010 that was possible.

Since SharePoint 2010, the Client Object Model is available even in the web browser, via JavaScript. Imagine what would happen if a malicious user configured a Web Part property with some JavaScript code, invoking the Client Object Model to delete or change some data on the server, and that custom property was used to render the output of the Web Part (for instance, a Title property). Of course, the Client Object Model acts in the context of the current user, so the injected JavaScript could do exactly what the current user can do. But what would happen if that same page were opened by a site collection administrator, for example? This new kind of cross-site-scripting (XSS) is natively blocked by the Cross-Site-Scripting SafeGuard feature. This feature impacts not only your new Web Parts, but also any Web Part developed by anyone else.

If—at your own risk—you want to continue to let a Web Part remain configurable, even by site contributors, you can change the SafeAgainstScript attribute of the SafeControl declaration for that Web Part. Figure 11-12 illustrates the UI provided by Visual Studio 2012 for changing this property.

A value of True instructs SharePoint to allow editing and configuration even by site contributors. There is also a new attribute, RequiresDesignerPermissionAttribute, which you can use to tag a property to make it configurable only by users with designer rights or higher. This last attribute overrides any configuration in the web.config file, so if you declare a control with SafeAgainstScript but also define a property marked with RequiresDesignerPermissionAttribute, that property will still not be configurable by a contributor, and will require at least a designer role, regardless of the web.config configuration.

A screen shot showing the editor provided by Visual Studio 2012 for changing the configuration of the SafeAgainstScript property of a Web Part. Included is a list of configurable members, and for each of them you can define the name, assembly, namespace, safety, safety against scripting, and target types.

Figure 11-12. The Safe Control Entries property editor of a Web Part in Visual Studio 2012.

The SharePoint-specific WebPart class

As you learned at the beginning of this chapter, in SharePoint you have the capability to inherit Web Parts from a SharePoint-specific base class, instead of using the standard class provided by ASP.NET. The resulting Web Parts are still fully integrated with the ASP.NET Web Parts infrastructure, because the SharePoint WebPart class internally inherits from that of ASP.NET. These Web Parts can be used only in SharePoint. They have, however, a few additional capabilities that in very specific conditions make implementing SharePoint-specific Web Parts a beneficial choice:

  • Support for SharePoint Tool Parts. This provides support for Tool Parts, which were described in the “Configurable Web Parts” section.

  • Path or code replacement tokens. You can use these to inject tokens in the output HTML code of a SharePoint Web Part, and then have the SharePoint infrastructure replace them with their corresponding values. There are tokens for the current user name, the current locale ID of the website, and so on.

  • Cross-page connections and connections between Web Parts that are outside of a Web Part zone. As shown in this chapter, Web Parts can be connected to each other to build master-detail solutions. SharePoint-specific Web Parts support cross-page connections, while standard ASP.NET Web Parts only support intrapage connections. SharePoint Web Parts can also be connected even if they are outside a Web Part zone.

  • Client-side connections. These are connections between SharePoint-specific Web Parts, based on client-side (JavaScript) code.

  • Data caching. There is a data-caching infrastructure that allows caching of Web Part data into the content database.

Summary

In this chapter, you learned about Web Parts—from their underlying architecture, to developing and deploying them from scratch, to providing custom appearances and behaviors. In particular, you saw how to create configurable and customizable Web Parts, providing the end user with custom Editor Parts, Tool Parts, and custom verbs. You also learned how to develop connectable Web Parts. The chapter also discussed how to deploy Web Parts that support versioning and security.

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

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