Building a Better Sidebar
When I first heard about .NET’s user controls I thought, “What’s this? A proprietary format for include files?” I argued with a colleague about this newest offering from Microsoft, dismissing user controls as some sort of hype from Redmond.
Little did I know that not only would I deploy user controls in my daily design work, I’ve grown to love them.
Include files, for those of you not in the know, were snippets’ of HTML or .ASP code that were used as header or footer files or anywhere that code repeated. These include files encapsulated common code, like a copyright warning or a login area – something that was repeated on many pages in a web application. Most hardcore developers have used include files before, so you’ll be able to appreciate what .NET brings to the table with their new user controls.
Simply put, a user control is exactly the same as an include file, except you get the power of a code-behind and great features that the .NET framework provides – like caching, events and properties.
Where I’ve found user controls extremely useful is in sidebars, where I have some sort of content that is small in size and concentrated in functionality. For example, on my site, tiberi.us, I have a user control for my What’s the Buzz’ column – I’ve consolidated what would have been an include file in ASP 3.0 into a self-contained user control, which I can easily design in VS .NET. We’ll take a look at the code and some design issues later on in this article, but first, let’s take a peek at what User Controls can offer the .NET developer:
A programmer gets sick of writing the same code again, or worse yet, doing a search and replace on every page when some critical information changes. Typically, if you weren’t using an include file, or if you’re just a glutton for punishment, you’ve gone through this ugly process.
User Controls in .NET really free up your time for real development, rather than laboriously recoding or doing a search and replace just because some yahoo in marketing screwed up on the site’s legal footer.
User Control Properties
If you’re trying to ensure you’re not making the same mistakes that you did with include files, like hard-coding your database connection string – You can look into providing properties for your user control that you set on the page that’s slaved the user control. The nice thing about user control properties is that you can set them at run time – similar to any server or ActiveX control.
You can set the property of a user control in the calling page by passing in the property name and a value as a parameter when declaring the user control on the page.
To make your pages and your user controls more extensible, you should provide properties that can be set at run-time – resulting in cleaner code and less distribution nightmares. Try to avoid hard-coding any property that might change – especially when coding for the enterprise.
One of the really great benefits of ASP.NET is the ability to cache a page or control, which ultimately means less processing overhead for IIS. Instead of dynamically dishing up content every time an end user requests a page, IIS caches the output in memory and dumps out that cached content when requested. Caching really comes in handy when you’re doing something intensive, like a database query. If needed, entire pages can be cached and dished up to end-users, effectively turning a dynamic page into a static page. For the purposes of our sidebar, we only need to cache our small control – this technique is known as fragment caching. Fragment caching is very slick and allows pieces of your page to be cached for a certain time period while leaving other pieces to be dynamically created.
Because our sidebar content only changes a few times a week, we could consider caching it once a day, but that’s not really good design. You might work odd hours and make an update at midnight and then one at six in the morning, so caching only once per day won’t cut it. For our purposes, none of the information we’re caching is critical, so we’ll just go for a once an hour caching strategy. Deciding when our page or control should be cached is called a caching policy. There are a few different strategies to consider when you cache your page – we can even write our caching policy around whether a file changes on our server.
We’ll implement our fragment caching by declaring using the OutputCache directive:
The Duration attribute sets the amount of time we’d like to cache the control in seconds, so if you want to cache your user control for 2 minutes, you’d set the duration to 120. In this case, I’m setting my duration to 3600, which is an hour for you math geniuses out there. Be sure and consider the right amount of time to cache your user controls – too little and you could affect performance and scalability, too much and you’re starving out needed content your end user is hungry for.
The VaryByParam attribute allows you to cache based on GET/POST parameters. It is a required attribute – here we’ll set it to none’, because we don’t really need to cache based on different parameters passed in from a querystring. Truthfully, the VaryByParam is very slick – it allows you to cache any page dynamically created from a querystring and subsequent requests using the same querystring parameter will get the cached version.
For example the directive:
would cache any page requested by a URL passed into a site with the querystring code’.
Finally, you can separate all of your GET/POST parameters with a semi-colon – all of these requests would be cached as well until the duration expires.
We’ve only touched upon the most common uses of fragment caching – I suggest that if you’re going to use caching, you should really read up on the capabilities of this most powerful new tool in the developer’s arsenal.
Building a better Sidebar
The sidebar on tiberi.us is a very simple yet flexible control that relies on XSLT Processing, an XML file that contains the content, and an XSL file that tells the sidebar how the most of the content should look’ to the end user. I felt that this strategy provided a little bit more control as I tweaked the look and feel of my site – if I needed to add or take away sections, I could do so by changing the XML and/or the XSL file – no need to add fields to a database or hardcode the “look and feel” of the side bar in HTML. This actually was very handy as I was putting together my site. I originally had the sidebar on the left side of my page, and was dissatisfied with its position – so I just dragged it from the left side to the right side, tweaked my layout in the XSL file, and my site was instantly updated. If I make the decision to change what the layout of my sidebar looks like today, I’ll just change the XSL file and instantly my site will reflect those changes.
Hard content vs. Soft content
In my side bar, I’ve cheated a bit and provided some information that I know won’t change in the actual user control, rather than placing it within the XML file. Not everything needs to be so dynamic – I do have some information that won’t change, like my contact information for my web site. This is pretty typical, most sites have content that WON’T change no matter what – just be sure to use your head and place what is typically soft content in your XML file and go ahead and place the hard content that won’t change wherever it is needed.
XML vs. Databases
So, why would you use XML rather than SQL Server? For one thing, Cost. Last time I checked, SQL Server costs a bundle. Even if you DO have access to SQL Server, you should look at how scalable your sidebar would be with intensive queries.
All in all, it comes down to performance. Database access is usually the bottleneck when it comes to performance in most web applications. I’m not saying don’t use databases, on the contrary, I’m saying use them wisely and only where XML couldn’t do a better job. I’d offload as much of my static’ content to XML and let SQL Server do the heavy lifting when needed – like performing a search or serving up dynamic content.
The really nice thing that .NET brings to web development is the ability to treat an XML file as a de facto database. While it’s true that you don’t get the security and integrity that a database can provide – with an XML file, you do get the benefits of queries and access to data without the overhead of network connections and costly software purchases.
Another sweet benefit of having content in XML is that once you know the tags that make up your XML document, authoring new content is a breeze. Although this may seem like overkill if you are the only person writing the content, believe me, with a myriad of authors on the road and no database connection, you’d be in some real trouble come deadline. Enabling the authors of content to write it wherever they want without being connected to a data entry screen is real distributed power.
For example, the XML structure that describes a story on my sidebar looks like this:
It’s pretty easy for someone with almost no experience in authoring for the web to write content. There’s no need for your authors to know more than just the basics of HTML – which can be accomplished in a few short hours.
Now that we’ve gotten a lot of the overview out of the way, it’s time to delve into the code. While it may seem like there is a lot of code to do something so simple, it’s really an issue of design and scalability vs. hard coded incompetence.
I won’t show you all the gory details of how my ASPX page is formatted; however, we need to see how I’m slaving in my User Control on the page:
First off, I’m telling the ASPX page that we’ll be using the sidebar User Control by completing the REGISTER directive:
It can’t be that easy, can it? Well, not quite. We still need to tell the page where we want our User Control to sit.
It’s pretty simple to prepare a page for a User Control – just make sure that you’ve registered the control on your page and then make a reference to that control wherever your layout needs it placed.
Let’s take a look at the actual sidebar.ascx file:
That’s pretty much it. Design-wise, I’ve kept the complexity down to a minimum, relying on the XML and XSL to provide most of the formatting, while slaving in the XSLT Processing inside a simple HTML table. Notice that I’ve provided some hard content in my User Control – the gifs and the contact information. I didn’t feel that these needed to by dynamic – my contact information isn’t going to change and if I really needed to change my gif I could do so in seconds.
Notice the OutputCache directive at the top of the ASCX page – I’m caching my sidebar for 3600 seconds That way, I can really reduce the amount of I/O the server has to perform, chugging away at reading and transforming XML, to once per hour. Again, my content isn’t going to change all that much and if my end user has to wait an hour to read my smarmy comments, that’s just too bad!
Looking at the sidebar User Control, you’ll notice a call to a function named TransformXML, this is where we transform the plain vanilla XML into what content you actually see in the sidebar – so, let’s take a look at the sidebar’s code behind and what’s going on in there.
Of course, the real meal deal is the TransformXML function. What we’re passing in here is the actual URL for the XML and XSL files, respectively. .NET fires up an XMLTextReader object and the XSLTransform object and does all the hard work for you. The resultant string is then passed back to the calling User Control and a Response.Write is issued, dumping the transformed XML into the sidebar.
Here’s the edited XML file in all its glory – I’ve omitted all of the stories but one
The XSL file contains the look and feel’ of the sidebar. If you’re not familiar with XSL, watch out, it’s the pickiest language out there.
That about wraps up our look at User Controls – keep in mind that when you’re designing components for your pages, try to design for effective scalability and re-use.
First appeared at Tiberi.us
Tiberius OsBurn is a freelance technology author and speaker based in Omaha,
Nebraska. His book, “Hardcore Development”, will be released in the summer
of 2003. Mr. OsBurn has extensive experience in VB, VB.NET, C#, SQL Server,
ASP.NET and various other web technologies. Be sure to visit his site,
http://www.tiberi.us, for his latest articles of interest to .NET developers.