Server Controls

Custom server controls, sometimes known as user controls, encapsulate user-interface functionality. They are implemented just like regular .aspx pages, except that they usually don't have some of the wrapping HTML tags, such as <html> and <body>. That's because they're almost always used from within another .aspx page that already has these wrapping HTML tags. As with regular .aspx pages, there is still a Load and Unload event that can be used to maintain data.

Most user controls are contained in .ascx files as this is the file extension for them. This differentiates them from regular .aspx files.

Custom controls can be used from a page by registering them with a unique prefix and name, and specifying the source file. A register tag is placed at the top of the .aspx file to register custom controls, as follows:

 <%@ Register TagPrefix="IBuySpy" TagName="Menu" src="/books/2/627/1/html/2/_Menu.ascx" %> 

This control can be declared and used within the .aspx page as follows:

 <IBuySpy:Menu  runat="server" /> 

The public properties can all be set from within the .aspx page, as you can see above where the id property is set to contain the value of "MyMenu".

Also Bought

This user control displays products that others who bought a particular item have bought. It's a good way to offer additional products that customers might buy. For instance, if they buy the moustache translator, there's a good chance that they'll buy the interpreter earrings. The control can be found in the _AlsoBought.ascx and _AlsoBought.ascx.cs files (_AlsoBought.ascx and _AlsoBought.ascx.vb for the VB version).

This control relies on a component named ProductsDB, and this component is located in the Components directory in a file named ProductsDB.cs (or ProductsDB.vb for the VB version). The ProductsDB component performs queries that are related to the products. Table 8.1 shows the methods and their descriptions.

The .ascx page of the AlsoBought user control contains a Repeater with an ID named alsoBoughtList. This Repeater is decorated so that it looks attractive, and it has header and footer templates (HeaderTemplate and FooterTemplate). The ItemTemplate contains a HyperLink that will be bound to the data. This will create hyperlinks that go to the ProductDetails.aspx page.

The .ascx.cs (or .ascx.vb for the VB version) file contains the code that uses the ProductsDB component. In the Page_Load() method, a ProductsDB object named productCatalogue is instantiated. A call to the ProductsDB.GetProductsAlsoPurchased() method returns the lists of products that were also purchased by people who purchased this particular item. (The ProductID is passed as a parameter to the GetProductsAlsoPurchased() method.) The Repeater object's DataSource property is set to the SqlDataReader object that is returned.

Table 8.1. The Methods for the ProductsDB Component

Method

Return Type

Description

GetProductCategories()

SqlDataReader

The GetProductCategories() method returns a DataReader that exposes all product categories (and their Category IDs) within the IBuySpy Products database. The SqlDataReaderResult structure also returns the SQL connection, which must be explicitly closed after the data from the DataReader is bound into the controls.

GetProducts()

SqlDataReader

The GetProducts() method returns a structure containing a forward-only, read-only DataReader. This displays all products within a specified product category. The SqlDataReaderResult structure also returns the SQL connection, which must be explicitly closed after the data from the DataReader is bound into the controls.

GetProductDetails()

ProductDetails

The GetProductDetails() method returns a ProductDetails structure containing specific details about a specified product within the IBuySpy Products Database.

GetProductsAlsoPurchased()

SqlDataReader

The GetPGetProductsAlsoPurchasedroducts() method returns a structure containing a forward-only, read-only DataReader. This displays a list of other products also purchased with a specified product. The SqlDataReaderResult structure also returns the SQL connection, which must be explicitly closed after the data from the DataReader is bound into the controls.

GetMostPopularProductsOfWeek()

SqlDataReader

The GetMostPopularProductsOfWeek() method returns a structure containing a forward-only, read-only Data Reader containing the most popular products of the week within the IBuySpy Products database. The SqlDataReaderResult structure also returns the SQL connection, which must be explicitly closed after the data from the DataReader is bound into the controls.

SearchProductDescription()

SqlDataReader

The SearchProductDescriptions() method returns a structure containing a forward-only, read-only DataReader. This displays a list of all products whose name and/or description contains the specified search string. The SqlDataReaderResult structure also returns the SQL connection, which must be explicitly closed after the data from the DataReader is bound into the controls.

Then, the Repeater's DataBind() method is called. Finally, if there are no items in the recordset, the Repeater is hidden by setting the Repeater's Visible property to false. Listing 8.1 shows the AlsoBought user control's Page_Load() method in C# and VB.

Listing 8.1 The Page_Load() method for the AlsoBought User Control

C#

 private void Page_Load(object sender, System.EventArgs e) {   // Obtain list of products that people who "also bought" an item have   // purchased.  Databind to list control   IBuySpy.ProductsDB productCatalogue = new IBuySpy.ProductsDB();   alsoBoughtList.DataSource =     productCatalogue.GetProductsAlsoPurchased(ProductID);   alsoBoughtList.DataBind();   // Hide the list if no items are in it   if (alsoBoughtList.Items.Count == 0)   {     alsoBoughtList.Visible = false;   } } 

VB

 Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)   ' Obtain list of products that people who "also bought" an item have   ' purchased.  Databind to list control   Dim productCatalogue As IBuySpy.ProductsDB = New IBuySpy.ProductsDB()   alsoBoughtList.DataSource = _     productCatalogue.GetProductsAlsoPurchased(ProductID)   alsoBoughtList.DataBind()   ' Hide the list if no items are in it   If alsoBoughtList.Items.Count = 0 Then     alsoBoughtList.Visible = False   End If End Sub 

Header

The Header user control is used at the top of each page in the IBuySpy Store application. This control is very simple because all it contains is static HTML. None of the data-access components are used, and no other user controls are used. The control can be found in the _Header.ascx and _Header.ascx.cs files (_Header.ascx and _Header.ascx.vb for the VB version).

Menu

This user control creates a menu of all product categories in the database. This forms the left-hand navigation of the product catalog pages. The control can be found in the _Menu.ascx and _Menu.ascx.cs files (_Menu.ascx and _Menu.ascx.vb for the VB version).

The .ascx page contains a DataList named MyList. This object will contain the product categories as hyperlinks.

The .ascx.cs file (or the .ascx.vb file for the VB version) contains the code that gets the data, and it databinds to the MyList object. It's in the Page_Load() method. As with the AlsoBought user control, the Menu control relies on the ProductDB component. (See Table 8.1 for details about this class's methods.)

The Page_Load() method is simple. It first attempts to retrieve an HTML parameter named Selection. If this parameter is found, the Data List object's SelectedIndex property is set to this value. The next thing that is done is to instantiate a ProductsDB component. The ProductsDB.GetProductCategories() method is used to retrieve a SqlDataReader object, which is then used to set the DataList's DataSource property. Finally, a call to the DataList's DataBind() method completes the process. Listing 8.2 shows the C# and VB source code for the Menu user control's Page_Load() method.

Listing 8.2 This Page_Load() Method Populates the DataList with the Product Categories.

C#

 private void Page_Load(object sender, System.EventArgs e) {   // Set the curent selection of list   String selectionId = Request.Params["selection"];   if (selectionId != null) {     MyList.SelectedIndex = Int32.Parse(selectionId);   }   // Obtain list of menu categories and databind to list control   IBuySpy.ProductsDB products = new IBuySpy.ProductsDB();   MyList.DataSource = products.GetProductCategories();   MyList.DataBind(); } 

VB

 Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)   ' Set the curent selection of list   Dim selectionId As String = Request.Params("selection")   If Not selectionId Is Nothing Then     MyList.SelectedIndex = CInt(selectionId)   End If   ' Obtain list of menu categories and databind to list control   Dim products As IBuySpy.ProductsDB = New IBuySpy.ProductsDB()   MyList.DataSource = products.GetProductCategories()   MyList.DataBind() End Sub 

There's one important note regarding the Menu control. It is cached and refreshes only every hour (or 3,600 seconds). This is a significant performance win because the database access can really add up if the application is heavily trafficked. The following directive is placed at the top of the _Menu.ascx page (but below the Control directive). The VaryByParam attribute allows you to vary the cached output, depending on the GET query string or form POST parameters.

 <%@ OutputCache Duration="3600" VaryByParam="selection" %> 

Popular Items

This user control displays the five most popular items, and it is a way to suggest sell a technique popular in today's retail environment. It's kind of like when you walk into McDonalds and don't order French fries; many times, the person taking your order will ask if you want French fries. This is known as suggest selling because it suggests a purchase that the buyer hasn't made. Many times the items that are suggested are ones that are common, or ones that are on special. The control can be found in the _PopularItems.ascx and _PopularItems.ascx.cs files (_PopularItems.ascx and _PopularItems.ascx.vb for the VB version).

The user-interface part of this control features a Repeater. This Repeater is populated in the control's Page_Load() method. The data will become part of a HyperLink that's in the DataList that has as its destination the ProductDetails.aspx page. This gives users a way to see the details about these popular items.

The Page_Load() method uses the ProductsDB component to retrieve the list of popular items from the database. After instantiating a ProductsDB component, the ProductsDB.GetMostpopularProductsOfWeek() method, which returns a SqlDataReader object, is called. The SqlData Reader is assigned to the DataList's DataSource property. A call to the DataList.DataBind() method finishes things up. There is one final detail, though. If the recordset is empty, the DataList is hidden by setting its Visible property to false. The Page_Load() method can be seen in Listing 8.3.

Listing 8.3 The Page_Load() Method That Populates the DataList Object for the PopularItems User Control

C#

 private void Page_Load(object sender, System.EventArgs e) {   // Obtain list of favorite items   IBuySpy.ProductsDB products = new IBuySpy.ProductsDB();   // Databind and display the list of favorite product items   productList.DataSource = products.GetMostPopularProductsOfWeek();   productList.DataBind();   // Hide the list if no items are in it   if (productList.Items.Count == 0) {     productList.Visible = false;   } } 

VB

 Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)   ' Obtain list of favorite items   Dim products As ProductsDB = New ProductsDB()   ' Databind and display the list of favorite product items   productList.DataSource = products.GetMostPopularProductsOfWeek()   productList.DataBind()   ' Hide the list if no items are in it   If productList.Items.Count = 0 Then     productList.Visible = False   End If End Sub 

The PopularItems user control does partial-page output caching at one-hour intervals. This enables the application to avoid having to read the database on each request to a page containing this user control, thus dramatically improving performance. The following directive can be seen at the top of the PopularItems.ascx page (although you must include the VaryByParam attribute in any @ OutputCache directive, you can set its value to None if you do not want to use the functionality it provides):

 <%@ OutputCache Duration="3600" VaryByParam="None" %> 

Review List

This user control displays a list of customer reviews. The control can be found in the _ReviewList.ascx and _ ReviewList.ascx.cs files (_ReviewList. ascx and _ReviewList.ascx.vb for the VB version).

The user interface object that's used to display the list is a DataList. It is declared in the .ascx file and populated in the .ascx.cs (or .ascx.vb file for the VB version).



ASP. NET Solutions - 24 Case Studies. Best Practices for Developers
ASP. NET Solutions - 24 Case Studies. Best Practices for Developers
ISBN: 321159659
EAN: N/A
Year: 2003
Pages: 175

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net