Chapter 1. Introducing SharePoint 2010 Web Parts – SharePoint 2010 Web Parts in Action

Chapter 1. Introducing SharePoint 2010 Web Parts

 

This chapter covers

  • Defining a Web Part
  • Using Web Parts
  • Knowing the difference between ASP.NET and SharePoint Web Parts

 

Web Parts are an essential part of Microsoft SharePoint 2010 and one of the first technologies that a new SharePoint developer starts using. You can describe a Web Part as a self-contained application that’s used in a SharePoint site. SharePoint comes with a wide range of out-of-the-box Web Parts and you can download more from Microsoft.com. You can even buy additional Web Parts from third-party vendors or download the source code for some Web Parts from open-source sites such as CodePlex.

Users, developers, IT professionals, and administrators have embraced the SharePoint platform. SharePoint is one of Microsoft’s most important products; it’s their fastest-growing server product. SharePoint is making an impact on all types of organizations, from small businesses to large Fortune 500 companies.

A product like SharePoint is always a challenge to implement. It’s a broad platform, and it’s sometimes difficult to determine what parts to use. Developers have had mixed feelings about SharePoint throughout the years. From the beginning, there was a lack of extensibility and, when that extensibility came, there was a lack of accompanying documentation. Each new version of SharePoint has introduced new challenges for developers, ranging from the developer toolset to the software features. Until recently, skilled SharePoint developers have been rare, probably due to these obstacles, which made the threshold to become a great SharePoint developer quite high. Thanks to excited developers and the strong online community, together with an engaged product team from Microsoft, these obstacles have been addressed with the release of SharePoint 2010. And, this book is a guide to Web Parts development on this new platform.

Microsoft SharePoint is a platform for creating portals and websites where the end user can—without programming skills—create and build websites and solutions using a standard web browser. Using lists, users can store data in SharePoint and/or integrate with external line-of-business systems. Lists can be predefined, such as Contacts, Calendars, or Announcements, or users can create their own. Figure 1.1 shows how a SharePoint site might look using several Web Parts.

Figure 1.1. Add Web Parts of different types to build a rich user interface.

Web Parts are a fundamental component of SharePoint and have been since the beginning of the SharePoint era. Web Parts can be small or standalone applications that you deploy into your SharePoint installation. With Web Parts, you can extend the functionality of your SharePoint investment and create new applications or even integrate with your existing applications to create a gateway from your SharePoint portal. Most of Microsoft’s products, such as Microsoft Dynamics AX and SQL Server Reporting Services, also integrate with SharePoint using Web Parts.

Building solutions and applications using Microsoft SharePoint 2010 allows you to keep your focus on the business logic, meet the customer’s requirements, and implement the cool features. You don’t have to worry about implementing security or authentication, building a framework for creating sites and pages, or creating a solution for deploying and distributing your features onto several servers in a controlled manner. The monitoring of your servers, software, and solutions is a task that’s important for large-scale scenarios, and you get this ability with SharePoint.

Web Parts won’t always be the best way to extend SharePoint. For instance, you’ll usually create lists, content types, and site definitions in SharePoint projects. In addition, Web Parts aren’t always the best tool for long-running calculations or jobs. In such cases, you might consider timer jobs, which you’ll read about later in this book. You might even consider a custom service application. As a SharePoint developer, you must be able to handle many skills and methods, and Web Part development is just one of those skills. To be a good SharePoint developer, you need to know when to use a Web Part—and when not to. That includes knowing when to use an out-of-the-box Web Part, customize a Web Part, or go in an entirely different direction. By discerning the best solution, you’ll save you and your customer a lot of time and money. In this chapter, I’ll introduce you to the world of Web Parts.

1.1. What is a Web Part?

Before we dig down deep into developing Web Parts for SharePoint 2010, you should know what a Web Part is. As the name implies, it means parts of a web. Web Parts are the building blocks for building web pages in SharePoint. Web Parts are essentially ASP.NET web controls that inherit the web control base class in ASP.NET but have special abilities compared with ordinary ASP.NET web controls. These special abilities focus on giving the end user or administrator, and not the developer, the possibility to customize, move, and edit the control. Normally, ASP.NET controls are configured and programmed on the server side with no or limited options for the end user to modify its properties. Web Parts, on the other hand, are building blocks that the end user can choose from to build their own web page. For example, the user may decide that a particular Web Part should show the contents of a document library with a specific set of columns, that another Web Part should display a graph generated from a data source, and so on. The most used Web Part in SharePoint is the one that shows a view of a SharePoint list, such as a task list, a calendar, or a document library.

All Web Parts have a common set of properties, including the title, size, chrome layout, and other appearance settings. They also share a common set of methods. That way, they’re initialized and rendered so that the web page that contains the Web Part doesn’t have to know exactly which Web Part it’s going to show—just that it’s a Web Part.

In a Web 2.0 standard fashion, the Web Part infrastructure also handles personalization of Web Parts and Web Part pages, which means that every end user of the Web Part can have their own configured web page that looks different from the same page for other users.

An important part of the Web Part infrastructure is the ability to connect Web Parts. Connected Web Parts can send or retrieve information from one Web Part to another. This concept allows developers to create advanced web pages and dashboards that users can connect to via the web interface. SharePoint provides a special kind of Web Parts called filter Web Parts. They have one purpose: to deliver a filter to other Web Parts so that their content can be filtered. For example, suppose you have a product catalog Web Part. You can set up a filter Web Part that filters the product catalog when users choose a product category in the filter Web Part.

All these factors together are what makes Web Parts so interesting and useful when creating custom applications or solutions for SharePoint. You as a developer can create configurable applications that users can adapt to their method of work. The user might also combine the Web Parts by connecting them together and, from that, create their own applications or mashups.

 

Note

A web page or web application built using different external sources or open APIs is often referred to as a mashup. You might consider everything in SharePoint, including Web Parts, Business Connectivity Services (BCS), and InfoPath, as external sources for mashups.

 

The concept of Web Parts isn’t unique to SharePoint. All major vendors and platforms have their version of Web Parts that are more or less evolved. In the Java world you might know them as portlets, Google uses gadgets for their iGoogle site, and so on. Web Parts can also be used to connect portals from different vendors and platforms using, for instance, the Web Services for Remote Portlets (WSRP) standard, which allows you to publish content from one portal to another, or the recently ratified Content Management Interoperability Specification (CMIS) standard.

If you’re an ASP.NET developer, you might be familiar with Web Parts, because that infrastructure exists in the ASP.NET 2 Framework. SharePoint is built on top of ASP.NET and has extended the Web Part infrastructure and introduced a number of new and improved features. Using Web Parts instead of building custom ASP.NET applications allows you to take advantage of the SharePoint feature set, including infrastructure, user management, deployment, and scalability. This enables you to focus on the business goals of the application instead of building a new infrastructure.

Web Parts are essentially ASP.NET WebControl objects or, to be more exact, ASP.NET Panel objects. Therefore, from a developer perspective, the first thing you need to learn is ASP.NET programming in the language of your choice: C#, Visual Basic, or even F#. SharePoint 2010 is built on the .NET Framework version 3.5 and ASP.NET 2, so anything in those frameworks can be used when developing Web Parts for SharePoint 2010. This book assumes that you’re familiar with ASP.NET 2 development and we’ll highlight only those areas where you have to be extra careful. One of the most important and, very often, underestimated concepts is the ASP.NET page and control life cycle. In the later chapters, you’ll see examples of why this concept is so important.

 

Note

All code samples throughout the book will use C#. You can download these samples from www.manning.com/wilen or www.sharepointwebpartsinaction.com.

 

1.2. Why use Web Parts?

Web Parts are just one but important component of the huge SharePoint product—without Web Parts, you couldn’t enjoy the platform’s flexibility. It’s the Web Parts that make SharePoint as well as other Web Part–based portals interesting for both editors and end users. As mentioned earlier, building a new web page or site can be done without programming skills. Editors create their pages and choose Web Parts from a gallery. Then, they customize a Web Part and save the page—and, all of this is done from the browser. The Web Parts that users can choose are determined by the administrator (and the permissions on the Web Parts). A Web Part’s configuration options are defined by the developer who created the Web Part.

One of the reasons Web Parts are easy to use when creating custom applications for SharePoint is that they can be self-contained or grouped together. The business logic and the user interface are based on the .NET and ASP.NET development, which lets you get started right away, if you’re familiar with .NET development.

Because Web Parts share a lot of common features and they’re managed in the same way, it’s easy for the end user to get started with a new Web-Part–based application. If users are familiar with SharePoint, they know how to find, add, and edit a page’s Web Part. This makes the adaptation of new features or applications in your SharePoint environment faster and easier.

You can deploy a Web Part to the site collections of the SharePoint environment that you want your Web Part to be able to run in, and you can even control who can use the Web Parts through the built-in permissions in SharePoint.

SharePoint 2010 comes with a number of Web Parts that you can use—which ones are available depends on which version of SharePoint you’ve installed. Appendix A, “Out-of-the-box Web Parts,” contains references to the most used Web Parts and their corresponding edition. Web Parts come in a couple of different types. The basic Web Part shows user tasks, the contents of a list, or a graph. Then, you have Web Parts that need customization, such as the Content Editor Web Part or Forms Web Part. For more advanced use, there are the new XSLT List View Web Part or the Data Form Web Part; both need to be configured using SharePoint Designer, and you can use them to create more advanced applications than you can using just the web browser.

Also available are complete suites or standalone Web Parts that can be downloaded for free or purchased. In many cases, getting one of these off-the-shelf products can solve your problem for a much lower price compared with the cost of developing a Web Part. You can custom-design applications, perhaps, in combination with these standard products and build Web Parts that do exactly what you want.

When do you need to create your own Web Parts? The Data Form Web Part is an excellent tool and should be used whenever possible. It’s great for connecting to an external data source or web service and, then, all you have to do is customize the view of the data. SharePoint 2010 also introduces a new way to connect to external data using External Lists in SharePoint. External Lists, in combination with the out-of-the-box Web Parts, can be used to create an interface for your custom database in SharePoint using just configuration techniques.

 

Note

BCS is the evolution of the SharePoint 2007 Business Data Catalog (BDC), which allows you to connect to external data sources such as databases or web services. Data sources can be visualized in an External List, which looks and acts like a standard SharePoint list for the user but the data still resides in the connected system. SharePoint Designer 2010 is the tool to use when creating external entities and mapping them to external data sources. In SharePoint 2007, BDC was an Enterprise feature but, in SharePoint 2010, a part of the BCS is available in the SharePoint 2010 Foundation edition.

 

Custom Web Part development takes all of these approaches one step further: you have full control of what’s going to be shown and you can create an interface that lets your user interact with the Web Part in a more advanced and sophisticated way than with the standard Web Parts. Using agile development methods, you can even involve the users early in the development process and iterate until you have a satisfied customer. The developer has the power to make the Web Part configurable for the end user. Compare that to the Data Form Web Part, where the administrator configures the Web Part and, then, all the user can do is watch and use the result. Most configuration of the Data Form Web Part has to be done using the SharePoint Designer application—which normal users don’t have access to—or requires skills in eXtensible Stylesheet Language for Transformations (XSLT)—which typical users generally don’t understand.

 

Note

Agile development has become popular in recent years. It’s a set of methodologies focusing on some simple principles, which include an iterative approach and early and continuous delivery. Some of the most popular agile methods are Scrum, test-driven development (TDD), and continuous integration.

 

As a Web Part developer, you have full control of the user interface. This is especially important when you’re creating Web Parts for publishing sites, where you might need to control the exact output of the Web Part or if you’re using a dynamic Ajax-based interface and you need to run client-side scripts.

Building custom Web Parts gives you access to the complete object model of SharePoint and can be used to modify or show content that the user normally wouldn’t have seen using elevated privileges. For example, you might store data in a SharePoint list that’s protected by permissions so that users aren’t allowed to see the list. You can then create a Web Part that uses the System Account context, reads data from the list, presents that data to the user, or lets the user update the data.

SharePoint 2010 has been updated to support mobile devices better than its successor—and it’s not just about the way it displays lists and libraries. SharePoint now has support for converting your Web Part pages into mobile views, and you can convert the Web Parts to mobile Web Parts using special mobile adapters. If you compare that to a no-code solution built using custom JavaScript, which relies on a powerful browser and perhaps isn’t adapted to a smaller screen, you’ll find that building Web Parts and mobile adapters will improve your user experience significantly.

Another interesting aspect of Web Part development is when you have an out-of-the-box Web Part or third-party product that you’d like to enhance. As long as the Web Part isn’t sealed, you can subclass it to enhance your version and override its default logic. This is a common task, and I’ve seen and used several subclassed versions of the Content Query and the Search Web Parts (which are not sealed in SharePoint 2010).

Web Parts can be powerful, which isn’t always a good thing. Because you can run whatever .NET code you like in your Web Part, there’s a risk that malicious or badly written code may cause damage to your applications and data. SharePoint has several mechanisms that help you control those scenarios through policies applied during deployment. With the new sandboxed solutions, you can even allow Web Parts from less trusted sources to run in your SharePoint environment in a special protected process. The sandboxing feature in SharePoint 2010 will be discussed in more detail further in this book.

1.3. Introducing the Web Part infrastructure

Before we go further, let’s explore some basic facts about site pages and Web Parts in SharePoint. If you’ve been working with SharePoint or ASP.NET, this might be old news to you but, nevertheless, it’s always good to refresh your memory. This section examines the various components in the Web Part infrastructure that you’ll encounter when building a page. In addition, you’ll get your first look at a simple Web Part. You’ll learn the different components and their responsibilities. Familiarize yourself with the technical terms because I’ll use them throughout the book.

1.3.1. Web Part page

A Web Part page, which most often is the type of page you use to host Web Parts, is an ASP.NET page that inherits from or uses a specific SharePoint page class, the WebPartPage. This class, in turn, is inherited from the standard ASP.NET Page class. The responsibilities of a Web Part page are:

  • Connecting to the SharePoint context.
  • Performing user authorization.
  • Hosting the Web Part Manager.
  • Hosting the Web Part zones.
  • Hosting the special zones for Web Part properties and the Web Part Gallery.

To use Web Parts on a web page, that page needs to be equipped with one Web Part Manager and, optionally, Web Part zones. The Web Part Manager in SharePoint is defined in the master page, which makes it available to all pages using that master page. Figure 1.2 shows how the building blocks of a Web Part page are organized. Web Parts can live inside or outside a zone. When a Web Part is outside a zone and managed by the page, that Web Part is called a static Web Part and can’t be customized by the end user using the web user interface. If a Web Part exists in a zone that’s managed by the Web Part Manager, it can be customized and the customization can be persisted so that it’s retained; it’s then called a dynamic Web Part. The Web Part zones can also allow the user to add, remove, or move Web Parts that the user either can upload or find in the Web Part Gallery.

Figure 1.2. The building blocks of a Web Part page and how they’re located in relation to one another

The Web Part Manager and Web Part zone objects are defined in the ASP.NET object model, but SharePoint uses its own implementation of these objects. .NET Framework has a provider model that allows developers to create their own backends for Web Part storage, and the SharePoint product team has created providers for SharePoint and enhanced them for SharePoint use. The customization and personalization of Web Parts are stored in the SharePoint content databases using the SharePoint implementation of the provider model.

1.3.2. Web Part Manager

The Web Part Manager control is responsible for handling the various Web Parts on a page. It deserializes and serializes Web Parts and their customizations from the content database, correctly places them in Web Part zones, and, optionally, connects them. During the Web Part page life cycle, a Web Part Manager fires and forwards all of the events on the different Web Parts. A Web Part Manager is responsible for:

  • Persisting properties and customizations of Web Parts.
  • Managing the Web Part connections.
  • Managing the Web Parts in Web Part zones.
  • Wiring up the events to the Web Parts.
  • Managing standard and mobile views.

There can be only one Web Part Manager on a page. In SharePoint, a Web Part Manager is defined in the master page. Removing it from the master page or adding it directly to a page can make the page fail.

1.3.3. Web Part zones

A Web Part zone acts together with the Web Part Manager to render Web Parts onto the page. It’s responsible for creating the chrome—any borders or styles around the Web Part—as well as for rendering the necessary scripts to make the Web Parts able to react to drag-and-drop actions. A Web Part zone contains a set of properties that defines the layout of the zone. The responsibilities of a zone are:

  • Defining the areas where Web Parts can be added.
  • Defining the appearance (header, footer, frames, and so on) and the behavior of the zone.
  • Specifying whether the Web Parts within a zone can be customized and/or personalized.
  • Rendering the Web Parts in a zone.

Web Part zones and the wiki content controls have undergone a major overhaul since the 2007 version. In SharePoint 2010, the wiki content areas and the rich HTML fields for Publishing pages can be used as Web Part zones. Yes, you’ve heard that right! In a wiki (see figure 1.3) or a Publishing page, you can add your Web Parts into the wiki content or rich text between the paragraphs or even in the middle of a word.

Figure 1.3. The default SharePoint 2010 Team Web is based on wiki pages. Wiki pages in SharePoint allow you to add Web Parts directly into the wiki content.

 

Note

Internally, SharePoint uses a hidden Web Part zone, with the id wpz, to manage the Web Parts in the wiki content. This Web Part zone is necessary so SharePoint can store its configuration. Each Web Part is marked in the wiki content using hidden DIV elements that reference the unique identifier of each Web Part (in the hidden zone).

 

1.3.4. Web Part elements

The Web Part itself consists of several parts, as shown in figure 1.4. It has a content area, which you as a developer are focusing on. The content area is where a Web Part renders the content and the controls. The title of a Web Part can be configured through a property, but its layout is controlled primarily by the zone.

Figure 1.4. A Web Part consists of a content area surrounded by the chrome. All Web Parts also have a title and a menu containing a set of verbs. You can configure the title and the menu so they don’t display.

A Web Part has an Options menu, normally in the upper-right corner, and this menu contains actions called verbs. We’ll discuss verbs in detail in chapter 4 but, for now, just know that a verb is defined as an action that belongs to the Web Part type. The action that’s executed is controlled by the developer in the Web Part object. The Options menu also contains some other standard Web Part verbs, such as Minimize, Close, Delete, and Edit. The actions that appear reflect the user’s permissions on the page and the Web Part’s configuration.

1.3.5. Web Part Gallery

Each site collection in SharePoint has a set of galleries (sometimes called catalogs) containing the various artifacts that are used to build the sites in the site collection. One of these galleries is the Web Part Gallery. This gallery contains all the Web Parts that are available for the editors in that site collection. When creating a Web Part page, users can choose a Web Part from this gallery and add it to the page. Administrators can add new Web Parts to the gallery via web interface.

Each Web Part in the gallery has a set of metadata attached to it, such as a group for grouping Web Parts, as well as default values for the Web Part properties and permissions. The Web Part Gallery will be discussed in greater detail in chapter 2.

1.4. Types of Web Parts

One of the first questions Web Part developers ask themselves is why there are two implementations of the WebPart class: one ASP.NET version and one SharePoint version. These implementations have similarities as well as differences. The reason behind the two implementations is that, when SharePoint Portal Server 2003 and Windows SharePoint Services 2.0 were introduced, they were based on Microsoft .NET Framework 1.0 and ASP.NET 1.0, neither of which had the Web Part infrastructure. The Web Part infrastructure was introduced later in ASP.NET 2.0. In late 2006, when Microsoft Office SharePoint Server 2007 and Windows SharePoint Services 3.0 came out, they were built on top of ASP.NET 2.0 and implemented in such a way that they accepted both the old SharePoint Web Part implementation (to be backward compatible) and the ASP.NET Web Part implementation. What happened was that Microsoft rewrote the SharePoint 2003 Web Part implementation and made it inherit from the ASP.NET 2.0 Web Part, which made it compatible with SharePoint 2007.

How does this affect the situation for developers? Numerous discussions have taken place about the pros and cons of the different versions; one camp believes that you should use the old SharePoint-based Web Part due to its specific abilities, and another camp claims that the ASP.NET 2 Web Part is better because it’s newer and Microsoft recommends it. In the next few sections, I’ll explain when you should and should not use each version. The choice of implementation is really up to you—you have to evaluate the pros and cons of respective implementations. My recommendation, which also is Microsoft’s recommendation, is that you should always start out with an ASP.NET 2 Web Part and only use a SharePoint Web Part if you need that implementation’s specific features. Both versions are equally supported by SharePoint 2010, but this book will primarily focus on the ASP.NET 2 implementation. (When the SharePoint implementation is used, I’ll point that out.) I’ll highlight the differences and the advantages and disadvantages of the two versions and, finally, take a look at what has changed since the previous versions of SharePoint.

1.4.1. ASP.NET 2 Web Parts

The ASP.NET 2 Web Part was introduced when Microsoft released .NET Framework 2, together with a framework that allowed you to create your own providers for storing Web Part information, such as customization and zone information. This framework was used for building SharePoint 2007, and it’s almost the same in SharePoint 2010.

ASP.NET Web Parts are defined in the System.Web.UI.WebControls.WebParts namespace in the System.Web assembly and are a part of ASP.NET. This means that if you write a Web Part using this implementation, you can start building it for a non-SharePoint environment; an example is a custom portal built with ASP.NET. Once you start adding references to the SharePoint assemblies and namespaces, you’ve lost this benefit and you are stuck with having your Web Part in SharePoint. Later in this book, we’ll discuss various design patterns to use when building Web Parts, and you’ll learn how to work around these issues.

ASP.NET Web Parts are the implementation that Microsoft recommends you use when building Web Parts for SharePoint. They’re said to be the future of Web Parts. Nothing has really happened to Web Parts in the .NET Framework since the release of 2, and .NET Framework 4, which was released in early 2010, doesn’t show any changes in the Web Part implementation.

SharePoint 2010 and Visual Studio 2010 features a new Web Part project type called Visual Web Parts (which we’ll discuss further in chapter 3), and those Web Parts are based on the ASP.NET Web Part. Essentially, a Visual Web Part is a standard Web Part class that loads a user control (ASCX file), and this control can be edited using the Visual Studio 2010 visual designer. This will make your Web Part development experience more pleasant, and you’ll save a lot of time because you don’t have to manually create the controls and events and add them to the control tree.

 

What about .NET Framework 4?

Although .NET Framework 4 has been released, SharePoint 2010 is still built with .NET Framework 3.5 (Service Pack 1). The reason behind this is that the SharePoint team thought that it was too risky to work with the new framework, because .NET 4 still was in beta.

The .NET Framework 4 contains side-by-side execution of different .NET versions, which leads me to believe that we’ll soon be able to run .NET 4 code in SharePoint. When you’re installing Visual Studio 2010, which you’ll do on your development machines, .NET 4 is a prerequisite.

 

When it comes to sandboxing (which means that the code is executed in a controlled and isolated environment), the only supported Web Part implementation is the ASP.NET Web Part. This is due to the sandboxing restrictions that don’t allow you to dynamically load a user control or use the SharePoint Web Part implementation.

Here are the main benefits of using ASP.NET Web Parts:

  • They’re Microsoft’s recommended choice for Web Part implementation.
  • They’re the future of Web Parts.
  • They form the base of Visual Web Parts.
  • They can be used to create non-SharePoint-hosted Web Parts.
  • They support sandboxed deployment, unless standard Visual Web Parts are used.

 

Note

The freely downloadable Visual Studio 2010 SharePoint Power Tools contain a Visual Web Part that can be used in sandboxed solutions.

 

1.4.2. SharePoint Web Parts

SharePoint Web Parts remain in the SharePoint API due to large investments in these Web Parts since the time of SharePoint 2003 and because SharePoint Web Parts have some interesting features that ASP.NET Web Parts don’t.

The Web Part implementation from SharePoint is defined in the Microsoft.SharePoint.WebPartPages namespace and exists in the Microsoft.SharePoint assembly. Once you derive your own Web Part from this class, your Web Part is tied to SharePoint and you can’t reuse it in other ASP.NET-based solutions. The SharePoint Web Part inherits from the ASP.NET Web Part, so everything that you can do with an ASP.NET Web Part you can also do with a SharePoint Web Part.

The main reason for using this Web Part implementation is that it has some exclusive features when working with Web Part connections, features that the ASP.NET Web Part doesn’t provide. The SharePoint Web Part can be connected to other Web Parts that either reside on other pages within the site or that don’t exist in any zone (in other words, static Web Parts). The ASP.NET Web Part only accepts connections between Web Parts placed in zones and on the same page. The SharePoint Web Part can also handle client-side connections using the Web Part Page Services Component (WPSC). This is no longer such a big deal because the new SharePoint 2010 Client Object Model, in combination with JavaScript, can be used to create a similar experience. Another reason for using the SharePoint Web Part is that it has a built-in feature for caching content.

Using this implementation might expose you to a risk, if you’re looking for a long-lived product. You can’t be sure that this implementation will be supported in upcoming versions of SharePoint.

The main benefits of using the SharePoint-based Web Parts are that:

  • You can use cross-page connections.
  • You can connect to static and dynamic Web Parts.
  • These Web Parts offer built-in caching.
  • You can take advantage of client-side connections using the Web Part Page Services Component.
  • You might need SharePoint-based Web Parts for backward compatibility.

The single most important reason why developers choose the SharePoint Web Part implementation is that it can use connections between Web Parts that don’t exist in Web Part zones or even on other pages. One example is when you have a dashboard page with a couple of zones and you’ve added a filter Web Part on your page but not in a zone, so that each page of this kind will always have that filter and the user can’t remove it. Using the new Client Object Model (described in chapter 10) and JavaScript, you can reproduce a similar behavior if you need it by using the ASP.NET Web Part implementation.

Caching is important for high-scalability solutions, and the SharePoint Web Part has a built-in caching mechanism. If you need caching in your Web Part, then the SharePoint implementation might be a good candidate to start with. But the ASP.NET 2 Framework also has built-in support for caching in several ways. Using this ASP.NET caching mechanism, you can easily create your own caching and still be able to use the ASP.NET Web Part implementation. I strongly recommend that you implement caching yourself using the ASP.NET Web Part, and I’ll show you how in chapter 9.

1.4.3. Changes in the Web Part infrastructure for SharePoint 2010

The Web Parts in SharePoint 2010 are derived from both implementations, but most of the new Web Parts derive from the ASP.NET 2 Web Part. This might be an indication of what Microsoft is trying to achieve for future versions of SharePoint. Even though, for the most part, ASP.NET Web Parts are used and SharePoint Web Parts are there for backward compatibility, there have been minor internal changes to the SharePoint Web Part implementation.

The SharePoint WebPart class hasn’t changed much and doesn’t offer developers any new features. Some internal changes have been made to the implementation related to the new SharePoint 2010 user interface, such as Ribbon integration.

The WebPartZone, SPWebPartManager, and other related classes have had some updates related to the Wiki Web Part zones. The updated SPWebPartManager also provides support for the mobile view of Web Part pages as well as mobile Web Parts. These changes are mostly internal to the assembly but, in later chapters, when we focus on these components, you’ll see how you can use some of these enhancements.

One of the most notable changes is that the customization of a Web Part is versioned just as the Publishing Web Part page is versioned, which was not the case in earlier versions of SharePoint. This is an important improvement and it’s crucial for you to be aware of it. If you roll back a page to a previous version, any changes to your Web Part customization will also be rolled back. The upside is that versioning makes it easier for you to experiment with customizations of a Web Part—if you’d like to go back to the original or working state, you just roll back the page.

To improve security and to prevent injection of malicious code, the Web Part infrastructure includes cross-site scripting (XSS) protection. We’ll discuss this protection mechanism further in chapter 7.

1.5. Hello World example

You’ve just read about the basics of Web Parts and their infrastructure. Because this is a book for developers, what would be better than looking at a Web Part using the classic Hello World sample in a Hello World Web Part? This simple Web Part will write the text “Hello World” in the Web Part content area. The result for the end user should look similar to figure 1.5. The text is written in the content area and the title is automatically generated by Visual Studio. The Web Part options menu shown in the figure is the default menu of any Web Part.

Figure 1.5. A Hello World Web Part, showing the default Web Part options menu in the right corner

The Hello World example in the following listing is quite basic if you’re familiar with ASP.NET development. Using Visual Studio 2010, you first have to create a SharePoint project and then add a Web Part item to that project with the name HelloWorldWebPart.

Listing 1.1. Hello World Web Part
public class HelloWorldWebPart :
    System.Web.UI.WebControls.WebParts.WebPart {

    public override void CreateChildControls() {
        Label label = new Label();
        label.Text = "Hello World!";
        this.Controls.Add(label);
        base.CreateChildControls();
    }
}

The Web Part is defined in the HelloWorldWebPart.cs file. The class derives from the ASP.NET Web Part class, which exists in the System.Web.UI.WebControls.WebParts namespace and System.Web assembly. To add the Label control, you override the CreateChildControls method, and in the overridden method, a new Label control is created and added to the control tree. The Text property of the Label control gets the value of "Hello World". Using Visual Studio 2010, you press F5 to build and deploy the Web Part into SharePoint 2010. The Web Part will be added to the Web Part Gallery during the deployment, and all you have to do is edit a page, locate the Web Part in the gallery, and add it to the page. This F5 deployment will be shown in greater detail in chapter 3.

As you can see from the sample code, the title and options aren’t specified. The Web Part’s title inherits from the base class and is, by default, the name of the class. Every Web Part has a set of default verbs that are added to the Options menu.

Later, I’ll walk you through the steps involved in the creation and deployment of Web Parts using Visual Studio 2010, and I’ll do the same with the Web Part Manager, zones, and connections. In SharePoint, along with the compiled assembly for the Web Part that you deploy to SharePoint, there are a few more files, and we’ll cover them all as well. But, first, let’s continue our look at the Web Part infrastructure.

1.6. SharePoint 2010 pages

We’ve gone through all the basics of the Web Part infrastructure in SharePoint 2010. Now, it’s time to take a look at the pages where you use your Web Parts. To understand where you can use the Web Parts you’re developing and where you have to use other approaches, you must have a good grasp of the concept of pages in SharePoint.

As previously stated, a page that has a Web Part Manager and, optionally, a zone can be used to host Web Parts, and this is almost the whole truth. SharePoint has two basic page types, application and site pages, and each serves its own purpose. These page types are based on a single ASP.NET master page that allows SharePoint to have a consistent interface framework.

First, we’ll share some SharePoint basic knowledge. Pages exist in SharePoint sites. A SharePoint site represents a set of lists, libraries, groups, features, subsites, and so forth. These sites are grouped into site collections. Every site collection has a top-level site, which may have one or more subsites.

 

Note

The SharePoint API doesn’t use the site collection and site naming conventions but, instead, uses site and web, where the SPSite object represents a site collection and SPWeb represents a site.

 

Sites in SharePoint 2010 have a special library called site pages (/SitePages/), which normally contains the web pages of a site, similar to the Pages library that the Publishing sites use to store the pages. The Site Pages library is new to SharePoint 2010. In SharePoint 2007, you either had to create a library on your own or resort to the more commonly used scenario: put your pages directly into the site. The advantage of a Site Pages library is that you can turn on versioning and/or workflows on all your site pages.

1.6.1. Application pages

First, we’ll review application pages. Application pages are most often used as configuration pages for features or applications. Application pages can’t host Web Part zones and therefore aren’t dynamic Web Parts. You can use static Web Parts (those living outside a zone) though. A good practice is to use web or user controls instead of Web Parts when building application pages. These pages can’t be controlled or edited by end users and should only be used for custom applications. They behave very much like a standard ASPX page. When you deploy or update application pages, you do so directly to the ASPX file in the file system. This is important; in a SharePoint farm, each server has a copy of these files and any changes and additions must be replicated to all servers (preferably using SharePoint Solution Packages, which is also the recommended way of doing this, as you’ll see later in this book). Application pages are also known as layout pages because they exist in the Internet Information Services (IIS) _layouts virtual directory. The files are stored in the TEMPLATES\LAYOUTS subfolder of the SharePoint root (see the accompanying note) and virtualized as the _layouts subfolder of each SharePoint site.

 

Note

The SharePoint root is the folder where SharePoint stores its file on the server. It was previously and unofficially called the 12-hive, from version 12 in SharePoint 2007. It is located in c:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\. Rather than writing the whole path I’ll use {SharePoint Root} throughout this book.

 

1.6.2. Site Pages

Site pages are the pages in SharePoint that are created while a site is provisioned by the user or by different triggers. Typical site pages are the default or home pages created in a site, the AllItems.aspx list view page and the EditForm.aspx form page used to edit list items. These pages can be customized or modified by the end user using the browser, SharePoint Designer, or using other tools or techniques. There are a few different types of site pages; this book will focus on the Web Part and wiki pages. For publishing sites, there’s a special type of page called the Publishing page that inherits from the Web Part page and is specifically designed to have a flexible layout. You can also create your own types of site pages by inheriting from or customizing any of the existing types.

Web Part Pages

A Web Part page is the simplest kind of site page. It’s based on the master page, just like all other pages in SharePoint, and is equipped with a set of Web Part zones. The Web Part page is used for all form and view pages for lists and libraries. These pages are limited to changes in the Web Part zone, and in SharePoint 2010 the use of Wiki pages should be considered when creating pages.

Wiki Pages

In SharePoint 2010, the default page becomes a wiki page, which has several benefits (compared with previous versions, where the default page type was a Web Part page). First, all text and content editing is easier and more user friendly with the WYSIWYG interface. Second, the wiki content areas have been hugely improved and now act as Web Part zones. In SharePoint 2007, the wiki content area was just a place where you could have content such as text, links, and images, with very limited editing possibilities. SharePoint 2010 wiki content areas can contain text, links, images, and Web Parts, and you have far better editing tools. The page editor can add and remove Web Parts in the wiki content and drag the Web Parts around and place them in appropriate positions, as shown in figure 1.6.

Figure 1.6. Wiki pages in SharePoint 2010 can contain Web Parts within the wiki content.

The wiki pages, inheriting from the WikiEditPage class, always contain a hidden Web Part zone that is used for storing the Web Parts that exist in the wiki content areas. In other words, the wiki content areas aren’t Web Part zones. The wiki content contains special tags where Web Parts are placed. When SharePoint finds one of these tags, it locates the Web Part in the hidden zone and renders it into a buffer. Finally, this buffer is flushed out to the page.

 

Note

Wiki is a Hawaiian word that means fast. A wiki typically is a website that allows for easy creation, editing, and linking between wiki pages using a specific syntax or editor. SharePoint 2010 uses a WYSIWYG editor and, using the [[ and ]] symbols, links to pages are created. If no page exists at the link, the editor will be asked to create a page once they click on the link.

 

Publishing Pages

Publishing pages are most often used in enterprise portals or public-facing websites. A Publishing page is a Web Part page that uses specific field controls to render the publishing content. A Publishing page inherits from PublishingLayoutPage, which inherits from the WebPartPage class. In many cases, Publishing pages also contain Web Part zones that the page editor can use to add extra information or functionality to the pages. Because SharePoint 2010 now can handle the versioning of a Web Part’s customization and personalization state, usability of Web Parts in Publishing pages and sites is enhanced compared with previous SharePoint releases. This was a problem in previous SharePoint versions: if you reverted to an old version of a Publishing page, the configuration of the Web Part didn’t change.

Custom Site Pages

Site pages are normally based on one of two classes, both defined in the Microsoft.SharePoint.WebPartPages namespace:

  • WebPartPage A site page containing Web Part zones.
  • WikiEditPage A new type of site page introduced in SharePoint 2010, which contains the new Wiki field, which can host Web Parts. In SharePoint 2010, these pages are sometimes simply called Page (see figure 1.7).
    Figure 1.7. You can use the new Silverlight-based Create dialog box to search for and add new items to your site. Notice the option to download new items and templates from Office.com. If you don’t have Silverlight installed, you’ll see an HTML-based interface instead.

By default, these site pages can’t contain inline server-side code, such as custom logic and events. Assume that you create a new site page in a document library and want to add a submit button that runs some code when clicked. You can’t do this using inline code without changing the security settings of your SharePoint web application. You can lower the security, but I don’t recommend it because that exposes your web application to malicious code. Instead, you have two basic options that work equally well but have different purposes:

  • Create a Web Part— This Web Part will display the button and handle the click event for you.
  • Subclass the site page— Your new class will have the code that handles the click event and the site page ASPX code will define the button.

Using a Web Part for your custom code is the preferred way because you can reuse the logic much more easily. If you add the Web Part as a static Web Part (outside a zone), you can control on which pages the Web Part is available. The easiest way to achieve this is using SharePoint Designer, but that will customize the page (read more about customization below). If you add a Web Part to the page using the web interface to a zone, the editors of that page can move, customize, or even delete the Web Part, but you’ll allow the page to stay in its original state (if it wasn’t already customized).

 

Allowing inline server-side code in a Site page

To allow inline code in your site page, you have to edit the web.config file of the web application to lower the security. Do so by adding a new PageParserPath element to the PageParserPaths element like this:

<PageParserPath
    VirtualPath="/Library/*"
    CompilationMode="Always"
    AllowServerSideScript="true"
    IncludeSubFolders="true" />

Where VirtualPath is the path to the document library or site where you put your site page.

Once you do this, anyone can upload their own code to be executed in the virtual path, so be advised. Enabling inline server-side code isn’t a good practice and you should use this approach only for testing and development purposes.

 

Page Customization

The site pages are stored, just like the Web Part customizations, in the content database of your SharePoint instance. Compared with the application pages, you don’t have to care about replicating changes between the SharePoint servers because the file resides in the database.

This is true in most cases. SharePoint has a mechanism called page customization, previously referred to as ghosting. This technique allows you to store the template of the site page on the disk (“ghost”) and the database keeps a reference to the file on the disk instead. When you customize the page (“unghost”), data is added to the content database and the reference points to the database instead of the file system. The page customization makes SharePoint perform better because it doesn’t have to keep a copy in the database for all provisioned pages—only the ones that the user explicitly customized. For example, the editform.aspx file for a contacts list uses the version stored on the disk for all contacts lists in the farm (unless the page is customized) and saves you a lot of database space and performance. Any updates to a file in the file system will immediately be visible for all noncustomized contacts list edit forms (for example, when you need to make some changes or when you apply a SharePoint service pack). You shouldn’t modify a site page residing in the file system of the SharePoint frontend web servers because it’s difficult to determine if and where this file has been customized and it will likely be difficult to get support if it breaks. Another disadvantage of editing files directly in the file system is that they might be overwritten when you update or upgrade SharePoint.

1.6.3. Master pages

A master page is the foundation of any page in SharePoint ASP.NET sites. A master page defines the basic layout, structure, and functionality of pages and contains placeholders where the pages can host their content. Each time a page is requested by a user, the page is created by replacing the placeholders in the master page with the content from the page, which merges the master page with the requested page.

SharePoint 2010 mainly uses one master page, called v4.master, compared with the previous SharePoint version, which had a separate master page for application pages. You can edit master pages or provide your own, but that’s a completely different topic. The default master page is located in the SharePoint root under the TEMPLATE\GLOBAL folder.

 

Note

SharePoint 2010 contains a completely new master page to support the new user interface and web browser compatibility. If you’ve invested heavily in the SharePoint 2007 UI and want to upgrade your site, it’s good to know that the old master pages are still provided with the SharePoint 2010 upgrade and you can at any time select the interface you want to use: the old one or the brand-new one. Note that, once you switch from the 2007 interface to version 2010, you can’t go back.

 

As a Web Part developer, be aware of a couple of things when working with master pages. The default master page delivered with SharePoint 2010 contains the important Web Part Manager object (SPWebPartManager), so there’s no need to define your own in your site or application pages. It’s defined close to the body tag of the page and has an id of m.

You can’t add Web Part zones to the master page—only to the pages utilizing the master page, but you can add Web Parts directly to a master page. These Web Parts will be available on all pages using the master page and they’ll be static, because they don’t exist in a zone. This also means that the Web Parts can’t be customized using the user interface, for instance, when editing a page. You have to use SharePoint Designer 2010 to customize the Web Parts.

1.7. Summary

This chapter was a brief introduction to the world of Web Parts in SharePoint, and you should now have the basic knowledge to begin building your own Web Parts. SharePoint is a platform that can be used to develop and deploy your custom applications. We walked through the basics of Web Parts in SharePoint 2010, and we introduced the building blocks of pages. Here’s a summary of what you’ve learned so far:

  • Web Parts are one of the building blocks in SharePoint.
  • Web Parts can act alone or together with other Web Parts.
  • The Web Part infrastructure is defined in ASP.NET 2.
  • Web Parts are managed through a Web Part Manager object.
  • Web Parts exist inside or outside of Web Part zones.
  • Pages in SharePoint host the Web Part zones.

For a SharePoint Web Part developer, two tools are especially important: Visual Studio 2010 and SharePoint Designer 2010. The first is used for designing and building Web Parts and the latter for configuring Web Parts, pages, and sites. The rest of this book will cover most of the situations you’ll be facing when building Web Parts, and you should have these tools close at hand.

Remember that you don’t always have to develop your own Web Parts; there are plenty of configurable Web Parts that you can use to create your solutions. But, there are many situations when you need to develop your own custom Web Part to provide a unique functionality that your customer is requesting or to have full control of your application. Developing Web Parts isn’t just about writing a piece of code that’s injected into a SharePoint environment; you need to know how SharePoint uses the Web Parts and how you leverage SharePoint’s features. We’ll continue to explore Web Parts in SharePoint and how to make your Web Parts utilize the platform in the best possible way.