Author Once, Theme Always

Build ASP.NET Pages that Support Variable Graphics

Dino Esposito

October 30, 2009

11 Min Read
ITPro Today logo in a gray background | ITPro Today

CoreCoder

LANGUAGES: C#| VB.NET

ASP.NETVERSIONS: 2.0

 

Author Once, Theme Always

Build ASP.NET Pages that Support Variable Graphics

 

By Dino Esposito

 

There are controls in the ASP.NET framework that supplysophisticated user interface features. But finding the right combination ofstyle settings and values for appearance properties can be difficult, even withthe help of Visual Studio.NET designers. Only searching in the ASP.NET 1.xtoolbox, you can find at least a couple of these UI-rich controls: DataGrid andCalendar. Aware of the issue, these controls attempt to alleviate your troublesby providing smart options in the Visual Studio.NET 2003 designer. Theseoptions manifest through the AutoFormat feature (a list of predefined skins forcontrols). This is nothing radically new AutoFormat was first introduced withMicrosoft Word tables yet this is a useful and time-saving capability. To bereally helpful, however, the auto-format feature would need at least a coupleof additions, such as definition of custom skins and programmatic binding ofskins.

 

In ASP.NET 2.0, both goals are achieved thanks to themes. Like AutoFormat, themes is not anew concept for Microsoft software products. Logically speaking, in fact,ASP.NET themes are in no way different from Windows XP themes. Themes are afeature for customizing the visual appearance of a Web page and, in turn, ofthe whole Web site. As a developer, you can define one or more themes to shipwith your application; as a power user, you can customize the look-and-feel ofa site by choosing one of the available themes.

 

There s some architectural work in the ASP.NET runtime tomake support for themes possible. For this reason, themes are supported inASP.NET 2.0, but not in ASP.NET 1.x. Themes are pluggable elements in anyASP.NET application so that third-party vendors can even create and sell themesfor certain particularly rich controls.

 

In short, themes are an easy way for page authors toensure a consistent look-and-feel for the constituent controls of a page. Atthe same time, themes let you easily change the appearance of a control in asingle shot. Settings contained in a theme can be deployed to individualapplications or all applications in a server with the same ease.

 

What Is a Theme, Anyway?

At its core, a theme makes it easy to customize the visualappearance of a Web site while requiring little or no modifications to theoriginal page. Pages can seamlessly work with or without a theme and usedifferent themes at different times based on user preferences. Technicallyspeaking, a theme is a collection of files and can be overall seen as a sort ofsuper CSS file.

 

A theme may include a CSS stylesheet file, as well as aset of skins and associated files such as images and other resources. Like aCSS, once enabled the theme determines the appearance of all controls that fallunder its jurisdiction. To get the gist of themes, consider this simple tag:

 

 

Without themes, the calendar will look quite spartan. Witha theme added, however, the same markup renders a more colorful and appealingcalendar. Take a look at Figure 1. Which do you think is the unthemed calendar?To get a more appealing result, no code had to be added; a new attribute in the@Page directive does the trick. As you can see, themes supply a neat separationbetween the page code, controls, and formatting rules.

 


Figure 1: A Calendar control, withand without themes.

 

Central to themes is the concept of a skin. A skin is anamed set of visual properties and templates that can be applied to one or morecontrols on a page. The skin determines the appearance of a control in much thesame way clothes determine the appearance of people. A skin is alwaysassociated with a specific control type. In Beta 2, ASP.NET 2.0 doesn t shipany sample themes but writing one is a snap, as you ll see in a moment.

 

Stylesheet and Customization Themes

In ASP.NET 2.0 there are two types of themes, stylesheet themesand customization themes. What s the difference? They re the same kind ofobject; the difference lies in how they re managed by the ASP.NET runtime. Astylesheet theme is applied to the controls in the page before the attributesin the .aspx source file are processed. This means that settings in the .aspxfile will override the settings defined by the theme. On the other hand, acustomization theme is applied later and overrides any settings hard-coded inthe .aspx source file. It is essential to note that whatever theme you apply,whether it be customization or stylesheet-control properties, it can always bemodified through code in page events like Init and Load.

 

You set stylesheet themes and customization themes usingdifferent attributes in the @Page directive. The same theme can be used as a stylesheetor customization theme at different times.

 

Imagine you create a new Web site and you want it to bevisually appealing from the start. Instead of having to learn all the availablestyle properties of each employed control, you simply get a third-party ASP.NETtheme (or have other members of your team create one). With this change, pagesautomatically inherit a new, and hopefully attractive, appearance. For example,if you add a Calendar control to a page, it automatically renders with thedefault appearance defined in the theme with no need for setting otherproperties declaratively or programmatically.

 

Selecting a theme for one or more pages doesn tnecessarily bind you to the settings of that theme, however. Through the VisualStudio.NET designer you can review the pages and manually adjust some of thestyles in a control, if you wish.

 

Create a Theme

To create a new theme in a Visual Studio.NET 2005 ASP.NETsolution, you start by creating a new folder under App_Themes. Right-click onthe App_Themes node and choose to create a theme folder. Next, you add themefiles to the folder. In this way, you create a theme specific to theapplication. By moving the directory to the root path of global themes on theWeb server you can make that theme available to all Web applications installedon the server machine. Figure 2 shows the contents of a sample theme as itappears through Windows Explorer. A theme is an aggregation of files. Typicalauxiliary files are CSS stylesheet files, skin files, images, XML or text files,or extensible stylesheet files (XSLT). In Visual Studio.NET 2005 you can createany of these by adding a new item to the folder. Empty files of the specifiedtype are created in the theme folder and edited through more or lessspecialized text editors. Of all the possible auxiliary files, skin files arethe least known and, therefore, the only ones to deserve further attention inthis article.

 


Figure 2: The constituent files ofan ASP.NET theme.

 

Saved with a .skin extension, a skin file contains the theme-specificmarkup for a given set of controls. A skin file is made by a sequence of servercontrol definitions that include predefined values for most visual properties,images for URL-based properties, and markup for supported templates. Each skinis control-specific and has a unique name. You can define multiple skins for agiven control and distinguish them by name. Once themed, a control has theoriginal markup written in the .aspx source file modified at run time by thecontent of the skin. The way the modification occurs depends on whether acustomization or a stylesheet theme is used. Skin files are located in the rootof the theme folder. Figure 3 shows a sample skin file.

 

 ForeColor="#585880"Font-Size="0.9em" Font-Names="Verdana" />  BorderStyle="Solid"Font-Size="0.9em" Font-Names="Verdana"  ForeColor="#585880"BorderColor="#585880" BorderWidth="1pt"  CssClass="theme_textbox" />  Font-Bold="true"BorderWidth="1pt" ForeColor="#585880"  BackColor="#F8F7F4" />  Font-Bold="true"BorderWidth="1pt" ForeColor="white"  BackColor="red"/> Figure 3: A sampleskin file.   In a page themed with the theme shown in Figure 3, thefollowing markup will render buttons with bold font and a 1-pixel border:     Likewise, the textboxes will have a 1-pixel frame andwhite background. You have no need to bother about styles; you choose the themeyou like, apply it, and go. But how do you apply a theme?  Apply a Theme You can apply themes at various levels: application,folder, and individual pages. In addition, within the same theme you can selectdifferent skins for the same type of control. Setting a theme at theapplication level affects all the pages and controls in the application. It s afeature you configure in the application s web.config file, as follows:       The preceding theme attribute sets a customization theme.If you use the styleSheetTheme attribute instead, you set a stylesheet theme.Likewise, a theme can be applied to all the pages found in a given folder andbelow. To do that, you create a new web.config file in an application sdirectory and add to it the section shown above. You can also set the theme fora particular page. In this case, only the controls in the page will be themed.You set a customization or stylesheet theme using the Theme or StyleSheetThemeattribute on the @Page directive:  <% @Page Language="C#"Theme="SmokeAndGlass" %> <% @Page Language="C#" StyleSheetTheme= "SmokeAndGlass"%>   It is important to note that the name of the selectedtheme must match the name of a subdirectory under the App_Themes path or thename of a global theme. If a theme with a given name exists both locally to theapplication and globally to the site, the local theme takes precedence.   A theme can contain multiple skins for a given control,each identified with a unique name (the SkinID attribute). A theme can containany number of named skins per control, but just one unnamed (default) skin. Youselect the skin for a control in an ASP.NET themed page by setting the control sSkinID property. If the page theme doesn t include a skin that matches theSkinID property, the default skin for that control type is used. Given the skinshown in Figure 3, only the second of the two buttons below will display with ared background:    "Click"skinid="RedButton" />   When you enable theming on a page, all controls are themedexcept controls, and individual control properties, that explicitly disabletheming. To disable theming, set the boolean EnableTheming property on ASP.NET2.0 controls to false.  CSS vs. Themes Themes are similar to CSS stylesheets in that both apply aset of common attributes to any page where they are declared. However, themesdiffer from CSS stylesheets in a few key ways. Themes work on controlproperties, whereas CSS stylesheets operate on styles of HTML elements. Withthemes you can include auxiliary files and specify standard images forparticularly UI-rich controls, such as the TreeView control or the pagingtemplate of a DataGrid. In addition, themes can optionally force overriding oflocal property values (customization themes) and not cascade as CSS stylesheetsdo.   As themes incorporate CSS stylesheet definitions, andapply them along with other property settings, there s no reason for preferringCSS stylesheets over themes in ASP.NET 2.0 applications.  Load Themes Dynamically Themes are normally defined statically and never change unlessyou edit the pages on the production server. However, themes could be appliedand changed dynamically in pages that support this feature explicitly. TheASP.NET runtime loads theme information immediately after the PreInit eventfires. When the PreInit event fires (this is a new event in the ASP.NET 2.0page lifecycle) the Theme property of the Page class is set with any themereferenced in the @Page directive. By handling the event, you canprogrammatically override it. So if you want to enable your users to changethemes on the fly, create a Page_PreInit event handler, as shown in Figure 4.Figure 5 shows the sample page in action. The drop-down list control enumeratesthe installed application themes and lets you choose the one to apply. Theselected theme is then applied in the PreInit event and immediately reflected.In the PreInit event, no viewstate has been restored yet; so Request.Form isthe only safe way to access a posted value such as the selected theme.   (C#)public partial class TestThemes : System.Web.UI.Page{   protected voidPage_Load(object sender, EventArgs e)    {    if (!IsPostBack) {     ThemeList.DataSource= GetAvailableThemes();     ThemeList.DataBind();   }    }  void Page_PreInit(objectsender, EventArgs e)  {    string theme ="";    if(Page.Request.Form.Count > 0)      theme =Page.Request["ThemeList"].ToString();   if (theme =="None")      theme = "";    this.Theme = theme;  }  StringCollectionGetAvailableThemes() {    string path = Request.PhysicalApplicationPath+ @"App_Themes";    DirectoryInfo dir = newDirectoryInfo(path);    StringCollection themes= new StringCollection();   foreach (DirectoryInfodi in dir.GetDirectories())     themes.Add(di.Name);    return themes;  } } (VB) Public Partial Class TestThemes : Inherits System.Web.UI.Page   Protected SubPage_Load(ByVal sender As Object,                            ByVal e As EventArgs)  If Not IsPostBack Then   ThemeList.DataSource =GetAvailableThemes()   ThemeList.DataBind() End If   End Sub   Sub Page_PreInit(ByValsender As Object,                     ByVale As EventArgs)  Dim theme As String =""  IfPage.Request.Form.Count > 0 Then   theme =Page.Request("ThemeList").ToString() End If If theme ="None" Then   theme = ""  End If Me.Theme = theme   End Sub   FunctionGetAvailableThemes() As StringCollection Dim path As String =Request.PhysicalApplicationPath + _                           "App_Themes"  Dim dir As DirectoryInfo= New DirectoryInfo(path)  Dim themes As NewStringCollection For Each di AsDirectoryInfo In dir.GetDirectories()   themes.Add(di.Name)  Next Return themes   End FunctionEnd ClassFigure 4: A pagethat lets users change the theme dynamically.  
Figure 5: Changing themesdynamically.  Conclusion ASP.NET themeslet developers author pages and controls that users and designers can skin atwill. Conceptually similar to Windows XP themes, ASP.NET themes can overall beseen as a superset of CSS style sheets that cover control properties inaddition to HTML element styles. Themes work well in conjunction with anotherhot new feature of ASP.NET 2.0 the user profile API. Using both, developerscan let end users choose the theme and persist its name back to thepersonalization storage layer so that the proper theme will be applied as theuser reconnects. Incorporating superior functions in ASP.NET pages has never been this easy.   C# and VB.NET samplecode accompanying this article is available for download.  Dino Esposito is atrainer and consultant who specializes in ASP.NET and ADO.NET. Author of Programming Microsoft ASP.NET and Introducing ASP.NET 2.0, both from MicrosoftPress, Dino also helped several companies architect and build effectiveproducts for ASP.NET developers. Dino is the cofounder of http://www.DotNet2TheMax.com, apopular portal for .NET programmers. Write to him at mailto:[email protected] or join theblog at http://weblogs.asp.net/despos.      

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like