Mine the Starter Kits
Customize and extend Microsoft’s free apps.
October 30, 2009
asp:feature
LANGUAGES: C#
TECHNOLOGIES: User Controls | HttpModules
Mine the Starter Kits
Customize and extend Microsoft's free apps.
By Brian Noyes
In this article and in two more features planned for thenext two issues of asp.netPRO, I'll take you on a mining expedition ofthe ASP.NET Starter Kits. The goal is to get you deep into the code andaccelerate your ability to reuse and extend the applications. I'll focus on themost interesting parts of the design and code, and I'll introduce ways to integrate,re-create, or extend the capabilities of each kit for your own Webapplications. In this article, I'll kick off the discussion by focusing on theCommunity Starter Kit, which demonstrates a unique approach to building dynamiccontent-driven and collaborative Web sites.
Develop a Sense of Community
The Community Starter Kit presents a way to build a Webapplication that exploits some of ASP.NET's best and newest capabilities. Thekit demonstrates a collaborative, community-oriented Web site where users canread articles, download files, view images, learn about events, and accessother types of informational content (see Figure 1). Users also can participatein the site by uploading files, participating in discussions, adding their ownarticles, and rating and commenting on content added by others. The kitincludes authentication to enforce access controls, and it provides asophisticated administrative interface for configurable customization of allthe site's aspects. It also includes separate controls that let ISPs set up andmanage multiple communities on a server from a single management interface.
Figure 1. Here is the Community Starter Kit home page. The kitdemonstrates a collaborative Web space you can reuse, adapt, or extend for yourown Web applications.
Great. So that's what it provides at the user/providerlevel. But what about you, the developer - what is here for you? The firstthing you might notice when you start looking at the Community Starter Kit isit really has only one .aspx page, which has no content on it at all. How canthat be? Well, the site is built based completely on an extensible anddynamically data-driven architecture. That ought to catch your developmentmanager's attention, right? It's pretty cool, if a bit complex to decipher atfirst. Basically, the site consists of an HTTP module; a single ASP.NET pageimplemented entirely in the codebehind; a framework of classes representing thecodebehind of all the controls that comprise the site; a set of themes thatprovide the HTML and ASP.NET control tags for those controls; and a database tostore and provide content.
It all gels together like this. An HTTP module namedCommunityModule intercepts every request that comes in to the site. The moduleparses out the requested URL to break it into information that determines whatcommunity, section, and page the user is requesting, and it also extracts theuser identity for authentication and authorization purposes. Then, it stuffsall this information into the SectionInfo, PageInfo, and UserInfo classes,which the module puts into the HttpContext object's Items collection so theclasses are accessible to any classes that get called further down the HTTPpipeline. The module then simply calls the one and only .aspx page in the application,communityDefault.aspx (see Figure 2). (By the way, there also is acommunityDefault.asmx page, which lets you expose capabilities from your siteas Web services, all using the same starter kit architecture.)
Figure 2. All requests processed by the Community Starter Kit areintercepted by the CommunityModule HTTP module and rewritten to thecommunityDefault.aspx page. The codebehind in that page builds the pagedynamically using a combination of static HTML, user controls, and data.
Once the request is transferred to communityDefault.aspx,the page's codebehind constructs the page returned to the user on the fly basedon a combination of hard-coded HTML tags, user controls (.ascx files), and datafrom a database. The results of this construction process are sent back to theuser in the response, and they are unaware that what they see is generateddynamically with no real, corresponding "page."
The other feature the site uses for extensibility andcustomization is the concept of "skins," which let you define your own look andfeel as a theme. Skins provide a set of .ascx files containing the HTML andASP.NET control tags that map to code-behind classes defined as part of thestarter kit class library. For example, one of the main sections (think "pagetypes") provided in the kit is a discussion area. The functionality of thediscussion thread is based on a set of classes defined in the kit that derivefrom WebControl. These classes load the .ascx files dynamically to determinethe layout, and they expect tags to be present with particular IDs in the .ascxfile they're tied to. To create a new theme, you simply define the .ascx filethat contains appropriate HTML and/or ASP.NET server controls with thosecontrol IDs.
Step Out on Your Own
The Community Starter Kit provides several ways to enhanceyour site or build one from the ground up. The first is that you could take thesite exactly as it is, then customize the existing look and feel, graphics, andcontent to create your community site without writing a single line of code.(See the whitepaper for information on how to do this.)
But you likely will want to incorporate some, perhaps notall, of the kit's capabilities into an existing Web site. Or, you might want toadd new functionality using the same dynamic construction approach. So let'slook into several forms of extending the starter kit for your own purposes.
First, I will cover one of the simplest ways to extend thekit: Adding a new theme to the site so you can change the look and feel. Then,I'll briefly discuss how to add the Community Starter Kit to an existing sitewithout disturbing your existing site architecture and pages. Finally, I'llshow you how to add new functionality and controls to the starter kit, usingthe existing class library and request processing.
When you implement a new theme, you don't have toimplement skin .ascx files for every single type of module defined in the kityou plan to include in your pages. If your theme fails to define a skin for acontrol, it will inherit the skin from the default theme.
To create a bare-bones theme, create a new folder underthe Themes folder with the name of your new theme (for example, MyTheme). Thencreate a subfolder structure (see Figure 3). In the MyThemeSkinsPageSkinsfolder, create a Default.ascx file as an empty file and add to it the codeshown in Figure 4.
Figure 3. This is the folder structure for a theme. If skin .ascx filesfor each type of control are not found by the kit in your defined theme, thefiles from the default theme will be inherited and used instead. This allowsyou to define a new theme incrementally.
<%@ import Namespace="ASPNET.StarterKit.Communities"%>
<%@ Register TagPrefix="community"
Namespace="ASPNET.StarterKit.Communities"
Assembly="ASPNET.StarterKit.Communities"%>
<%@ Control Language="C#" %>
Welcome to my site
Runat="Server" ID="Userlogin1" />
Figure 4. Implement a minimal skin by defining thecode shown as the Default.ascx file in a custom theme. Then you can startcreating your own look and feel and layout for the starter kit's built-incapabilities.
To define your skin, simply start adding HTML and ASP.NETserver control tags to the page to define the look and feel. Without modifyingthe kit's base classes, only one ASP.NET server control is absolutely required:an Image control with an ID of "Logo". You'll also need to include, however,the UserLogin and Content PlaceHolder controls, or else you will have no way tolog in and access the Administrative pages that let you customize the site. TheUserLogin control assumes the presence of the Content PlaceHolder control topresent the login controls, so those two go hand in hand.
The CommunityDefault base class also looks for servercontrols with IDs of content, txtSearch, lnkSearch, and Footer. Beyond that,you may add to the Default.ascx file any HTML content or server controls youwish. The page skin represents the overall layout of a page; most of thesystem's skins are located in the ContentSkins folder and correspond to each ofthe different section types of content that can be presented in the maincontent area of the page (for example, discussions, photos, books, events, andso on).
The process is similar for customizing other skins -locate the class that implements the codebehind of the control to which youwant to add a new skin, then define the .ascx code in your Theme folderscorresponding to the controls the codebehind will seek. Determining whichcontrols are required and where the corresponding codebehind class is locatedin the EngineFramework classes can take some digging. Use the existing themesand their skin definitions to identify the control IDs defined in a particularcontrol for which you want to create a skin, then use VS .NET to search for thecontrol IDs declared in the codebehind classes under the EngineFrameworkfolders.
Integrate a Community
Using the Community Starter Kit's built-in capabilities toadd community functionality to an existing Web site is a piece of cake - andyou don't have to modify the Web site one bit. You either can install the kitand start adding references to the URLs defined for the kit to pages withinyour Web site, or you can create another virtual directory as a subfolder ofyour site pointing to the starter kit's root folder. (Note that you probablywill need to create a custom theme to make the kit pages look like they arepart of your site.)
Finally, you might want to create a new type of control ormodule that uses the same dynamic construction process the starter kitprovides. To do this, you need to implement a class that represents thecodebehind for the control that will present your new functionality, which willneed to derive from the starter kit's SkinnedCommunityControl base class. Youneed to create a skin (an .ascx file) that provides the layout and presentationof that new functionality using HTML and ASP.NET server control tags. Then youneed to make some database entries to make the new functionality accessiblefrom the existing site. Note that the whitepaper documentation refers to addingnew pages or controls in this fashion as "Creating New Modules." Be aware thatthe documentation uses the term "module" in a general sense - this does notrefer to adding new HTTP modules to the application.
As an example, you can implement a survey page that asks areader to complete a survey about the site. The survey presents a series ofquestions stored in the database, allows the reader to answer those questions,and thanks them for their input. A real implementation of this functionalitywould probably store the results in the database when they are submitted andoffer a summary page that shows cumulative survey results. To implement thissample functionality, create two new content controls - one for presenting thesurvey and one for presenting the completion page to the user.
Figure 5 shows a skeletal implementation of the UserSurveyclass, derived from SkinnedCommunityControl. Once the implementation of themethods is filled in, you need to create a corresponding skin that lays out thetags corresponding to the controls defined in the control class. If the controluses a container control such as Repeater (as does this example), the skin alsowill need to ensure the contained controls are defined. In the case of theUserSurvey sample, this includes defining an ItemTemplate that contains a Labelcontrol, named lblQuestion, and five RadioButton controls, named rb1 throughrb5. This article's downloadable sample code simply populates the control withsome statically coded questions defined in the control itself. A second controlis defined in a similar fashion for presenting the user with a "Thank You"message after they have submitted their survey. In a real-world implementation,you also would want to force the user to log in before accessing the surveypage, and you probably would pull the questions from the database. See thestarter kit modules code for accessing the Book page from the Book Listing pagefor an example of how to force the authentication within the starter kitclasses.
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using ASPNET.StarterKit.Communities;
namespace ASPNET.StarterKit.Communities.UserSurvey
{
public class UserSurvey: SkinnedCommunityControl
{
// Declare the skin.ascx file that
// defines the layoutfor this control
string skinFileName ="UserSurvey_UserSurvey.ascx";
// Declare thecontrols that this uses in the skin
Button btnSubmit;
Repeater rptQuestions;
Label lblSummary;
TextBox txtComments;
public UserSurvey() :base()
{
// Assign a defaultskin filename
if (SkinFileName ==null)
SkinFileName =skinFileName;
}
override protectedstring SkinType
{
// Tell theframework what kind of control this is
get { return"ContentSkins"; }
}
override protectedvoid InitializeSkin(Control skin)
{
// Use SkinnedCommunityControl.GetControlto locate
// expected controlsand connect to member control
// references, thenset their values
}
protected overridevoid OnLoad(EventArgs e)
{
// Initialize membervariables from DB or other source
}
}
}
Figure 5. To create a control you can plug in as a newmodule in the Community Starter Kit, you need to create a class derived fromSkinnedCommunityControl, override some of the base class methods andproperties, and provide a corresponding skin .ascx file.
Once the classes and their corresponding skin .ascx filesare defined, you need to add them to the code base for the starter kit andrecompile it. I added them as a new folder, named Survey, under the Modulesfolder in the starter kit's Engine section. The code is going to resolve theclasses at run time based on namespace, so where they are in the folderstructure is important only for project-management purposes. You then must addsome entries to the database so you can add a section for the survey. To dothis, add a row to the Community_PageTypes table that added the UserSurveycontrol as a new Section page type, then add a row to the Community_NamedPagestable to add the SurveyThanks control as a new named page type. (You can find aSQL script to run in Query Analyzer to add these rows in this article's codedownload.) Finally, to present the survey as part of the site, you must log inas Administrator, go to the Edit Sections interface, and add the Survey as anew section so it is presented in the top-level menu. The readme file includedin this article's code download details all the steps necessary to integratethe code.
Now you know how to start using the Community Starter Kitto implement collaborative functionality on your site and present dynamicallygenerated content. Get the sample code and go through the exercise of addingthe survey control to the starter kit to get a better idea of how this allcomes together. Up next: The Reports Starter Kit, which demonstrates severaltechniques for building Web-based reporting applications, including graphicaland tabular reports of many forms.
The sample code in thisarticle is available for download.
Brian Noyes is an independent software consultant,writer, trainer, and president of Software Insight (http://www.softinsight.com). He'san MCSD with more than 12 years of programming, design, and engineeringexperience. Brian specializes in architecture, design, and coding ofcutting-edge software systems, and he is a contributing editor for asp.netPRO andother publications. E-mail him at mailto:[email protected].
Explore the Starter Kits
ASP.NET provides a development platform for building complexWeb applications and services that is easy to learn and use. The sample codeand snippets that comprise the framework's SDK documentation can take you onlyso far, however, in building real-world applications. To build enterprise-classWeb apps, you usually need more complex samples that not only demonstratespecific coding techniques, but that also demonstrate Web applicationarchitectures and design patterns you can adopt and reuse in your owndevelopment.
Most ASP.NET developers are familiar with the IBuySpystore and portal sample applications that became available with the release ofthe .NET Framework SDK 1.0, and many companies used these sample sites as atemplate for building their own apps. With the release of ASP.NET 1.1, a wholeset of new ASP.NET Starter Kits will be released that demonstrate manydifferent techniques, architectures, and designs that potentially can save youhundreds of hours of development time. The starter kits are available in betaform now at http://www.asp.netand work fine with version 1.0 of the framework as well.
Each kit comes with full source code and some whitepaperdocumentation to get started on your own. They also each come in SDK and VS.NET versions - the former favors no codebehind, while the latter usescodebehind and includes VS .NET projects to manage and explore the code. Theyeach come in VB .NET and C# variants as well. Each kit demonstrates a differentkind of Web application with a fully functional and fictional purpose. They aredesigned so you can reuse them in multiple ways, including direct modificationof the kit's content to create your specific application, addition of newcapabilities or content based on the framework the starter kit provides, orextraction of code portions to integrate into your own Web application codebase.
Five starter kits currently are available. The CommunityStarter Kit demonstrates a unique approach to building and managing an onlinecollaborative environment using dynamic content, including discussion threads,articles, events, downloads, and the ability for users to comment and ratecontent on the site. The Reports Starter Kit shows you how to create a sitethat provides graphical and tabular reporting content for online analysis andviewing of your business data. The Time Tracker Starter Kit demonstrates aWeb-based time-management application for tracking project hours from normalbrowsers or mobile devices. Finally, the Portal and Commerce starter kitsclosely model the IBuySpy portal and store, respectively, but they have beenmodified and made more generic for direct reuse in your applications.
Practice What You Preach
Using the Community Starter Kit to create acommunity-based site is not simply a concept; the Capital Area .NET User'sGroup (http://www.caparea.net)is actually doing it (see Figure A).Scott Lock, Alex Minor, Hal Hayes, and I are completely rebuilding the group'ssite using the Community Starter Kit.
Figure A. Here is the home page for the Capital Area .NET User's Group,which is using the Community Starter Kit to create a real-world community site.The look and feel of this site was created by adding real content to one of thekit's existing themes.
Rather than building a theme from scratch, we started withone of the existing themes ("Eco" to be exact), and modified copies of theexisting skin files to achieve the look and feel for the site we wanted. Fromthere, we simply used the built-in administration interfaces to expel all thesample site content and modules and replaced the content with informationmigrated from the existing site. This was all done in under 12 hours.
We also will create a couple of new Web Boxes. Web Boxessimply are user controls (.ascx files) displayed by the WebBoxList control inthe kit wherever you place it in your page layout (the right margin in thedefault theme). We will use these for gathering input from users on meetingevaluations and suggested speaker topics. Eventually, we might add some custommodules for other purposes as well. After familiarizing ourselves with theCommunity Starter Kit, we found it would be perfect for what we need to do, andthe out-of-the-box functionality it delivers is more than a head-start onsetting up a site like this - the kit creators have run most of the race foryou.
Tell us what you think! Please sendany comments about this article to [email protected] include the article title and author.
About the Author
You May Also Like