Skip navigation

Web Parts and ASP.NET Controls

Extend Server Controls to Work as Web Parts

Modular page layouts and personalized content are key factors to increase user satisfaction and productivity. If, for example, a manager needs to review a given table of data every morning, the software should 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 appropriate format is essential to saving time and, subsequently, money.

Providing rich content is important, but making content available in a personalizable way adds more value to the solution. Enter the concept of portals. A portal is an application that results from the composition of a number of tailor-made building blocks. The user is solely responsible for the final layout of the pages.

Most SharePoint solutions, for example,  work according to this pattern; that is, by composing ad hoc components named Web Parts. In SharePoint, Web Parts are server controls that inherit from a base class and require a particular policy (as far as deployment is concerned).

A similar family of components is introduced in ASP.NET 2.0 with the goal of making you able to build ASP.NET 2.0 portal-like applications. 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 building modular and customizable Web sites easier and even pleasant.

As of today, ASP.NET Web Parts and SharePoint Web Parts are different entities, even though they look related (if not similar). With the latest service pack, SharePoint can host ASP.NET 2.0 Web Parts. However, the opposite is not true.

In this article, after explaining the strategic role of Web Parts in future releases of Microsoft products, I ll take the plunge into ASP.NET Web Parts and explore the difference between classic server controls and ASP.NET 2.0 Web Parts.

 

ASP.NET and SharePoint Convergence

Most ASP.NET and SharePoint developers think that the two products are different things. This is correct, but the common and overlapping area between the two technologies is significant and must be known. SharePoint products and related technologies are aimed at empowering collaboration within an organization between members, partners, and customers. When you build a portal with SharePoint, in the end you are simply working with one of the possible practical applications of the term collaboration. A SharePoint application is a sort of super-framework tightly integrated with ASP.NET but it s not an integral part of it. ASP.NET 1.1 supplies a run-time environment that can host a SharePoint application. A SharePoint application reuses most of the ASP.NET plumbing, 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 to serve pages reading the source from other storage media.

ASP.NET 2.0 comes with a framework and a compilation model that has been redesigned to allow other teams to build a newer and richer SharePoint environment just inside ASP.NET. In addition, in ASP.NET 2.0 you ll find a set of classes 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, Web Parts components. In the end, today s SharePoint Web Parts are ASP.NET controls with an extra layer of code that make them interact with the SharePoint framework. ASP.NET 2.0 Web Parts are server controls that interact with the ASP.NET Web Parts framework to provide a behavior that mimics that of SharePoint documents.

SharePoint and ASP.NET are destined to converge in the future, even though the level of the convergence is not clear just yet. What is certain is that the next version of SharePoint will be entirely based on ASP.NET 2.0, and ASP.NET Web Parts will be fully supported by SharePoint. To a large extent, this already happens today once you install the SharePoint Service Pack 2. Some of the new features in the ASP.NET compilation model (no-compile pages, parser filters, virtual path providers) have been introduced just to facilitate and, in some cases, make it happen the porting of the SharePoint engine to ASP.NET 2.0. Web Parts are the next logical step. In the future, with the next major release of SharePoint, SharePoint Web Parts and ASP.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 partitioned among zones; each zone contains homogeneous parts. There are various types of zones, and subsequently, parts: Web Parts, Catalog Parts, and Editor Parts. All zones and their contents are managed by an instance of the WebPartManager class (see Figure 1).



 

 

 

 

 

     

     

 

  

Figure 1: A sample page using Web Parts.

 

The zone is a container for parts and provides additional user interface elements and functionality for all the parts it contains. An ASP.NET page can contain multiple zones, and each zone can contain one or more parts.

The page in Figure 1 contains only one zone a Web Part zone filled with two Web Part controls. Controls can be added to a Web Part zone either declaratively or programmatically. In the former case, you list controls under the element. Web Parts can also be added through code by populating the WebParts collection property of the WebPartZone class. The WebParts property is of type WebPartsCollection.

As previously mentioned, Web Parts are ultimately server controls. WebPart is the base class of all content-enabled parts controls used in ASP.NET pages. WebPart derives from an abstract base class named Part, which in turn inherits from one of the native ASP.NET server controls (Panel).

A Web Part is designed to show some content through a window-like user interface. Like a window, it can be moved around and its content can be configured to some extent. The Web Parts infrastructure provides drag-and-drop facilities for moving the control around and changing the page layout. The parent zone enriches contained parts with styles and verbs. Verbs indicate special actions such as minimizing, restoring, closing, and editing the Web Part or connecting the Web Part to other Web Parts in the same zone.

The primary goal of a Web Part control is delivering information to users. The information can be retrieved in a variety of ways, according to the characteristics of both the Web Part and the hosting application. In a portal scenario, the Web Part shows through the user s personalized page some content grabbed over the internal network, such as reports 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 from the base class WebPart. This class enriches a classic server control with additional properties to represent the title and subtitle of the part and available verbs. Aside from this, a Web Part is simply a server control hosted in a panel. For this reason, you insert in a Web Part zone any ASP.NET server control from Calendar to AdRotator and from Wizard to a plain, simple Button.

When a control is added to a Web Part zone, it is automatically wrapped by an instance of the GenericWebPart class if it is not a pure Web Parts control; that is, it inherits from the WebPart class. When the Add method on the WebPartsCollection class is invoked to associate a control with a zone, the check is made and a GenericWebPart wrapper is generated (if appropriate).

The bottom line is that you can put into a Web Part just about any server control and be sure that the run-time system will transform it into a true Web Part. The code below is not much useful to run, but is perfectly legal from a syntax point of view:



  

 

Why should you ever need specific Web Part controls if regular server controls can be used? One reason is that GenericWebPart can only bind one control at a time. In other words, when multiple controls are specified as direct children of the tag, only the first one is considered. In addition, you cannot use literals, unless you make them server-side controls:



  

Hello

If you omit the runat= server attribute, the preceding contents are ignored. To work around this limitation, you can use custom composite controls only or, better yet, aggregate and link more controls together by creating a user control. However, creating a new specific control that derives from the WebPart class gives you the maximum programmatic control over the behavior of the Web Part.

 

Web Parts as User Controls

A Web user control allows you to easily group multiple controls 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 do through a Web Part. Because the Web Part is wrapped by a generic Web Part, you can still set Title and Subtitle properties declaratively; at least if you accept that Visual Studio 2005 complains about missing attributes in the known schema.

If you need to add some logic behind the properties, you can implement the IWebPart interface in your user control. To implement an interface in a user control, you use the @Implements directive or, if the control supports the code-behind model, you implement the interface in the code-behind class.

 

Web Parts-specific Controls

A typical Web Part control derives from WebPart and overrides Title and Subtitle at the very minimum. Figure 2 shows some sample code that demonstrates 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 Set

End Property

Figure 2: How to override the Title property.

The control can then add custom properties and make them customizable through Web Part editors. To expose a property to the editor, you must decorate it with two attributes, Personalizable and WebBrowsable, as shown in 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 Set

End Property

Figure 3: Expose a property to the editor by decorating it with the Personalizable and WebBrowsable attributes.

Finally, the Web Part will override RenderContents to create its own composite output to render in the page. As long as the contents are relatively static, you re all set. If you want to give users a way to refresh the contents, you can add a Refresh postback button to the user interface, and handle the Click event.

However, most of today s browsers support sending requests over HTTP programmatically, and most of them offer good Dynamic HTML support. So you might want to add automatic update capabilities to your Web Parts by implementing a script callback mechanism that periodically refreshes the page. The sample code shown in Figure 4 is a Web Part that changes its background color every two seconds (configurable value) without refreshing the whole host page.

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: Rendering an auto-update Web Part.

The RenderContents method adds some script (see Figure 5) that calls back the page to obtain the new, randomly generated, background color.

 

Figure 5: Script that calls back the page to obtain the new, randomly generated, background color.

The first function invoked upon page loading is AutoRefresh. The function makes a callback to the server to refresh the background of the Web Part and then sets a timeout of two seconds. When the timeout expires, the AutoRefresh is called again to refresh the background and start another timeout. The callback posts to the same .aspx page that contains the Web Part and invokes a method on the ICallbackEventHandler interface implemented 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 String

Sub 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)

  Return

End Sub

Function GetCallbackResult() As String _

   Implements ICallbackEventHandler.GetCallbackResult

   Return results

End Function

Figure 6: The callback posts to the same .aspx page that contains the Web Part and invokes a method on the ICallbackEventHandler interface implemented by the Web Part itself.

The code generates a new RGB color and returns it as an HTML color string. On the client, the UpdateColor script function is used to refresh the background of the Web Part using the page object model. Figure 7 shows the page in action.


Figure 7: An auto-update Web Part control.

 

Conclusion

You don t need to install SharePoint and learn a new programming and deployment model to build portal-like applications in ASP.NET 2.0. However, ASP.NET and SharePoint remain two distinct things that are going to be even more integrated in the future.

As a matter of fact, ASP.NET Web Parts are components that can be used on the current version of SharePoint as long as you install the Service Pack 2. With the next version of SharePoint, though, ASP.NET Web Parts will become the only type of Web Parts you can use.

Web Parts are simply plain server controls with some additional capabilities. The ASP.NET infrastructure normally can transform any server control (including user controls) in a Web Part. A nice touch to Web Parts (no matter if they re native Web Parts or adapted from user controls) is adding auto-update capabilities. In practice, the Web Parts injects in the host page some script code that periodically posts back to the server, grabs some fresh data, and updates the user interface through Dynamic HTML. No full page refresh occurs, and the user is served a highly responsive page that delivers up-to-date information.

The source code accompanying this article is available for download.

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish