Sponsored Links


Resources

.NET Research Library
Get .NET related white papers, case studies and webcasts

WebParts - From Sharepoint to ASP.NET 2.0WebParts - From Sharepoint to ASP.NET 2.0WebParts - From Sharepoint to ASP.NET 2.0 Discuss DiscussDiscuss Printer friendly Printer friendlyPrinter friendly
WebParts - From Sharepoint to ASP.NET 2.0

March 8, 2005

“Time is money” an old and wise proverb says, and getting the information you need timely and at-your-fingertips is key to save time and subsequently money. Today’s Web sites have a super-huge quantity of information to offer, but presenting too much content on a single page only leads to confusion. Modular page layouts and personalized contents are the key to increase user satisfaction and productivity. If a manager needs to review a given set of data each and every morning, you should be able to serve her just those data with no frills, and in an-easy-to-access way. That’s why Internet portals exist.

In the Windows world, SharePoint products and technologies simplify and support various forms of collaboration between partners within a company or an organization. The pages of a Web site based on SharePoint can contain special components named WebParts which are specifically designed to provide personalized and customizable windows of information to users. In the end, Web Parts are ASP.NET controls with an extra layer of code that make them interact with the SharePoint framework. So far so good. What about Whidbey and the next version of the .NET Framework?

ASP.NET 2.0 comes with a built-in portal framework that brings two significant benefits to the table. First, it dramatically reduces the investment for building ASP.NET portal solutions. Second, it provides a consistent model for building ASP.NET-based portals.

What’s the difference between SharePoint technologies and ASP.NET 2.0? They’re different types of animal with an overlapping area. SharePoint products (and related technologies) are aimed at empowering collaboration within an organization between members and their partners and customers. In this context, a portal is just one of the possible practical applications of the term “collaboration”. ASP.NET 2.0 supplies a framework that developers can use to build portal-like solutions without resorting to SharePoint products and the related set of technologies. Are there any points of contact between SharePoint and the ASP.NET portal framework? Sure, there are and their name is WebParts components.

Present and Future of WebParts

As of today, with Windows SharePoint Services (WSS) and SharePoint Portal Server (SPS) 2003 available, a WebPart is little more than a plain ASP.NET server control. More precisely, it is a custom server control built starting from a base class defined in one of the SharePoint constituent libraries. What’s a WebPart in ASP.NET 2.0? It’s a server control (possibly, a user-defined control) that can optionally implement a particular interface. The definition seems to be the same, and to a large extent it is. So are

ASP.NET WebParts and SharePoint WebParts equivalent? They’re not equivalent and not interchangeable, but they’re definitely similar from a conceptual point of view. In the long run, it is foreseeable that there will be some form of convergence between ASP.NET and SharePoint WebParts. However, this won’t certainly happen until the next generation of SharePoint products will be out. In the future, it is expected that the ASP.NET WebParts framework will serve as the common platform for portal solutions built across Microsoft products.

If you’re a SharePoint consultant, and know a lot about WebParts, you’ll be pleased to see that you’ll be able to reuse much of your skills while building portal solutions with ASP.NET. Likewise, if you’re an ASP.NET developer building WebParts doesn’t represent a mission impossible. If you then already started practicing with ASP.NET 2.0 WebParts and need to get back to SharePoint WebParts everything risks to look like a deja-vu. In this article, I’ll design a realistic component and build it as a SharePoint WebPart. Next, I’ll build the same component as an ASP.NET 2.0 WebPart.

Building WebParts Today

Building a SharePoint 2003 WebPart is not really different from building an ASP.NET custom control. To start out, you create a Web Control Library project in Visual Studio .NET, add a reference to the SharePoint library, and begin coding. You can save some time and work in slightly more comfortable environment if you first install the SharePoint 2003 template for Visual Studio .NET 2003. You can get it from the following URL. The component adds a new project item to the Visual Studio .NET menu and, once selected, prepares a Web control ready to compile as an empty SharePoint WebPart. Interestingly enough, the new project template adds automatically both a DWP file and a manifest.

The WebPart I’m going to build mimics the behavior of some of the built-in MSNBC Web Parts. These WebParts connect to the MSNBC Web site and download live data regarding weather, business or sport news, stock quotes and so forth. The sample WebPart here will connect to a remote server and download book news. For the purpose of this example, I’ll use the Amazon Web service. Note though that the search engine is totally insulated and can be replaced with limited efforts. The WebParts class is declared as follows:

[XmlRoot(Namespace="AmazonBookNews")]
public class BookFinder : Microsoft.SharePoint.WebPartPages.WebPart
{
   :
}

The WebPart I have in mind works interactively by letting the user enter the author name and click to get details of the books he or she wrote. An alternative approach might entail adding one or more persistent and customizable properties to hold the author name and the desired level of detail.

The graphical layout of the WebPart is entirely defined overriding the control’s CreateChildControls method. Why CreateChildControls? Because any realistic WebPart controls are ASP.NET composite controls. A composite control groups together two or more constituent controls and its user interface reuses the functionality of existing controls. Rendering the user interface of a control is normally faster than adding controls to an object hierarchy and have the system iterate through and generate markup. If you opt for the first option, then use the method RenderWebPart; if you go for the second choice, then CreateChildControls is the perfect fit. CreateChildControls is the internal method where you build the hierarchy of child controls, by instantiating them and adding instances to the Controls collection of the WebPart. What’s the benefit of CreateChildControls?

Imagine you have to render a button. Writing out the markup to style the control is relatively easy; but what about the client-side script needed to trigger postback events? I’m not saying this is impossible to do—it’s just boring and error-prone. By using CreateChildControls you delegate boring tasks to well-tested and system provided code.

The interface of the sample BookFinder WebPart looks like in Figure 1.

FIGURE 1—The BookFinder WebPart in action

As you can see, the interface includes a textbox, a push button, a checkbox, and a list of templated items. If you look at the code in Listing 1, you’ll see that there’s a little more.

private void CreateMainFrame()
{
	// Create the surrounding DIV
	Panel div = new Panel();
	div.Style["margin"] = "5";
	Controls.Add(div);

	// Add a message
	AddHeaderMessage(div);

	// Add the textbox
	AddTextBox(div);

	// Add a separator
	AddSeparator(div);

	// Add the button to load information
	AddButton(div);

	// Add a separator
	AddSeparator(div);
	AddSeparator(div);

	// Add the checkbox
	AddCheckBox(div);

	// Add the HR ruler
	AddRuler(div);

	// Add the child scrollable panel
	AddBookPanel(div);

	// Add some credits
	AddCredits();
	return;
}
LISTING 1--Building the infrastructure of the WebPart component

Each of the AddXXX methods creates one or more ASP.NET controls. Can you imagine the messy code you are called to manage if you drop composition (CreateChildControls) in favor of manual rendering (RenderWebPart)?

The most prominent part of the control is the little template that renders book cover and detail information. How would you code that? The Repeater control is the perfect fit. To specify header and data templates you can use instances of classes that implement the ITemplate interface. Here’s an example:

_presenter = new Repeater();
bookPanel.Controls.Add(_presenter);
_presenter.HeaderTemplate = new BookFinderHeaderTemplate();
_presenter.FooterTemplate = new BookFinderFooterTemplate();
_presenter.ItemTemplate = new BookFinderItemTemplate();
_presenter.DataSource = view;
_presenter.DataBind();

To get the data source for the Repeater, you invoke the Amazon Web service and obtain a free-form XML string that the ReadXml method of the DataSet class can work on. Once the data is in the DataSet, you can easily create a proper view and attach it to the Repeater. The table that stores information about each book has fields for the URL of the cover picture, manufacturer, title, sales rank, average customer rating, and more. For more details, you can download the source code from here. Note that in order to use the Amazon Web service, you need to register with the site and get your own developer token. See details at http://www.amazon.com/gp/aws/landing.html. This article’s companion code contains a placeholder where a personal dev-token is needed.

The WebPart at Work

Regardless you successfully compiled and deployed the WebPart, a boring error may show up when you actually use it to build a page. The error message has to do with missing Web permissions. No matter the WebPart is correctly marked as a safe control, it seems not granted required permissions to make calls over the Web. What’s up? Let’s step back and take a look at the code that downloads data from the Amazon Web site.

The code programmatically composes the URL and connects to download some XML data.

WebRequest req = WebRequest.Create(url);
WebResponse result = req.GetResponse();
Stream receiveStream = result.GetResponseStream();
StreamReader rs = new StreamReader(receiveStream);
response = rs.ReadToEnd();
rs.Close();

Default security constraints prohibit WebParts running in the Bin folder of the site from doing that. You should either avoid similar code or increase the trust level up to High. The simplest thing you can do in order to run the sample code is editing the web.config file and increase the trust level of all WebParts. More wisely, you minimize the surface for an attack by placing the specific assembly for which you need higher permissions in the GAC (automatic full trust) or creating a custom policy file. As a margin note, consider that you run into the same problem even if you import the WSDL of the Web service and build a call through that syntax and object model. This article explains the security topic as far as calling Web services is concerned.

WebParts in ASP.NET 2.0

Just as SharePoint WebParts represent the building blocks of pages in a SharePoint-powered Web site, ASP.NET Web Parts provide an infrastructure for building sites that enable users to select and receive only the content they want. In both cases, Web Parts are container components that aggregate different types of content and are particularly useful for creating portal pages. Aside from a bunch of implementation details, WebParts are conceptually the same type of animal in SharePoint and ASP.NET 2.0. As mentioned, they cannot be used interchangeably yet, but this is likely to be just the next step in the evolution of SharePoint technologies.

Let’s see what it takes to create the same book finder WebPart in ASP.NET 2.0. You’ll be pleased to see that under a different set of façade objects and properties, most of the skills you may have matured building SharePoint WebParts are valid and helpful.

From the developer’s perspective, an ASP.NET 2.0 Web Part component is a sort of smart Panel control. Like a panel, a WebPart can contain any valid ASP.NET content. The ASP.NET’s WebPart class is actually derived from the Panel class. What makes the Web Part more powerful than a simple panel is the support it gets from the WebPart manager (represented by the aptly named WebPartManager control) and the extra visual elements it renders. The layout and system features of an ASP.NET Web Part mimic those of a SharePoint WebPart. It has a caption bar with a title, as well as links to common verbs such as minimize, close, and restore.

Introducing the ASP.NET Portal Framework

The WebPart control is central element in the WebParts infrastructure, but it is not the only one. A page employing WebParts uses several components from the Portal Framework, each performing a particular function. The table below details these components.

Component

Description

WebPartManager

The component that manages all WebParts on a page. It has no user interface and is invisible at runtime.

WebPart

Contains the actual content presented to the user. Note that WebPart is an abstract class; you have to create your own WebPart controls either through inheritance or user controls.

WebPartZone

Wraps one or more WebPart controls and provides the overall layout for the WebPart controls it contains. A page can contain one or more zones.

CatalogPart

The base class for catalog WebPart controls that present a list of available WebParts to users. Derived classes are ImportCatalogPart, DeclarativeCatalogPart, and PageCatalogPart.

CatalogZone

A container for CatalogPart controls.

ConnectionsZone

A container for the connections defined between any pair of WebParts found in the page

EditorPart

The base class for all editing controls that allow modifications to WebParts. An editor part presents its own user interface to let users set properties.

EditorZone

A container for EditorPart controls.

TABLE 1—Components of the ASP.NET Portal Framework

Aside from the WebPartManager class, the Web Parts infrastructure is made up of three types of components, known as parts: Web parts, catalog parts, and editor parts. WebPart components define the content to show; editors let users edit the structure and the settings of a particular WebPart; finally, the list of available WebParts is provided by a catalog component. The following code shows how to write an ASP.NET 2.0 page that uses WebPart controls.

<%@ register tagprefix="x" tagname="News" src="News.ascx" %>
<%@ register tagprefix="x" tagname="Favorites" src="Favorites.ascx" %>
:
<asp:WebPartManager ID="WebMan" runat="server" />
<asp:WebPartZone ID="WebPartZone1" runat="server"
      HeaderText="This is Zone #1">
    <ZoneTemplate>
        <x:News runat="server" id="News" />
        <x:Favorites runat="server" id="Favs" />
    </ZoneTemplate>
</asp:WebPartZone>

Each page must contain a WebPartManager control and one or more WebPart zones. In turn, each WebPart zone group one or more WebParts in its ZoneTemplate area. ASP.NET pages support two types of WebParts—classic user controls (ASCX files) and ad hoc WebPart custom controls.

To employ user controls in SharePoint WebParts, you need a specialized wrapper component like SmartPart to create a dynamic instance of the user control and add it to the body of the outer WebPart. In ASP.NET 2.0, the GenericWebPart control provides the same behavior and in a hidden way. As the code snippet above demonstrates, you’re simply required to drop user controls to a WebPart zone and the ASP.NET runtime will take care of wrapping any ASCX file in a generic WebPart wrapper. In the preceding code, x:News and x:Favorites are ASCX files.

The second type of ASP.NET WebPart component is created in much the same way you do with SharePoint WebParts—derive a new control from a particular base class and override a few methods.

public class BookFinderWebPart : WebPart
{
  :
}

The WebPart base class is defined in the System.Web.UI.WebControls.WebParts namespace. You can take nearly all the internal code written for the SharePoint BookFinder part and add it to the new ASP.NET control—it just works.

In ASP.NET 2.0, user controls employed as WebParts may optionally implement the IWebPart interface to expose, and let users customize, extra properties specific of WebParts such as caption, icon, catalog icon.

WebParts public properties can be edited through an editor part that you can place wherever you like in the host page via the EditorPart control. For a property to appear in the editor, you must mark it with the WebBrowsable and Personalizable attributes, as below.

[Personalizable(true), WebBrowsable(true)]
public int EmployeeID
{
  get { return _empID; }
  set { _empID = value; }
}

Property values are persisted through the ASP.NET personalization provider and can leverage a variety of storage media and formats. These two attributes are equivalent to SharePoint’s Browsable and WebStorage attributes.

Finally, ASP.NET WebParts are connectable like SharePoint WebParts. I’ll cover connectable WebParts from both perspectives in a future article.

The Bottom Line

The ASP.NET 2.0 Portal Framework provides a simple and familiar way for ASP.NET developers to create modular Web applications that support end user personalization. A Web site built in this way tends to look a lot alike a SharePoint’s site. Users can build their views of the information by composing WebParts and dragging and dropping them around. An ASP.NET 2.0 portal is different from a SharePoint portal because radically different is the surrounding runtime environment—Windows 2003 SharePoint Services vs. ASP.NET HTTP runtime. In spite of this, constituent components—the WebParts—are conceptually similar, though incompatible as of today.

The great news is the similarity works in both ways. You can easily reuse your SharePoint skills to build ASP.NET portals and a good grasp of ASP.NET WebParts greatly smooths your landing in the SharePoint territories. This said, ASP.NET and SharePoint remain different products and require a different skillset to be fully understood and properly leveraged.

Future Foreseeable Convergence

If you’re a SharePoint consultant, or invested a lot in the current version of SharePoint, is the advent of ASP.NET WebParts a good or bad news? And vice versa, if you have significant ASP.NET skills (especially in control development), does the future open up a whole new world of job opportunities in the SharePoint’s land?

Although this article has been written before the release of the Whidbey’s Beta 2—the build announced as feature-complete—I believe that a few quick considerations can be made regarding the future of ASP.NET WebParts and SharePoint products.

  • It is rumored that the next version of SharePoint products (both Windows SharePoint Services and SharePoint Portal Server) will entirely be built on the ASP.NET WebParts framework;
  • Today’s SharePoint 2.0 WebParts will continue work in the next version of SharePoint, thus preserving your today’s investments;
  • ASP.NET WebParts will work in the next version of SharePoint;
  • The next availability of an update to SharePoint 2.0 to support ASP.NET 2.0 WebParts seems not to be a far-fetched idea either;

The core code of SharePoint WebParts can be easily ported to ASP.NET WebParts. It goes without saying that the more platform-specific features you use, the more work is required to adapt controls. However, conceptually speaking SharePoint and ASP.NET WebParts support a nearly identical set of features so that mapping one to the other doesn’t pose insurmountable problems.

Authors

Dino Esposito is a trainer and consultant for Wintellect based in Rome, Italy. He runs the Cutting Edge column for MSDN Magazine and is a regular contributor to MSDN News and SQL Server Magazine. Before becoming a full-time author, a full-time consultant and a full-time trainer, Dino was a full-time employee and worked day and night for Andersen Consulting focusing on the very first real-world implementations of DNA systems. Dino also has extensive experience developing commercial Windows-based software, especially for the photography world, and was part of the team who designed and realized one of the first European image online databanks. To get in touch, just write to dinoe@wintellect.com. To meet in person, just attend leading conferences such as Microsoft TechEd, VSLive!, VS DevCon, WinSummit or Wrox WebDev Conference.

News | Blogs | Discussions | Tech talks | White Papers | Downloads | Articles | Media kit | About
All Content Copyright ©2007 TheServerSide Privacy Policy
Site Map