The XmlNavBar Control

The XmlNavBar Control

Surf the Web, and you ll find numerous pages with lists of links to other pages running down the left-hand side. Known as navigation bars or simply navbars, these ubiquitous UI elements are nearly as common in Web pages as menus are in Windows applications. They also make ideal user controls. Why? Because they typically appear not once but many times throughout a site. A navbar implemented as a user control doesn t have to be physically replicated on each and every page. A simple tag creates the control wherever it s needed. And updating every navbar on the site requires changing just one source code file.

The Web page in Figure 7-11 features a navbar user control I call the XmlNavBar. XmlNavBar retrieves the items that it displays and the URLs that they point to from an XML file. It also has properties for controlling its width and height, its foreground and background colors, and the font that it uses to render its items. XmlNavBar even supports mouseovers. If you include a MouseOverColor attribute in the control tag, the navbar highlights items using the specified color when the cursor passes over them.

The navbar in Figure 7-11 contains four items. Clicking an item takes you to the corresponding Web page: News.aspx, Sports.aspx, Stocks.aspx, or Weather.aspx. All four are provided on the CD that accompanies this book, but because they re virtually identical, only one is shown in this section (Figure 7-12). You can see the @ Register directive that registers the control and the <user:XmlNavBar> tag that creates it. You can also see the XmlSrc attribute identifying the XML file from which the control derives its content. Individual items are represented by Item elements in the XML file. For a given item, Name and Link elements define the item text and the URL that the item refers to. Because XmlNavBar configures itself from an external file, you could customize it on every page by pointing it to different XML files. The XML file used in this example Links.xml appears in Figure 7-13.

Figure 7-11

Web page featuring an XmlNavBar user control.

News.aspx

<%@ Register TagPrefix="user" TagName="XmlNavBar"   src="/books/4/347/1/html/2/XmlNavBar.ascx" %> <html>   <body>     <form runat="server">       <table width="100%" height="100%">         <tr height="48">           <td bgcolor="teal" align="center" colspan="2">             <span style="color: white; font-family: verdana;               font-size: 24pt; font-weight: bold">               News             </span>           </td>         </tr>         <tr>           <td width="128" valign="top" bgcolor="royalblue">             <user:XmlNavBar Xmlsrc="/books/4/347/1/html/2/Links.xml" ForeColor="white"                Font-Name="verdana" Font-Size="10pt" Font-Bold="true"               MouseOverColor="black" RunAt="server" />           </td>           <td align="center" valign="center">             No news is good news           </td>         </tr>       </table>     </form>   </body> </html>
Figure 7-12

Web form that uses XmlNavBar.

Links.xml

<?xml version="1.0"> <Items>   <Item>     <Text>News</Text>     <Link>News.aspx</Link>   </Item>   <Item>     <Text>Sports</Text>     <Link>Sports.aspx</Link>   </Item>   <Item>     <Text>Stocks</Text>     <Link>Stocks.aspx</Link>

</Item>   <Item>     <Text>Weather</Text>     <Link>Weather.aspx</Link>   </Item> </Items>

Figure 7-13

XML source file for configuring an XmlNavBar.

XmlNavBar is defined in the source code file XmlNavBar.ascx (Figure 7-14). That file contains just one line of HTML:

<asp:Table  RunAt="server" />

Everything else is server-side script. Page_Load builds the XmlNavBar at run time by adding rows to MyTable. (Even though a user control isn t a page in the classical sense, Page_Load is still the handler name for the event that fires when the control loads.) Each row contains one cell. Inside the cell is a single item consisting of item text surrounded by an HTML <a> element referencing the item s URL. Here s a typical item:

<a href="News.aspx" onmouseover="defcolor=this.style.color; this.style.color='Black'" onmouseout="this.style.color=defcolor" style="text-decoration: none; font-family: verdana; font-size: 10pt; font-weight: bold; color: White">News</a>

The Href attribute comes from one of the Link elements in the XML file. The MouseOverColor attribute in the <user:XmlNavBar> tag translates into On Mouse Over and OnMouseOut attributes that change the color of the item underneath the cursor. Font and ForeColor attributes, if used, translate into Style attributes in the <a> tags.

XmlNavBar reads XML files the same way Chapter 5 s Converter.aspx reads XML files: by reading them into a DataSet and iterating over the DataSet s rows. DataSet.ReadXml reduces the complex task of parsing an XML file to one simple method call. Once the file is read, XmlNavBar retrieves the names and URLs of the items it generates by using the element names in the XML file as indexes into the DataSet s DataRows.

XmlNavBar.ascx adapts portions of its output to the browser that originated the request. Rather than blindly emit OnMouseOver and OnMouseOut attributes when a MouseOverColor attribute is present in the control tag, XmlNavBar outputs them only if the requestor is Internet Explorer 4 or later. Mouse overs are a royal pain to implement in Navigator, and they don t work in early versions of Internet Explorer, either. How does XmlNavBar know the type and version of the browser that transmitted the request? Like this:

if (Request.Browser.Type.ToUpper ().IndexOf ("IE") > -1     && Request.Browser.MajorVersion >= 4) {       .       .       . }

Web servers receive information about browser types and version numbers in the User-Agent headers accompanying HTTP requests. ASP.NET examines User-Agent headers and makes the information gleaned from them available to server-side scripts through the Request object s Browser property. Type, MajorVersion, MinorVersion, JavaScript, Cookies, and other Browser properties provide information about the browser that originated the request and the features that it supports. For a complete list of Browser properties, see the documentation for System.Web.HttpBrowserCapabilities in the .NET Framework SDK.

A final item of interest regarding XmlNavBar.ascx is how it implements the Font property. Font is nothing more than a container for subproperties named Name, Size, and Weight. When ASP.NET encounters an attribute such as this one:

Font-Name="verdana"

it generates code that looks something like this:

ctrl.Font.Name="verdana";

For this to work, Font must be an instance of a type that implements a string property named Name. In XmlNavBar.ascx, Font is implemented this way:

MyFontInfo MyFont = new MyFontInfo ();   .   .   . public MyFontInfo Font {     get { return MyFont; }     set { MyFont = value; } }

MyFontInfo, which is also defined in XmlNavBar.ascx, implements Name this way:

string FontName;   .   .   . public string Name {     get { return FontName; }     set { FontName = value; } }

The Font property that Web controls inherit from WebControl is implemented in much the same way. Now that you ve seen how it works, you can write properties that have subproperties any time the situation calls for it.

Incidentally, when I designed XmlNavBar, I didn t intend to write a MyFontInfo class. I planned to use the FCL s FontInfo (System.Web.UI.WebControls.FontInfo) class instead. However, FontInfo can t be instantiated directly because it lacks a public constructor. So I wrote a version of my own and included it in XmlNavBar.ascx.

XmlNavBar.ascx

<%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Drawing" %> <asp:Table  RunAt="server" /> <script language="C#" runat="server">   string MyXmlSrc;   Color MyBackColor;   Color MyForeColor;   Color MyMouseOverColor;   MyFontInfo MyFont = new MyFontInfo ();   public string XmlSrc   {       get { return MyXmlSrc; }       set { MyXmlSrc = value; }   }   public Color BackColor   {       get { return MyBackColor; }       set { MyBackColor = value; }   }   public Color ForeColor   {       get { return MyForeColor; }       set { MyForeColor = value; }   }

public Color MouseOverColor   {       get { return MyMouseOverColor; }       set { MyMouseOverColor = value; }   }   public MyFontInfo Font   {       get { return MyFont; }       set { MyFont = value; }   }   void Page_Load (Object sender, EventArgs e)   {       if (MyXmlSrc != null) {           DataSet ds = new DataSet ();           ds.ReadXml (Server.MapPath (MyXmlSrc));           foreach (DataRow item in ds.Tables[0].Rows) {               TableRow row = new TableRow ();               TableCell cell = new TableCell ();               StringBuilder builder = new StringBuilder ();               builder.Append ("<a href=\"");               builder.Append (item["Link"]);               builder.Append ("\" ");               if (MyMouseOverColor != Color.Empty &&                   Request.Browser.Type.ToUpper ().IndexOf ("IE") > -1                   && Request.Browser.MajorVersion >= 4) {                   builder.Append ("onmouseover=\""  +                       "defcolor=this.style.color; " +                       "this.style.color=\'");                   builder.Append (MyMouseOverColor.Name);                   builder.Append ("\'\" onmouseout=\"" +                       "this.style.color=defcolor\" ");               }               builder.Append ("style=\"text-decoration: none; ");               if (MyFont.Name != null) {                   builder.Append ("font-family: ");                   builder.Append (MyFont.Name);                   builder.Append ("; ");               }               if (MyFont.Size != FontUnit.Empty) {                   builder.Append ("font-size: ");                   builder.Append (MyFont.Size.ToString ());                   builder.Append ("; ");               }               if (MyFont.Bold)                   builder.Append ("font-weight: bold; ");               if (MyForeColor != Color.Empty) {                   builder.Append ("color: ");                   builder.Append (MyForeColor.Name);               }               builder.Append ("\">");               builder.Append (item["Text"]);               builder.Append ("</a>");               cell.Text = builder.ToString ();               row.Cells.Add (cell);               MyTable.Rows.Add (row);           }           if (MyBackColor != Color.Empty)               MyTable.BackColor = MyBackColor;       }   }   public class MyFontInfo   {       string FontName;       FontUnit FontSize;       bool FontBold = false;       public string Name       {           get { return FontName; }           set { FontName = value; }       }       public FontUnit Size       {           get { return FontSize; }           set { FontSize = value; }       }       public bool Bold       {           get { return FontBold; }           set { FontBold = value; }       }   } </script>

Figure 7-14

XmlNavBar user control.



Programming Microsoft  .NET
Applied MicrosoftNET Framework Programming in Microsoft Visual BasicNET
ISBN: B000MUD834
EAN: N/A
Year: 2002
Pages: 101

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