Author Archive

This is the second entry in my the series of entries that I’ve devoted to answering Scott Hanselman’s ASP.NET interview questions.  The first entry covered the events fired as part of the ASP.NET Page lifecycle.

 

Alright, so here is the question: What are ASHX files?  What are HttpHandlers?  Where can they be configured?

 

And, here is the answer (to the best of my abilities): Let’s start with HttpHandlers, because that will take us into ASHX files.  In the simplest (programmatic) terms, an HttpHandler is any class that implements the System.Web.IHttpHandler interface.  OK, you might be saying, so where are they used?  Well, everywhere.  Any time a request is made to the ASP.NET worker process, the request is passed on to the HttpHandler that has been configured to handle such requests.  For example, when you go to http://localhost/default.aspx, IIS sees this request as one that should be handled by ASP.NET (more on how to configure this later) and hands it off to the worker process.  Then, by looking at the extension, ASP.NET knows to process the request using System.Web.UI.PageHandlerFactory.  Similarly, if a request is made to retrieve the web.config file, ASP.NET knows to process the page using System.Web.HttpForbiddenHandler.  In fact, if you open up the machine.config file, you should see several recognizable page extensions and the HttpHandlers that are responsible for each:

<add verb="*" path="*.aspx" type="System.Web.UI.PageHandlerFactory" />
<
add verb="*" path="*.config" type="System.Web.HttpForbiddenHandler" />
<
add verb="*" path="*.asmx" type="System.Web.Services.Protocols.WebServiceHandlerFactory" />

These recognizable extensions are provided by default in ASP.NET.  So, you can spend your entire developer career knowing nothing of HttpHandlers and still manage to create functional and successful sites.  However, to use a well known example, suppose you want to create an RSS feed to syndicate content on your site.  Sure, there are plenty of tutorials online that will help you create the XML and save it to the output stream on an ASPX page, but you want to be fancy and make it so that all of your RSS feeds end in a .rss extension.  What could you do?  Well, if you haven’t guess, HttpHandlers would be your answer.  Remember above where I said that I’d eventually show you how to instruct IIS to pass certain requests to the ASP.NET worker process?  It turns out that now would be the perfect time (if you’d like a more in-depth tutorial on how to syndicate your content using HttpHandlers, there is a great article here).

For this example, let’s assume your feed is to be posted at MyFeed.rss.  So, when this request is made to IIS, you want to make sure that the .rss extension is sent to the ASP.NET worker process.  Here is how:

Open up IIS:

image


Select "Configuration…"

image


Select "Add"

image


Use .rss as the extension and aspnet_isapi.dll as the executable (you can copy this from another extension).  I unchecked "Check that the file exists" so that the file doesn’t actually need to exist when the request is made.  Once you have this configured, IIS will now know to send all requests with a .rss extension to the ASP.NET worker process.  However, the ASP.NET process still does not know how to process the request.  This is solved by adding a few lines to the system.web section of the web.config file (similar to how *.aspx requests are defined in the machine.config file example from above):

<system.web>
  
<httpHandlers>
     
<add verb="*" path="*.rss" type="type,assemblyname" />
   </
httpHandlers>
</system.web>

Where type is the actual type and assemblyname is the actual assembly name.  To build the assembly, you would create a new class (inside of a .cs file) that implements the IHttpHandler interface and defines the ProcessRequest method and the IsReusable property.  For example:

public class YourRssHandler : IHttpHandler {
   
public void ProcessRequest(HttpContext context) {
       
//You would build the actual rss feed below
        string rssXML = "<rss>Dummy rss xml feed</rss>";
        
       
context.Response.ContentType = "text/xml";
       
context.Response.Write(rssXML);
   
}

    public bool IsReusable {
       
get {
           
return true;
       
}
   
}
}

 
Now, I have drastically oversimplified the process (as I pointed out above, there are much better tutorials elsewhere online — this post is only meant to give you the information necessary to at least be able to answer the question put forth above), but that is basically it.
 
Now that we’ve covered HttpHandlers, where do .ASHX files fit in to all of this?  Well, let’s say that you don’t want to go through all the trouble (or can’t due to your hosting provider) of setting up a custom extension in IIS and configuring them through the web.config file, but you still want to take advantage of HttpHandlers.  It turns out that ASP.NET has a build in extension for just such an occasion — .ASHX.
 
To use the same RSS example, the exact same code above could be implemented above in a .ASHX file.  The only difference would be that instead of encapsulating the code within a .cs file, you would instead create a .ashx file, and instead of the feed being fetched through MyFeed.rss, it would be fetched through MyFeed.ashx.  In this case, I’m not sure that RSS feeds are the best example for these types of files, but I have worked on several projects that have taken advantage of .ashx files to serve up images dynamically from a database.  If you’re interested, there is a great tutorial that covers that topic here.
 
That should give you a pretty good idea of how HttpHandlers and .ASHX files work.  If you have any further questions, comments are always welcome, and if you’re willing to look, there is a wealth of information on this subject available online.

Comments 2 Comments »

I’ve only been a "developer" for about two years now.  I put the term in quotations, because I don’t really count college work as development and my first job out of college was basically to occupy space.  With that being said, there are two main reasons that I got into this field: 1) I love to learn (and this field offers a never-ending supply of new material) and 2) I love to build things.  My quest to fulfill goal number one has often resulted in better results out of goal number two.

 

It wasn’t long after I was hired at my current job that I realized the wealth of information that was being disseminated through blogs, and one of my favorite bloggers has got to be Scott Hanselman.  Recently I came across some ASP.NET interview questions on Scott’s blog.  The post is a little dated (2004), but most of the questions are still relevant.  At least, they’re relevant enough that I feel bad for not being able to answer most of them.  Since I’m always up for a challenge, I thought it’d be a great learning experience to devote a series of blog entries to answering these questions.  This post shall contain my attempt at answering the first:

 

Disclaimer: I know Einstein said "The secret to creativity is knowing how to hide your sources.", but I should point out that a lot of the information contained from this point on was gathered from these two articles on MSDN: ASP.NET Page Life Cycle Overview and Page Events.

 

Question

  • From constructor to destructor (taking into consideration Dispose() and the concept of non-deterministic finalization), what events are fired as part of the ASP.NET System.Web.UI.Page lifecycle. Why are they important? What interesting things can you do at each?

 

Answer

  • PreInit Event
    • Called at the very beginning of page initialization, this event has several practical uses in your code behind pages.  A few of these uses are: Checking the IsPostBack property, dynamically setting a master page or theme property, dynamically creating controls, and reading or setting property values.  If you were so inclined, you could set a master page dynamically in the PreInit event as such:
  • Init Event
    • Called after the PreInit event and after all controls have been initialized and any skin settings have been applied, this event is very useful for initializing control properties before the page loads.
  • InitComplete Event
    • Like the name implies, this event is called after the Init event is completed.  I’m at a bit of a loss for thinking up useful and/or interesting things to do with this event, but if there were any tasks that needed to be completed once the controls were initialized, this would be the place to do it.
  • PreLoad Event
    • This event is called immediately before the Page.Load event and after all postback data has been processed.
  • Load Event
    • Probably the most familiar since it comes for free whenever you switch to the code-behind (or hit F7) on an aspx page in Visual Studio.  This event is useful for setting control properties and establishing database connections (both of which could be used to populate a drop-down from the database, for example).
  • LoadComplete Event
    • What else could possibly follow up the Load event?  This event is useful for doing any processing that requires that all controls on the page first be loaded.
  • PreRender Event
    • This event is useful for making any final changes to the page or the controls before the output is rendered to the browser.
  • PreRenderComplete Event
    • Called after PreRender is completed.  This is the last event to be called before the viewstate is saved.
  • SaveStateComplete Event
    • Called once the viewstate has been saved.  Use this for any processing that requires the viewstate to be saved but that doesn’t affect the rendering of the controls.
  • Render
    • While not technically an event, this method gets called for every control on the page.  When creating a custom control (that requires custom markup), you could override this method to provide your own markup.
  • Unload Event
    • Use this event to do any final cleanup work on the page.  Any controls on the page will also have an unload event that can be used to do cleanup on the controls themselves.
  • Disposed Event
    • This is the last event called for a control when it is released from memory on the server.  The is the last stage of the ASP.NET lifecycle when a page is requested.

 

I’m not sure that I’ve technically answered the question as thoroughly as one might need to in an interview situation, but I think I’ve provided enough information that the aspiring programmer could think of other uses for each of these events.  If you have any additional comments that others might find useful (or if I’ve missed an event or incorrectly described one), please don’t hesitate to leave them in the comments.

Comments 1 Comment »

Our main application at work was primarily built using .Net 1.1.  That being said, most of the collection objects inherit from a base class that gives support for things like adding to, removing from, and enumerating through the collection.  We have since migrated the application to .Net 2.0 but there has been little incentive to go back and update these collections to use the support for generics that was added as part of the .Net 2.0 framework.

 

Recently I took on the role of lead developer for a smaller, internal project that will live independently from any of our other apps.  The fact that this app will not use any of the business objects or the same database meant that I was free to utilize whatever technology I thought best suited for the project.  Eventually, I settled on developing the application in the newly released .Net 3.5 framework using C# 3.0 mainly due to the fact that I was anxious to start using Linq (I know, probably not the most solid reason for choosing a platform, but it is a reason, and that’s really all I needed).  When I started building up my business object layer, I eventually came across the need for collections.  The base class that was ported over from .Net 1.1 would have been more than adequate, but I knew that if I wanted to use Linq, I would have to inherit from something that implemented the IEnumerable interface.  After looking around the web and playing around with a few different methods, I eventually decided that the easiest way to build up the collection would be to inherit from the List<T> generic class (where ‘T’ is the type of object that will live in the collection).

 

Here is an example using a widget object to populate a collection of widget:

 

The widget object:

public class Widget
{
   
/// <summary>
    /// The Widget ID
    /// </summary>
    public int WidgetID { get; set; }

    /// <summary>
    /// The Widget Name
    /// </summary>
    public string WidgetName { get; set; }

    /// <summary>
    /// The default public constructor.
    /// </summary>
    /// <param name="ID">The widget ID</param>
    /// <param name="Name">The widget Name</param>
    public Widget(int ID, int Name)
   
{
       
WidgetID = ID;
       
WidgetName = Name;
   
}
}

 

The widget collection:

public class WidgetCollection : List<Widget>
{
   
/// <summary>
    /// The default public constructor.
    /// </summary>
    public WidgetCollection()
   
{
       
Reload();
   
}

    /// <summary>
    /// Load the collection.  This would normally be done from the database.
    /// </summary>
    private void Load()
   
{
       
this.Add(new Widget(1, "Widget1"));
       
this.Add(new Widget(2, "Widget2"));
   
}

    /// <summary>
    /// Clear out the collection and reload it.
    /// </summary>
    public void Reload()
   
{
       
this.Clear();
       
Load();
   
}
}

 

This gives me the ability to then bind dropdowns within the program as well as the ability to manipulate the collection using Linq (which is what I was after all along).

 

So, how about you?  Is inheriting from List<T> a pretty standard way of building up collections, or have I stumbled upon one of those programming faux pas that more experienced developers know to avoid?

Comments No Comments »

This is my first post, so bear with me.

I’m currently working to create a website for the start-up software company Higher Symmetry Software. At the moment, Higher Symmetry has yet to officially release their first product, so in the meantime, we’re trying to determine a way to easily gauge user interest. I came up with the simple idea of creating an ASP.NET webform that takes in a user’s email address and generates an automatic email that will be sent to an email distribution list. So, my first post will focus on creating a form to generate and send an email using C# and System.Web.Mail.

The html (aspx) side is fairly simple. Just a form element with a textbox and a button. In an aspx page, that looks like this:

<form id="Form1" method="post" runat="server">
   
<div align="center" style="padding: 15px" id="submitemail" runat="server">
        Interested in Product X?
<br /><br />
        Enter your email address below to get updates as they become available!<
br /><br />
        <
asp:TextBox ID="txtEmailUpdates" Runat="server" style="width: 200px" /><br /><br />
        <
asp:Button ID="btnSubmit" Runat="server" Text="Submit" />
    </
div>
   
<div align="center" style="padding: 15px" id="emailsent" runat="server" visible="false">
        Thanks for your support!  We will keep you updated!
   
</div>
</form>

If you notice here, I’ve enclosed the main body of the form within one div and the success message within another div. I prefer this to using an asp.net placeholder control simply for the flexibility that div tags have with CSS. I’ll demonstrate how to show and hide these divs later in the post.

The code-behind page is a little more complex, but still fairly straightforward. First, import the libraries you’ll need. In this case, all you need are System and System.Web.Mail. Next, make sure that you have declared all of your controls (or have Visual Studio auto-generate them for you) and that your btnSubmit_Click method has been declared and created. In that method, you’ll need something similar to the following:

private void btnSubmit_Click(object sender, System.EventArgs e)
{
   
string strTo = "you@email.com";
   
string strFrom = txtEmailUpdates.Text.Trim();
   
string strSubject = "Website submission";

    try
   
{
       
SmtpMail.SmtpServer = "smtp.yourserver.com";
       
SmtpMail.Send(strFrom, strTo, strSubject,String.Format("{0} is interested in Product X.", txtEmailUpdates.Text.Trim()));
   
}
   
catch( Exception )
   
{
       
//Do nothing — just let them assume they submitted the email
    }

    submitemail.Visible = false;
   
emailsent.Visible = true;
}


That should be it. To make things more consistent across the application, I like to put the smtp server and the email address in the web.config file, but it’s up to you.

Comments No Comments »