Web Parts and ASP.NET Controls
Extend Server Controls to Work as Web Parts
October 30, 2009
Modular page layouts and personalized content are keyfactors to increase user satisfaction and productivity. If, for example, amanager needs to review a given table of data every morning, the softwareshould be able to serve this data with no frills, and in an easy-to-access way.Getting the requisite information in a timely manner and in the most appropriateformat is essential to saving time and, subsequently, money.
Providing rich content is important, but making contentavailable in a personalizable way adds more value to the solution. Enter theconcept of portals. A portal is an application that results from thecomposition of a number of tailor-made building blocks. The user is solelyresponsible for the final layout of the pages.
Most SharePoint solutions, for example, work according to this pattern; that is, bycomposing ad hoc components named WebParts. In SharePoint, Web Parts are server controls that inherit from a baseclass and require a particular policy (as far as deployment is concerned).
A similar family of components is introduced in ASP.NET2.0 with the goal of making you able to build ASP.NET 2.0 portal-likeapplications. This family of ASP.NET 2.0 controls is also known as Web Parts.More precisely, Web Parts are the tools in ASP.NET 2.0 that make buildingmodular and customizable Web sites easier and even pleasant.
As of today, ASP.NET Web Parts and SharePoint Web Partsare different entities, even though they look related (if not similar). Withthe latest service pack, SharePoint can host ASP.NET 2.0 Web Parts. However, theopposite is not true.
In this article, after explaining the strategic role ofWeb Parts in future releases of Microsoft products, I ll take the plunge intoASP.NET Web Parts and explore the difference between classic server controlsand ASP.NET 2.0 Web Parts.
ASP.NET and SharePoint Convergence
Most ASP.NET and SharePoint developers think that the twoproducts are different things. This is correct, but the common and overlappingarea between the two technologies is significant and must be known. SharePointproducts and related technologies are aimed at empowering collaboration withinan organization between members, partners, and customers. When you build a portalwith SharePoint, in the end you are simply working with one of the possiblepractical applications of the term collaboration. A SharePoint application isa sort of super-framework tightly integrated with ASP.NET but it s not anintegral part of it. ASP.NET 1.1 supplies a run-time environment that can hosta SharePoint application. A SharePoint application reuses most of the ASP.NETplumbing, but customizes and overrides some aspects to pursue its own goals.For example, SharePoint builds pages reading information from a database;ASP.NET 1.1 pages are saved to disk and there s no way for a piece of code toserve pages reading the source from other storage media.
ASP.NET 2.0 comes with a framework and a compilation modelthat has been redesigned to allow other teams to build a newer and richerSharePoint environment just inside ASP.NET. In addition, in ASP.NET 2.0 you llfind a set of classes that developers can use to build portal-like solutionswithout resorting to SharePoint products and the related set of technologies.
Are there any points of contact between SharePoint and theASP.NET portal framework? Sure, Web Parts components. In the end, today sSharePoint Web Parts are ASP.NET controls with an extra layer of code that makethem interact with the SharePoint framework. ASP.NET 2.0 Web Parts are servercontrols that interact with the ASP.NET Web Parts framework to provide abehavior that mimics that of SharePoint documents.
SharePoint and ASP.NET are destined to converge in thefuture, even though the level of the convergence is not clear just yet. What iscertain is that the next version of SharePoint will be entirely based onASP.NET 2.0, and ASP.NET Web Parts will be fully supported by SharePoint. To alarge extent, this already happens today once you install the SharePointService Pack 2. Some of the new features in the ASP.NET compilation model(no-compile pages, parser filters, virtual path providers) have been introducedjust to facilitate and, in some cases, make it happen the porting of theSharePoint engine to ASP.NET 2.0. Web Parts are the next logical step. In thefuture, with the next major release of SharePoint, SharePoint Web Parts andASP.NET Web Parts will be the same thing. But this is not entirely true today.
Building Pages with Web Parts
The screen real estate of a Web Parts page is partitionedamong zones; each zone contains homogeneous parts. There are various types ofzones, and subsequently, parts: Web Parts, Catalog Parts, and Editor Parts. Allzones and their contents are managed by an instance of the WebPartManager class(see Figure 1).
Figure 1: A samplepage using Web Parts.
The zone is a container for parts and provides additionaluser interface elements and functionality for all the parts it contains. AnASP.NET page can contain multiple zones, and each zone can contain one or moreparts.
The page in Figure 1 contains only one zone a Web Partzone filled with two Web Part controls. Controls can be added to a Web Partzone either declaratively or programmatically. In the former case, you listcontrols under the element. Web Parts can also be addedthrough code by populating the WebParts collection property of the WebPartZoneclass. The WebParts property is of type WebPartsCollection.
As previously mentioned, Web Parts are ultimately servercontrols. WebPart is the base class of all content-enabled parts controls usedin ASP.NET pages. WebPart derives from an abstract base class named Part, whichin turn inherits from one of the native ASP.NET server controls (Panel).
A Web Part is designed to show some content through awindow-like user interface. Like a window, it can be moved around and itscontent can be configured to some extent. The Web Parts infrastructure providesdrag-and-drop facilities for moving the control around and changing the pagelayout. The parent zone enriches contained parts with styles and verbs. Verbsindicate special actions such as minimizing, restoring, closing, and editingthe Web Part or connecting the Web Part to other Web Parts in the same zone.
The primary goal of a Web Part control is deliveringinformation to users. The information can be retrieved in a variety of ways,according to the characteristics of both the Web Part and the hostingapplication. In a portal scenario, the Web Part shows through the user spersonalized page some content grabbed over the internal network, such asreports and announcements, or content provided by external Web sites (blogs,news, stock quotes, etc.).
Web Parts as Individual Controls
As mentioned, a Web Part is a server control derived fromthe base class WebPart. This class enriches a classic server control withadditional properties to represent the title and subtitle of the part andavailable verbs. Aside from this, a Web Part is simply a server control hostedin a panel. For this reason, you insert in a Web Part zone any ASP.NET servercontrol from Calendar to AdRotator and from Wizard to a plain, simple Button.
When a control is added to a Web Part zone, it isautomatically wrapped by an instance of the GenericWebPart class if it is not apure Web Parts control; that is, it inherits from the WebPart class. When theAdd method on the WebPartsCollection class is invoked to associate a controlwith a zone, the check is made and a GenericWebPart wrapper is generated (ifappropriate).
The bottom line is that you can put into a Web Part just aboutany server control and be sure that the run-time system will transform it intoa true Web Part. The code below is not much useful to run, but is perfectlylegal from a syntax point of view:
Why should you ever need specific Web Part controls ifregular server controls can be used? One reason is that GenericWebPart can onlybind one control at a time. In other words, when multiple controls arespecified as direct children of the tag, only the firstone is considered. In addition, you cannot use literals, unless you make themserver-side controls:
Hello
If you omit the runat= server attribute, the precedingcontents are ignored. To work around this limitation, you can use customcomposite controls only or, better yet, aggregate and link more controlstogether by creating a user control. However, creating a new specific controlthat derives from the WebPart class gives you the maximum programmatic controlover the behavior of the Web Part.
Web Parts as User Controls
A Web user control allows you to easily group multiplecontrols together and form a monolithic block that can be bound as a Web Part.There s virtually nothing that is required on a Web Part that you cannot dothrough a Web Part. Because the Web Part is wrapped by a generic Web Part, youcan still set Title and Subtitle properties declaratively; at least if youaccept that Visual Studio 2005 complains about missing attributes in the knownschema.
If you need to add some logic behind the properties, youcan implement the IWebPart interface in your user control. To implement aninterface in a user control, you use the @Implements directive or, if thecontrol supports the code-behind model, you implement the interface in thecode-behind class.
Web Parts-specific Controls
A typical Web Part control derives from WebPart and overridesTitle and Subtitle at the very minimum. Figure 2 shows some sample code thatdemonstrates how to override the Title property.
public override string Title{ get { if (String.IsNullOrEmpty(base.Title)) return "AutoRefresh"; return base.Title; } set { base.Title = value; }} Public Overrides Property Title As String Get If String.IsNullOrEmpty(MyBase.Title) Then Return "AutoRefresh" Return MyBase.Title End Get Set (ByVal value as String) MyBase.Title = value End SetEnd Property
Figure 2: How tooverride the Title property.
The control can then add custom properties and make themcustomizable through Web Part editors. To expose a property to the editor, youmust decorate it with two attributes, Personalizable and WebBrowsable, as shownin Figure 3.
[Personalizable][WebBrowsable]public int RefreshRate{ get { return _refreshRate; } set { _refreshRate = value; }} _ _Public Property RefreshRate As Integer Get Return _refreshRate End Get Set (ByVal value as String) refreshRate = value End SetEnd Property
Figure 3: Expose aproperty to the editor by decorating it with the Personalizable andWebBrowsable attributes.
Finally, the Web Part will override RenderContents tocreate its own composite output to render in the page. As long as the contentsare relatively static, you re all set. If you want to give users a way torefresh the contents, you can add a Refresh postback button to the userinterface, and handle the Click event.
However, most of today s browsers support sending requestsover HTTP programmatically, and most of them offer good Dynamic HTML support.So you might want to add automatic update capabilities to your Web Parts byimplementing a script callback mechanism that periodically refreshes the page.The sample code shown in Figure 4 is a Web Part that changes its backgroundcolor every two seconds (configurable value) without refreshing the whole hostpage.
void CreateOutput(HtmlTextWriter writer){ Table t = new Table(); t.ID = "Table1"; t.CopyBaseAttributes(this); t.Width = Unit.Percentage(100); t.BackColor = Color.Blue; TableRow row = new TableRow(); t.Rows.Add(row); TableCell c = new TableCell(); c.Text = " "; row.Cells.Add(c); // Add auto-update capabilities if (RefreshRate > 0) { if (!Page.ClientScript.IsStartupScriptRegistered( this.GetType(), "AutoRefresh")) { string js = GetRefreshScript(); Page.ClientScript.RegisterStartupScript( this.GetType(), "AutoRefresh", js, true); } } // Render out t.RenderControl(writer);} Sub CreateOutput(ByVal writer As tmlTextWriter) Dim t As New Table t.ID = "Table1" t.CopyBaseAttributes(Me) t.Width = Unit.Percentage(100) t.BackColor = Color.Blue Dim row As New TableRow t.Rows.Add(row) Dim c As New TableCell c.Text = " " row.Cells.Add(c) ' Add auto-update capabilities If RefreshRate > 0 Then If Not Page.ClientScript.IsStartupScriptRegistered( _ Me.GetType(), "AutoRefresh") Then Dim js As String = GetRefreshScript() Page.ClientScript.RegisterStartupScript( Me.GetType(), "AutoRefresh", js, true) End If End If ' Render out t.RenderControl(writer)End Sub
Figure 4: Renderingan auto-update Web Part.
The RenderContents method adds some script (see Figure 5) thatcalls back the page to obtain the new, randomly generated, background color.
Figure 5: Scriptthat calls back the page to obtain the new, randomly generated, backgroundcolor.
The first function invoked upon page loading isAutoRefresh. The function makes a callback to the server to refresh thebackground of the Web Part and then sets a timeout of two seconds. When thetimeout expires, the AutoRefresh is called again to refresh the background andstart another timeout. The callback posts to the same .aspx page that containsthe Web Part and invokes a method on the ICallbackEventHandler interfaceimplemented by the Web Part itself. This code is shown in Figure 6.
private string _results;void ICallbackEventHandler.RaiseCallbackEvent(string argument){ _rnd = new Random(); int r = _rnd.Next(0, 255); int g = _rnd.Next(0, 255); int b = _rnd.Next(0, 255); _results = String.Format("#{0:x}{1:x}{2:x}", r, g, b); return;}string ICallbackEventHandler.GetCallbackResult(){ return _results;} Private results As StringSub RaiseCallbackEvent(ByVal argument As String) _ Implements ICallbackEventHandler.RaiseCallbackEvent rnd = New Random() Dim r As Integer = rnd.Next(0, 255) Dim g As Integer = rnd.Next(0, 255) Dim b As Integer = rnd.Next(0, 255) results = String.Format("#{0:x}{1:x}{2:x}", r, g, b) ReturnEnd SubFunction GetCallbackResult() As String _ Implements ICallbackEventHandler.GetCallbackResult Return resultsEnd Function
Figure 6: Thecallback posts to the same .aspx page that contains the Web Part and invokes amethod on the ICallbackEventHandler interface implemented by the Web Partitself.
The code generates a new RGB color and returns it as anHTML color string. On the client, the UpdateColor script function is used torefresh the background of the Web Part using the page object model. Figure 7shows the page in action.
Figure 7: An auto-update Web Partcontrol.
Conclusion
You don t need to install SharePoint and learn a newprogramming and deployment model to build portal-like applications in ASP.NET2.0. However, ASP.NET and SharePoint remain two distinct things that are goingto be even more integrated in the future.
As a matter of fact, ASP.NET Web Parts are components thatcan be used on the current version of SharePoint as long as you install the ServicePack 2. With the next version of SharePoint, though, ASP.NET Web Parts willbecome the only type of Web Parts you can use.
Web Parts are simply plain server controls with someadditional capabilities. The ASP.NET infrastructure normally can transform anyserver control (including user controls) in a Web Part. A nice touch to WebParts (no matter if they re native Web Parts or adapted from user controls) isadding auto-update capabilities. In practice, the Web Parts injects in the hostpage some script code that periodically posts back to the server, grabs somefresh data, and updates the user interface through Dynamic HTML. No full pagerefresh occurs, and the user is served a highly responsive page that deliversup-to-date information.
The source code accompanyingthis article is available for download.
About the Author
You May Also Like