www.codeguru.com/csharp/sample_chapter/article.php/c13037/

Back to Article

Home >> .NET / C# >> Sample Chapter


Web parts: the building blocks of portals
Rating: none

DarrenNeimke (view profile)
December 19, 2006

Go to page: Prev  1  2  3  4  5  Next

2.3 UNDERSTANDING THE WEBPART CLASS

Up until now, all the web parts that we've seen have been created by simply adding server controls—such as the Calendar and Label—to zones within the page. Now it's time to learn about another kind of web part control—a custom server control that directly inherits from the abstract WebPart base class. In this section we will create a web part by inheriting directly from the WebPart class and then learn how to add our custom web part to a web page by registering our custom web part class with the page.


(continued)




Dragging user controls onto zones and having them treated as web parts is fine when the web parts do not need to be shared outside a single application; but part of the power of web parts is that, by their very nature, they lend themselves well to being reused in more than just a single portal application. For reuse, user controls cannot surpass custom controls, because custom controls can be compiled into very specific assemblies and easily shared between applications. If you need to share web parts between your own applications, or indeed, package them for reuse by third parties, then you will want to create custom controls so that you can take advantage of the packaging of assemblies.To do this you will need to create custom classes that derive directly from the WebPart class.

The WebPart class lives in the System.Web.UI.WebControls.WebParts namespace and serves as the base class for all web part controls. In fact, if you look at the definition of GenericWebPart, you will see that it does in fact inherit from the WebPart class. The WebPart class itself inherits from a base class named Part. The Part class has the basic properties that are relevant for all web part "parts"—including editor parts and catalog parts such as description, title and a few others.

2.3.1 Using custom controls

We've just seen that, when creating web parts, we have two options. The first option is to create a class that derives directly from the WebPart class, and the second option is to drop user controls or server controls onto a web zone and have the framework place those controls within a generic wrapper known as a GenericWebPart. Let's now take a look at how to create web parts using each of these two methods.

The first web part that we'll build is a custom server control that inherits directly from the WebPart class. This will allow us to see for the first time what's involved in getting a web part up and running using that method. The web part that we will build will be a weather web part to display the weather for a variable number of days. It will have a property that allows us to specify how many days of weather to display. This is a good example of the sort of informational web part that would appear on a typical portal. Figure 2.6 displays what the weather web part control will look like when displayed in a browser.

Figure 2.6 This custom web part control displays random weather information for a variable number of days.

Creating a weather web part

To start creating the weather web part, open your test web project and add a new class file named "CustomWeatherPart.cs" to the WebPart folder and then derive that class from WebPart. At this point your class should look similar to the following snippet:

namespace WebPartTests {

   public class CustomWeatherPart : WebPart {

      public CustomWeatherPart() { }
   }
}

To allow users to set the number of days of weather to be displayed, we'll add a property named NumberOfDays. By default we'll set it to a value of 4 so that at least that number of days of weather will be displayed—even before the user has had time to configure it to be some other value. We can store the value for this property in ViewState so that it is persisted even after multiple trips between the browser and the web server (postbacks). The last bit of logic to be added ensures that the user cannot accidentally set the number of days to a value greater than 10 or less than 1. The code for our property is shown in listing 2.2, with all of its logic in place.

Listing 2.2 The NumberOfDays property contains the number of days of weather that should appear in the web part.

public int NumberOfDays {
   get {
      if (ViewState["NumberOfDays"] == null) {
         return 4;
      } else {
         return (int)ViewState["NumberOfDays"];
      }
   }
   set {
      if (value < 1 || value < 10) {
         ViewState["NumberOfDays"] = 4;
      } else {
         ViewState["NumberOfDays"] = value;
      }
   }
}

The NumberOfDays property can now be used to specify how many days of weather our control will display; and the constraints that were added to the property ensure that there will always be some number of days to display weather for.

Rendering custom controls

When you work with custom server controls, one of the problems you face is that user interface elements are created by using code, as opposed to standard HTML and markup. Displaying a control in code requires creating every facet of it, including its style information in code. This is not the case when using user controls because you can use Visual Studio's design-time tools to simply drag controls from the toolbox onto the surface of the user control. What's more, once the controls are on the design surface, the developer can use design time tools, such as property editors and other wizards that exist within Visual Studio, to develop and maintain the properties of the control.

You create user interface elements for custom server controls by writing code that runs during the control's Render method. The Render method is a method that is common to all web controls and is called by the ASP.NET runtime to display every web control. In the Render method you write your user interface elements directly into an HtmlTextWriter object that is passed in as a parameter to that method by the ASP.NET Framework.

NOTE The Render method is a virtual (overridable) member of the System.Web.UI.Control class. This is a class that all server controls inherit from.

For our custom weather web part control, we'll use some logic to randomly produce a weather result for a variable number of days, and then create a weather image for each day of weather. In reality you would likely have some back-end process—such as a web service—that would return actual weather results. Add the code shown in listing 2.3 to your class and build the project to see that everything compiles.

Listing 2.3 The Render method for the weather web part displays a series of random weather images.


(
Full Size Image)

In the Render method we have constructed a simple loop that will run for as many days as we have weather to display and, within each loop, a weather picture is produced and rendered.

NOTE The HtmlTextWriter that we've used to render our weather web part is a customized text writer that simplifies the task of writing HTML and is also capable of rendering specific output based on the device that is targeted. For example, when the page is visited by an older browser, the HtmlTextWriter will automatically emit down-level markup.
Adding custom controls

That completes the creation of the custom web part; all that remains is to create a web page to contain and display it—and from now on we'll refer to web pages that contain web parts as "web part pages," to distinguish them from ordinary web pages.

Add a new web page to your project named CustomWeather.aspx and, as with all web part pages, add a WebPartManager to it. You must also declare the server control to the page by using a Register directive at the head of the page as shown here:

<%@ Register TagPrefix="wp" Namespace="WebPartTests" %>

When you have registered your controls to the page you can then reference your custom web part within a ZoneTemplate—making sure to use the same tag prefix as declared in the register directive:

<asp:WebPartZone ID="WebPartZone1" runat="server">
   <ZoneTemplate>
      <wp:CustomWeatherPart
         ID="CustomWeatherPart1"
         runat="server"
         Title="Weather Forecast" />
   </ZoneTemplate>
</asp:WebPartZone>

As we saw in figure 2.6, when this page is displayed in a browser, it will render the weather web part with the default four days' worth of weather visible. To change the number of days that are displayed you can just add the NumberOfDays property in the markup of the server control or set the value in code. The following snippet shows the property being set within the markup to display an entire week's worth of weather.

<wp:CustomWeatherPart
   ID="CustomWeatherPart1"
   runat="server"
   NumberOfDays="7"
Title="Weather Forecast" />

2.3.2 Creating web parts with user controls

We've seen labels and calendars that magically morph into GenericWebParts and custom server controls that derive from the WebPart class being used to create web parts; but we haven't as yet seen a web part created using a UserControl. Being able to use user controls as web parts allows developers to create user interfaces employing exactly the same techniques they applied when creating web pages. This includes having the ability to drag-and-drop controls from the Toolbox onto the design surface. For this reason, user controls may also be easier to understand for someone who is relatively new to ASP.NET and who would benefit from the better design time experience that they would get when creating user controls in Visual Studio 2005. One advantage includes being able to drag controls directly from the Visual Studio 2005 Toolbox onto the surface of user controls as opposed to having to work solely in code.

The weather web part that we built had a very simple user interface and therefore the rendering code and logic were not overly complex; but as the amount of presentation code that is required for a control increases, custom server controls can become quite difficult to create and maintain because you tend to end up writing many lines of code to create the user interface layout.

Displaying calendar appointments

In this next example a user control will be used to create a web part that displays the current date and time. The web page will also display information to the users about upcoming meetings from their calendars. In our example, however, we'll again use hard-coded sample data for simplicity rather than writing the code that would be required to connect to a real calendar. Figure 2.7 shows how this web part will appear when it's complete.

Figure 2.7 A user control web part is used to display the current date and time. It also displays information about upcoming meetings for the logged-in user.

From within your test web project, add a new user control file named MyCalendar.ascx to the project. To create the user interface elements necessary to display our control, add the markup that is displayed in listing 2.4 to the control.

Listing 2.4 The HTML to display the calendar user interface


(Full Size Image)

Listing 2.4 creates the presentation layout for the web part. As you can see, there is a Repeater server control named rptMeetings that binds to some fields named "MeetingName" and "MeetingDateTime."

Binding dynamic data

I mentioned before that, in a real world situation, the data we are displaying would be coming from a live backend, line-of-business application such as a Customer Relationship (CRM) database that contains information about the contacts and customers of a business. However, in our example, those fields are going to come from some sample data held in a data table. To create the data and bind it to the repeater, switch to source code view and add the code displayed in listing 2.5 to the form:

Listing 2.5 Data is created and is bound to the user interface elements of our Calendar web part control


(Full Size Image)

The code in listing 2.5 shows that a DataTable is created and two columns are added to it that will contain the information about meetings. Next, dummy data is appended to the table before we finally bind the table to our repeater control, which contains the user interface logic to display the data to the user.

That completes the code for the user control. Now we can create a web page to display it in. Add a page to your test web project and, as with all web part pages, add a WebPartManager and a WebPartZone to the page.

With the page in design mode, drag the user control that we just created from the Server Explorer onto the web part zone. Listing 2.6 shows how the page appears when displayed in source view. You can see that the designer has added a Register directive for the user control and also added the correct mark-up for the user control into the body of the ZoneTemplate. Build and run your page in a browser to view the results. They should appear as they did in figure 2.7.

Listing 2.6 The MyCalendar user control web part is declared within the web part zone

<%@ Register Src="MyCalendar.ascx" TagName="MyCalendar"
             TagPrefix="uc1" %>

<asp:WebPartZone ID="WebPartZone1" runat="server">
   <ZoneTemplate>
      <uc1:MyCalendar
         id="MyCalendar1"
         runat="server"
         Title="My Calendar" />
   </ZoneTemplate>
</asp:WebPartZone>

Now you've seen both options for creating web part controls. That is, you can either create them by using custom server controls and by inheriting from the base WebPart class, or you can use user controls. In a very short time we've actually managed to build web parts by using both custom server controls and user controls. Ideally, as you've been working through these samples you've started thinking of all the different types of web parts that a real business might want to have displayed on its portal—employee information, sales data, production figures, profit and loss data, and so on. As we move further into the book, you'll learn that the portal framework comes complete with a catalog to store all these parts. Then you will see that having too many web parts never presents a problem, because they can all be stored and easily retrieved from within the catalog gallery, ready to be displayed on a user's page at any time.

Go to page: Prev  1  2  3  4  5  Next

Tools:
Add www.codeguru.com to your favorites
Add www.codeguru.com to your browser search box
IE 7 | Firefox 2.0 | Firefox 1.5.x
Receive news via our XML/RSS feed






internet.commediabistro.comJusttechjobs.comGraphics.com

Search:

WebMediaBrands Corporate Info

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs