Playing in the ASP.NET Sandbox
The RSS Toolkit and CSS-friendly Control Adapters
October 30, 2009
LANGUAGES: VB.NET
ASP.NET VERSIONS: 2.0
Since the release of .NET 2.0, the ASP.NET team has beenchurning out add-ins to be used with ASP.NET 2.0 and Visual Studio 2005. Whilesome are fully supported, like the Web Application Project (created to appeasefrustrated developers moving from ASP.NET 1.x), and others, such as Atlas, area peek into the not-so-distant future of ASP.NET, another set represents thingsthat team members have been exploring. All of these can be found in the Sandboxarea of the official ASP.NET Web site at http://www.asp.net/downloads/teamprojects.
In this article I ll provide a quick overview of two ofthese tools: the RSS Toolkit and the CSS-friendly Control Adapters.
RSS Toolkit
In February, ASP.NET team member Dmitry Robsman published onhis blog the RSS Toolkit for ASP.NET 2.0. This was followed by a tutorial byScott Guthrie on how to use it. In late March, the toolkit was tweaked based onfeedback from users.
The RSS Toolkit simplifies embedding RSS feeds into your Webpages. Many people had been coming up with their own solutions, so it madesense to have something that could eventually be a standard part of ASP.NET.The toolkit provides an RssDataSource component that can be bound to theASP.NET data controls. Figure 1 shows the RssDataSource control added to thetoolbar, along with the RssHyperLink control (explained later in this article).
Figure 1: Add the RssDataSource andRssHyperLink components to the toolbar if you wish to use them on the designsurface of your Web page.
The Toolkit can be placed into the GAC for use with manyprojects/sites, or added individually to a project via Add References. Withjust a few steps you can quickly place an RSS feed on your Web page:
1) Adda data bound control (such as DataList) to your page.
2) Choosethe RssDataSource icon in the Select DataSource Wizard.
3) Enterthe URL of an RSS.
4) Editthe DataList template to show the post title with hyperlink (details to follow).
5) Setthe MaxItems property of the RssDataSource so that the selected feed doesn toverwhelm your Web page or your resources if it happens to expose a large numberof items.
Step 4 is important. By default, the DataList will showall the elements of the RSS feed; if you try to run the site at this point, you llget an exception that says RssToolkit.RssElementCustomTypeDescriptor does notallow indexed access. As per Dmitry s ReadMe file instructions, you need toremove all those default fields and add the Title and URL fields. This caneither be done manually in HTML or by dragging a HyperLink control into theEdit Template window, then configuring the HyperLink s DataBindings, as shownin Figure 2.
Figure 2: After hooking up a Datacontrol to an RssDataSource with the feed configured, you can easily configureyour control by adding a HyperLink control and then setting the Text andNavigateURL properties with this handy ASP.NET DataBindings wizard (by rightclicking on the HyperLink control).
The resulting HTML will look like this:
NavigateUrl='<%#Eval("link") %>' Text='<%#Eval("title") %>'> There is another control, RssHyperLink, which lets youeasily expose your own RSS feed. It requires creating an HttpHandler thatderives from RssDataSource.GenericRssHttpHandlerBase and programmaticallycreating and populating the feed items. For example, you could create a feed byiterating through a DataReader or XML file populated with company news items.Or you could create a feed that contains links to pages in your Web site. Figure3 shows a VB code listing for a handler that exposes key pages of theVermont.NET User Group Web site. The NewItem function takes the link and titleinformation and creates a new Channel Item for the feed. The example createsthree such Channel Items. <%@ WebHandler Language="VB"Class="VTdotNETRSS" %> Imports SystemImports System.WebImports RssToolkitPublic Class VTdotNETRSS InheritsGenericRssHttpHandlerBase Protected Overrides SubPopulateChannel _ (ByVal channelName AsString, ByVal userName As String) Channel("title") ="VTdotNETLinks" Channel("link") = "http:/www.vtdotnet.org" Channel("description") = _ "ImportantPages in the Vermont.NET web site" Channel.Items.Add(NewItem("Upcoming Meetings", _ "http://www.vtdotnet.org/nextmeeting.aspx", _ "All futurescheduled meetings and directions")) Channel.Items.Add(NewItem("Past Meetings", _ "http://www.vtdotnet.org/past_meetings.aspx", _ "All previousmeetings and related resources")) Channel.Items.Add(NewItem("BookReviews", _ "http://www.vtdotnet.org/bookreviews.aspx", _ "Member bookreviews")) End Sub Private FunctionNewItem(ByVal title As String, _ ByVal link As String,ByVal description As String) _ As GenericRssElement Dim item As NewGenericRssElement item("title") = title item("description") = description item("link") = link Return item End FunctionEnd ClassFigure 3: Exposingkey pages of a user group s Web site. Given that this is all in a file called VTdotNETRSS.ashx,anytime someone browses to that file, they will get the response shown inFigure 4.
Figure 4: The RSS feed exposed bythe VTdotNETRSS feed. The RssHyperLink control simplifies exposing this feed onyour Web pages. In addition to the properties of a HyperLink control, it has afew other properties that are relevant to an RSS feed, such as ChannelName.Drop an RssHyperLink onto a page in your site, set the NavigateURL property toyour RssHttp handler, and, after setting some other key properties, such asChannelName and Text, visitors to your site can easily subscribe to your feed. There is much more to the toolkit than the servercontrols. The API exposes a lot of functionality that you can tap into in yourcode. The ReadMe file that comes with the toolkit lists examples for manyscenarios to get you started with the toolkit. In addition to using theRssDataSource control, there are samples for consuming feeds usingObjectDataSource, strongly typed classes, or late-bound classes. An important feature of the toolkit that is not to beoverlooked is the ability to persist feed results through memory and diskcaching. The RssDataSource first looks for the feed in memory. If it is notavailable, or has expired (based on the defaultRssTtl setting in web.config ora default of 1 minute), it will then check to see if you are using the optionaldisk caching (designated by another web.config setting called rssTempDir). Ifthat file does not exist or is expired, then it will go out to the actual URLand pull in the feed. After refreshing the feed, the RssDataSource will persistit into the memory cache and (if appropriate) the disk cache. If using diskcaching, be sure that you are using a folder which your application haspermissions to read. Check Dmitry s note in the RssToolkit.doc about trustlevels with respect to the RSS Toolkit. I hope to see this toolkit continue to evolve and someday becomea first-class citizen in ASP.NET. CSS-friendly Control Adapters CSS (Cascading Style Sheets) is the chosen formattingmethod for professional Web designers. Most of the rest of us are used todesigning our Web pages by using tables as our building blocks. Many of the Webserver controls (such as DataLists and GridViews) are rendered by ASP.NET astables, an HTML element that does not work well with CSS. As a way of showcasing the very powerful ASP.NET 2.0System.Web.UI.Adapters.ControlAdapters, the team has created a toolkit ofControl Adapters that will adapt five Web server controls (TreeView, Menu,DetailsView, FormView, and DataList) and render them in HTML that is morecompatible with CSS. In most cases, this is div tags and List Items ().Note that in the case of the DataList adapter, the HTML does render tables, but uses , , and sections to simplify the use of CSS. Although I recommend that you have some working knowledgeof CSS and the new Themes and Skins in ASP.NET 2.0 before digging too deeplyinto the Control Adapters, I had minimal CSS experience (with a great desire togain more) and had never even touched Themes and Skins. This made the time ittook me to get up to speed with these Control Adapters a little longer thanthey may otherwise have required, but the learning curve was well worth theeffort. In hindsight, I realize it would have been simpler had I had some priorknowledge of these tools, but it was certainly possible. If you have ever looked at the source for a page with Webserver controls on it, you would have seen that the HTML does not match theHTML in your UI designer. In design mode, you might have code such as or , but these are nowhere to be found in the HTML that isrendered to the Web browser. ASP.NET processes your page and, based on thecontent, renders HTML code. Therefore, where you have an ,ASP.NET (by default) will output an HTML table. What the Control Adapters do isallow you to replace ASP.NET s default rendering with something of your owndesign. In the case of the examples in this toolkit, the adapters will takeover when it comes to rendering the five controls noted above. In fact, theconfiguration is browser specific, which means you can specify differentrenderings for different Web browsers. The key elements of this kit are: 1) CSSAdapters.dll.This assembly has the rendering instructions for each of the five adapters. Thesource is available, which means you can use it to learn more about creatingyour own Control Adapters. The basic concept is that the Adapter classes rendertheir own HTML with an HtmlTextWriter. 2) AppBrowsers folder. This contains the CssFriendly.browser file. It is an XML fileused to configure, on a browser by browser basis, which Web server controls getadapted and which adapter is used. Figure 5 shows an example of theconfiguration for IE. In my case, I am only using Adapters for TreeView andDataList, so I have commented out the other three replacements. CSSFriendly isthe namespace of classes in the CSSAdapters assembly. 3) BrowserSpecificCSSfolder. This contains individual CSS files that supplement CSS rules for aspecific browser and control. For example, the IEMenu.CSS file would be used todefine additional formatting specifically for Menu controls in InternetExplorer. This would be used to supplement the general CSS rules for a Menu. 4) AdapterJavaScript files. These files (AdapterUtils.js, TreeViewAdapter.js,MenuAdapter.js, etc.) contain script that is used by the adapters. They willhandle things like expanding and collapsing TreeView nodes in response to clickevents. adapterType="CSSFriendly.TreeViewAdapter" /> adapterType="CSSFriendly.DataListAdapter" /> Figure 5: TheCssFriendly.browser file configured for IE. Defining the Adapters When you design your Web page, you ll use the standard Webcontrols, such as TreeView. With no more work than that, you ll already noticethe difference in rendering. Note that every TreeView in the project will get adapted.An alternative measure would be to create a custom TreeView control thatinherits from TreeView and, instead of setting controlType toSystem.Web.UI.WebConrols.TreeView, set it to your own TreeView class. Figure 6 shows a page in design mode with a TreeViewcontrol on it that has not had any CSS applied. Figure 7 shows a portion of thesource of the rendered page. It s pretty messy stuff, but I have highlighted afew of the , , and tags for quickidentification. Figure 8 shows the same tree rendered with the Control Adapter.For starters, it s much easier on the eyes. The combination of (ListItem) and tags will be much simpler to format with CSS.
Figure 6: A TreeView in design modewith no formatting.
Figure 7: The default rendering fora TreeView is done with divs and tables.
Figure 8: The same TreeView renderedby the Control Adapter is built with List Item and span elements, which can beeasily formatted with CSS. (CSS has not been applied to this TreeView yet.) Now it s time to apply some styles with CSS. The key tothis is the CssSelectorClass attribute that is added to TreeViewControl. Thesample code that comes with the toolkit uses a CssSelectorClass named PrettyTree.Here is how the puzzle fits together. In the HTML for the TreeView, set the CssSelectorClassattribute. Note that IntelliSense will complain about this attribute becausethis is a custom attribute: CssSelectorClass="PrettyTree"> This is where ASP.NET 2.0 Themes comes into play. Themesare organized in folders by theme name. In the folder that will be used for theWeb site pages, a CSS file is required for each of the controls to be adapted;for example, TreeView.css or DataList.css. There are sample files provided withthe toolkit. Within the CSS file, notice the pattern for each style rule:CSSClassName, Class to be styled, element(s) to be styled. Following are a fewexamples. This first example defines the PrettyTree CssSelectorClassthat is to be used for AspNet TreeView controls. Any hyperlink (a) inside of alist item (li) should be black and not decorated: .PrettyTree div.AspNet-TreeView li a{ text-decoration: none; color:Black; } In the second example, shown in Figure 9, the instructionsare to apply the style to any root, parent, or leaf nodes inside of a list itemof an AspNet TreeView that has the CssSelectorClass named PrettyTree. To besure my CSS is working, I selected Purple for Root nodes, Green for Parentnodes, and left the innermost nodes (Leaf nodes) Black.
Figure 9: Apply the style to anyroot, parent, or leaf nodes inside of a list item of an AspNet TreeView thathas the CssSelectorClass named PrettyTree. I also used CSS to define the gifs used to visualizeexpand and collapse in the TreeView. Figure 10 shows the TreeView rendered bythe adapter after applying the PrettyTree CSS class.
Figure 10: The TreeView after beingrendered by the Control Adapter and styled with CSS. I chose to use my CSS styles in the Basic theme. Therefore,the TreeView.css file is inside the Basic folder in App_Themes. For this all towork, be sure to set either the Theme or the StyleSheetTheme property of thepage s Document object to the theme you are using; in this case, Basic . When you have defined your styles with CSS, it makes itvery easy to apply formatting to Web pages. Having HTML that works well withCSS makes the formatting much simpler, more predictable, and very flexible. TheCSS-friendly Control Adapter toolkit not only helps achieve this, but at thesame time is a great way to get your feet wet with the power of ControlAdapters in ASP.NET 2.0. There are many more projects in the Sandbox to explore. Andthe Sandbox will likely grow over time. Stay tuned. Julia Lerman is anindependent consultant and .NET Mentorwho has been designing and writing software applications for over 20 years. Shelives in Vermont where she runs the Vermont.NET User Group. Julia is well knownin the .NET community as an INETA Speaker, .NET MVP, ASPInsider, conferencespeaker, and prolific blogger. You can read Julia s blog at http://thedatafarm.com/blog.
Read more about:
MicrosoftAbout the Author
You May Also Like