October 31, 2003 12:10 AM

Meet the Web Part Framework

Create Web apps easily with these powerful new ASP.NET controls.
DevConnections
Rating: (0)

asp:feature

LANGUAGE: C#

ASP.NET VERSIONS:2.0

 

Meet the Web Part Framework

Create Web apps easily with these powerful new ASP.NETcontrols.

 

 

Most Web sites display the exactsame content to everyone regardless of the needs and interests of the peoplevisiting them. For example, if both you and I surf to the home page of the NewYork Times Web site, we'll both see exactly the same thing. This is trueeven if the only reason that I visit the New York Times site is to seethe latest movie reviews and the only reason that you visit it is to see thelatest football scores. Wouldn't it be nice if both you and I could get exactlywhat we want when we go to the same home page?

 

ASP.NET 2.0 includes a new set ofcontrols, called Web Parts, that are designed to address this very problem. WebParts are all about personalization. When a Web page is built using them,anyone who views that page can modify its content and layout. If you have everpersonalized the MSN or Yahoo! home page, then you're already familiar with theidea behind Web Parts (see Figure 1).

 


Figure1. You can personalize the MSNhome page so that it displays only the content that interests you.

 

Industry experts predict there willbe a healthy market for third-party custom Web Part controls. This bodes wellfor you, given developers can potentially build new Web applications simply byselecting controls out of a catalog of preexisting Web Parts. You'll have thecapabilities to build a Web application the same way you build a laptop computercurrently on http://www.dell.com - bybundling preexisting components together.

 

In this article, I'll introduce youto the ASP.NET 2.0 Web Parts Framework. You'll learn how to build a simplecompany intranet portal and enable users to personalize the portal by takingadvantage of Web Parts. I'll walk you through creating the Northwind portalpage - an internal Web site used by the employees of the Northwind Traders Co.- as an example.

 

Create Pages WithWeb Parts

When designing a page with WebParts, you must start by defining the Web Parts it will contain. There arethree basic ways you can create a Web Part: You can use the ContentWebPartControl, create a Web User Control, or create a Custom Control. The easiest wayis to use the ContentWebPart Control. You can wrap any type of content that youplease within a ContentWebPart template, then treat that content as a Web Part.For example, this Web Part simply displays the static text "Hello World!":

 

<asp:ContentWebPartid="HelloPart" runat="Server">

  <ContentTemplate>

    Hello World!

  </ContentTemplate>

</asp:ContentWebPart>

 

Notice that the ContentWebPart is atemplated control. So, you place the text "Hello World" inside theContentTemplate template to display it. Also notice that we've provided ourContentWebPart with an ID. Unlike many of the controls in ASP.NET 1.0, theContentWebPart requires a unique ID or you'll get an exception.

 

ContentWebParts are very easy tocreate. However, they have some significant disadvantages. First, when youcreate a Web Part with a ContentWebPart, you cannot use the same Web Part onmultiple pages (without doing a copy and paste of the code). Second, you cannoteasily add application logic to a ContentWebPart. A ContentWebPart is bestsuited for displaying static text or the output of a simple control. (In fact,because of these disadvantages, the ContentWebPart Control might not beincluded in the final release of the ASP.NET 2.0 Framework.)

 

Normally, you'll create Web Partsby creating Web User Controls. Web User Controls do not have the twoshortcomings I just mentioned. When you create a Web Part with a Web UserControl, you can reuse the same Web Part across multiple pages. Furthermore,you can create very complicated Web Parts that contain significant applicationlogic. For example, you can create a Web Part that displays random quotationsby saving this code to a file named Quotes.ascx:

 

<%@ Control Language="C#"%>

<Script runat="Server">

 

  void Page_Load() {

    ArrayList colQuotes = new ArrayList();

    colQuotes.Add( "Early to bed, early to rise!" );

    colQuotes.Add( "Look before you leap!" );

    lblQuote.Text = (string)colQuotes

      [ new Random().Next(2) ];

  }

 

</Script>

 

<asp:Label id="lblQuote"Runat="Server"/>

 

Notice that the Quotes Web Part isnothing more than a standard Web User Control. The Web User Control randomlydisplays one quotation from an ArrayList of quotations whenever it's loaded.

 

The final option for creating WebParts is to create a custom Web Control. This is appealing when you need tohide the source code for your Web Part. For example, you might want to create aWeb Part that displays news headlines. (You could use a Web Service in your WebPart to retrieve the latest news headlines from a central news serverperiodically.) Furthermore, you might want to sell this control to companies sothey can display news headlines on their Web site home pages. In this case,you'll want to hide the source code and create the Web Part by creating a customWeb control. For example, you can use this code to create a custom Web Partthat displays the news item "Rain storm in Seattle!":

 

using System.Web.UI;

using System.Web.UI.WebControls;

 

public class NewsWebPart : WebPart {

 

  protected override void RenderContents

    (HtmlTextWriter writer) {

    writer.Write( "Rain storm in Seattle!" );

  }

 

}

 

Notice that you create a custom WebPart by deriving from the base WebPart class. After you've derived your controlfrom the base WebPart class, you can build your control exactly the same wayyou would create any other custom Web Control. In this case, we override theRenderContents method to display the single news item.

 

Create Portal WebParts

To keep things simple, we'll createthree Web Parts for our Northwind intranet portal page. MotivationWebPartdisplays different motivational messages at different times of the day,ProductsWebPart displays a list of available products, andEmployeeLookupWebPart contains a form that enables you to look up an employee'sphone extension when you provide the employee's last name.

 

We'll create all three Web Parts bycreating Web User Controls (files with an ASEX extension). Furthermore, we'lltake advantage of the sample data included with the Microsoft SQL ServerNorthwind database, using it with our Web Parts.

 

We'll start by creating theMotivationWebPart. This Web Part displays the time and different motivationalmessages depending on the hour (see Figure 2):

 

<%@ Control Language="C#"%>

<Script runat="Server">

  void Page_Load() {

    int hour = DateTime.Now.Hour;

    lblMotivate.Text = DateTime.Now.ToString("t");

    if (hour < 9)

      lblMotivate.Text += " - Go back to sleep!";

    else if (hour < 13)

      lblMotivate.Text += " - Almost time for lunch!";

    else if (hour < 17)

      lblMotivate.Text += " - Almost time to go home!";

    else

      lblMotivate.Text += " - Go home!";

  }

</Script>

<asp:Label id="lblMotivate"Font-Name="Comic Sans MS"

  Runat="Server" />

 


Figure 2. The Motivation Web Partdisplays the time and a motivational message.

 

The ProductsWebPart is a littlemore complicated. It displays a list of the 10 most expensive products theNorthwind Trading Co. sells (see Figure 3):

 

<%@ Control %>

 

<asp:GridView

  id="MyGridView"

  DataSourceId="Northwind"

  HeaderStyle-BackColor="DeepSkyBlue"

  AlternatingRowStyle-BackColor="PowderBlue"

  runat="server" />

 

<asp:SqlDataSource

  id="Northwind"

  ConnectionString="server=localhost;uid=sa;pwd=secret;

database=Northwind"

  SelectCommand="Select Top 10 ProductName, UnitPrice

FROM Products ORDER BY UnitPriceDESC"

  runat="server" />

 


Figure 3. The ProductsWebPartdisplays the 10 most expensive products.

 

The ProductsWebPart is created fromtwo new controls in the ASP.NET 2.0 Framework; the GridView control is thereplacement for the ASP.NET 1.0 DataGrid control; and the SqlDataSource controlrepresents a connection to a data source. When the ProductsWebPart isdisplayed, the SELECT statement contained in the SqlDataSource control'sSelectCommand property is executed and the results are displayed in theGridView.

 

Our final Web Part enables someoneto look up an employee's phone extension based on the employee's last name (seeFigure 4):

 

<%@ Control %>

 

<asp:TextBox

  id="txtLastName"

  Text="Lookup Last Name"

  runat="Server" />

 

<asp:Button

  Text="Lookup"

  runat="Server" />

 

<asp:DetailsView

  DataSourceID="mySource"

  AllowPaging="true"

  EnableCaching="true"

  CacheDuration="86400"

  runat="Server" />

 

<asp:SqlDataSource

  id="mySource"

  ConnectionString="Server=localhost;UID=sa;PWD=secret;

Database=Northwind"

  SelectCommand="SELECT LastName,FirstName,Extension

FROM Employees"

  FilterExpression="LastName LIKE '@LastName%'"

  runat="Server">

  <FilterParameters>

    <asp:ControlParameter Name="LastName"

      ControlId="txtLastName"

      PropertyName="Text" />

  </FilterParameters>

</asp:SqlDataSource>

 


Figure 4. The EmployeeLookupWebPartenables you to look up an employee's extension given his or her last name.

 

The EmployeeLookup Web Part takesadvantage of the new DetailsView control included with the ASP.NET 2.0Framework. This control displays the contents of a single item from a datasource automatically. In this case, we're using the DetailsView control todisplay the values of the LastName, FirstName, and Extension columns retrievedfrom the data source when the user enters a last name in the TextBox control.

 

Notice the FilterExpressionproperty contained in the SqlDataSource control. This property enables you tofilter the results of the data returned from the SelectCommand. In this case,we're filtering the results to return only the records that match the last namethe user enters into the TextBox control.

 

Divide a Page IntoWeb Part Zones

Now that we've created the WebParts for our portal application, we're ready to add them to a Web page. Whenyou add Web Parts to a page, you add the Web Parts to something called a WebPart Zone. A Web Part Zone is a region of a page that contains a collection ofWeb Parts (see Figure 5).

 

  <%-- Zone 1 --%>

 

  <asp:WebPartZone id="Zone1" runat="Server">

    <ZoneTemplate>

      <custom:MotivationWebPart

        id="MotivationPart" title="Motivation"

        runat="Server" />

      <custom:EmployeeLookupWebPart

        id="EmployeeLookupPart"   Title="Employee Lookup"

        runat="Server" />

    </ZoneTemplate>

  </asp:WebPartZone>

 

  <%-- Zone 2 --%>

 

  <asp:WebPartZone id="Zone2" runat="Server">

    <ZoneTemplate>

      <custom:ProductsWebPart

        id="ProductsPart" Title="Top Products"

        runat="Server" />

    </ZoneTemplate>

  </asp:WebPartZone>

Figure5. You can add two Web Part Zones to a page with the code in this pagefragment.

 

The first Web Part Zone - namedZone1 - contains two of our Web Parts. It contains the MotivationWebPart andthe EmployeeLookupWebPart. The second Web Part Zone - named Zone 2 - contains asingle Web Part. It contains the ProductsWebPart (see Figure 6).

 


Figure 6. The Web Parts appear inthe two zones displayed by the Northwind Trading Co. intranet portal page in normaldisplay mode.

 

There is one other control you mustinclude in every page that contains Web Parts: The WebPartManager control.Every page that contains Web Parts must contain one, and only one,WebPartManager control. This control must appear before any Web Part Zones in apage. The WebPartManager control is responsible for keeping track of the stateof all the Web Parts in a page. This control is important to us in the nextsection.

 

Make Web PartsCustomizable

Thus far, you might be thinkingthat Web Parts are not all that exciting. To this point, just about everythingthat we've done with Web Parts, we could have done using normal user controls.So why all the fuss?

 

In this section, you'll learn howto unleash the true power of Web Parts by enabling users to personalize theNorthwind portal page. You'll also learn how to enable users to rearrange howWeb Parts are laid out on a page. And you'll learn how to enable users to addnew Web Parts from a catalog of Web Parts.

 

The secret to allowing both typesof personalization is the WebPartManager control. The WebPartManager controlhas an important property that affects the behavior of all the Web Parts in apage: the DisplayMode property. This property has four possible values. Catalog displays a catalog of availableWeb Parts and enables users to rearrange the Web Parts on a page; Design enables users to rearrange theWeb Parts on a page; Edit enablesusers to edit the properties of individual Web parts; and Normal displays the Web Parts without enabling users to edit orrearrange the Web Parts on a page (the default mode).

 

If you want to do anythinginteresting with Web Parts, then you need to change the WebPartManagercontrol's DisplayMode property.

 

The downloadable code for thisarticle contains the complete code for our Northwind Portal page (see theDownload box accompanying this article). Our Northwind portal page contains anHTML table that divides the page into three columns. The first two columnscontain the two Web Part Zones that I discussed in the previous section. Thethird column contains a new control named the CatalogZone control. It enablesyou to display a catalog of Web Parts that a user can add to a page. Forexample, after a user closes a Web Part, the user can add it back to the pagefrom the CatalogZone.

 

The Northwind Portal page alsocontains a LinkButton control that's labeled Personalize. When a user clicksthe Personalize link, the PersonalizePage event handler is executed and thepage mode is changed to Catalog mode. In Catalog mode, the user can personalizethe page (see Figure 7). When the user is satisfied with the appearance of thepage, he can click End Personalize and the page reverts back to its normaldisplay mode.

 


Figure 7. In the Northwind TradingCo. intranet portal page in Catalog display mode, the user is dragging theEmployeeLookupWebPart from Zone 1 to Zone 2.

 

In the current version of the WebParts Framework, any personalization an anonymous user performs is saved inview state. This means that any changes he makes will be lost when theanonymous user leaves the page. (This behavior might change before the finalrelease of the Framework.)

 

On the other hand, if the user isan authenticated user (for example, he was authenticated by using FormsAuthentication), then any changes he makes will be persisted. This means thatif an authenticated user makes changes to the content and layout of a pageusing Web Parts, the changes will remain when he returns to the application.

 

There are many exciting features ofthe Web Parts Framework that I was unable to cover in this brief article. Forexample, the Framework includes several controls that enable users to edit WebParts properties. It also includes support for exporting a Web Part from onepage and importing it to another page.

 

The sample code in this article isavailable for download.

 

Stephen Walther wrote thebest-selling book on ASP.NET, ASP.NET Unleashed. He was also the architect and lead developerof the ASP.NET Community Starter Kit, a sample ASP.NET application produced byMicrosoft. He has provided ASP.NET training to companies across the UnitedStates, including NASA and Microsoft, through his company Superexpert (http://www.AspWorkshops.com).

 

 

 

Add a Comment

There are no comments to display. Be the first one!
You must log on before posting a comment.

Are you a new visitor? Register Here

advertisement




Comments from the DevConnections Community

Join our community of development pros.

Windows problem

I all, I have a problem on my Windows Vista that began afetr the purchase of an external Hard Disk Freecom. A few days afetr the purchase I discon...

Most Recent Posts

GOOGLE LINKS
SPONSORED LINKS
FEATURED LINKS