Archive for the “Programming” Category

Sass/Compass

I spent a good chunk of the last few months of 2009 completely immersed in Haml, and having spent time using both ERb and the templating language that ships with ASP.NET MVC, I have no intentions of ever turning back.  That being said, Sass seems like the next logical choice for cleaning up my html/css, and while I was a bit confused as to the point of Compass (other than being a Sass compiler – which I already get for free through the Haml gem), Chris Eppstein finally gives up the goods about 15 or 16 minutes into his Compass screencast (the first 15 minutes are great too, but if you already have a grasp on Sass, they’re a bit redundant).

Long story short: I’m tired of sucking at CSS, and short of completely immersing myself in the spec, learning the idiosyncrasies of which browser supports which feature, and then somehow retaining all of that information, Compass with Sass seems very appealing.

Related Technologies: Blueprint, YUI

RSpec

While I’m still not quite a ninja in Test::Unit, I finally feel at least proficient in it, and though I’d like nothing more than to proclaim my love for Shoulda from the highest peak of the highest mountains, I feel that I at least owe it to myself to check out RSpec before I consider the book closed on testing frameworks in Rails.

Related Technologies: Cucumber, Factory Girl, Mocha

Hudson

I spent the first three or so years of my professional life completely immersed in the .NET world (ignoring that first year spent looking at COBOL mainframe code), and in that world, CruiseControl .NET is king of the continuous integration castle.  So, when I came into the Rails fold, I naturally turned to cruisecontrol.rb for my continuous integration needs.  Unfortunately, either I haven’t yet fully grasped the extensibility of cruisecontrol.rb or the community simply hasn’t yet matured to the level of CC.NET, but I am so far underwhelmed by the Ruby version of this popular continuous integration solution.  Luckily, while first learning Rails, my initial confusion over cruisecontrol.rb led me to stackoverflow where someone suggested checking out Hudson … six months later, I think I just might give it a try.

 

Runners Up

GitGit is an incredibly popular SCM solution in the Rails world, so I will eventually need to learn it.  For now, I think I’ll wait and hope that the tooling matures a bit more.

E-TextEditor – If it weren’t for the need to drop down into Cygwin to run rails apps, this would have been a no brainer.  Unfortunately for e, Netbeans still has a much, much shallower learning curve.  Unfortunately for Netbeans, it can be very, very slow, so e is something else that I will eventually need to learn.

 

Additional Resources

This list is still (by far) the best resource I have found for identifying new technology avenues to pursue.

Comments 6 Comments »

Time again to dig into the next question on Scott Hanselman’s list of ASP.NET interview questions.  This question focuses on PostBacks; specifically, this question is posed:

"Explain how PostBacks work, on both the client-side and server-side. How do I chain my own JavaScript into the client side without losing PostBack functionality?"

Lets start with what a simple definition: A PostBack happens when the contents of a web page is sent back to the server for processing.

From the definition, it would seem that most (if not all) PostBacks happen on the server side.  Indeed, server-side PostBacks are the type you’re probably most familiar with.  For example, any time a component is declared with runat=server, it is taking advantage of the server-side handling of PostBacks.  When a PostBack happens, the information entered into a form is sent back to the same page for processing.  Newer versions of ASP.NET allow for cross-page PostBacks, but the vast majority of pages still post back to themselves.  That being said, there are a few things to remember when working with PostBacks:

  • The PostBack request contains the current value of every control within your form declared with runat=server.  The data is commonly referred to as the Post Data
  • The Post Data will also contain the content of the page’s ViewState.  In this case (unless specified otherwise), the ViewState will contain the original value of these same controls before their values were changed
  • Finally, the Post Data will contain the ID of the control that initiated the PostBack (for example, if you clicked a ‘Submit’ button, the ID of that button will be part of the Post Data

There is some additional information on ViewState and server-side PostBacks on MSDN, but that should get you started.

Regarding client-side PostBacks, and despite my best efforts to fully research the topic, without being able to directly talk to a potential interviewer posing this question, I’m not exactly certain what kind of answer Mr. Hanselman is looking for.  Almost every article I’ve found online seems to suggest that a client-side PostBack is little more than having an ASP.NET button, link button, or image button call a bit of JavaScript either before doing a server-side PostBack (i.e. displaying a confirmation dialog or doing some form validation) or in lieu of doing a server-side PostBack at all.  If that is indeed the case, this can be accomplished a few different ways.

For example, assume you have an ASP.NET button declared with ID = "btnSubmit"

<asp:button id="btnSubmit" runat="server" text="Do Something Potentially Destructive?"/>

And you want to add a confirmation dialog before the server-side PostBack occurs.  One way is to add an attribute to the control on PageLoad:

void Page_Load(object sender, EventArgs e)
{
  
btnSubmit.Attributes.Add("onclick", "return confirm(‘Are you want to do something potentially destructive?’);");
}

Starting with .NET 2.0, you can also take advantage of the OnClientClick property to accomplish the same goal:

<asp:button id="btnSubmit" runat="server" OnClientClick="return confirm(‘Are you sure you want to do something potentially destructive?’);" text="Do Something Potentially Destructive?" />

Assuming I’ve correctly interpreted the question, I believe that should set you on your way.  If not, please let me know in the comments.  This blog is as much a learning experience for me as it is for any potential readers, so don’t be shy. :)

Now, there is one lingering branch of this question that still needs answered.  Specifically, how do we chain our own JavaScript without losing PostBack functionality?  Well, again, to really answer this question, it would be best to get some more information as to exactly what is being asked.  That is, if you use one of the two methods above to add a confirmation dialog to a button, you won’t lost PostBack functionality.  In fact, I had to dig a bit deeper to really find a good example of how to answer this question.  Surprisingly (or maybe not-so-surprisingly), the answer came from Scott’s site.

What I think is being asked here is better understood when thinking about an ASP.NET LinkButton as opposed to your everyday Button.  If you’ve ever noticed, ASP.NET achieves the functionality of LinkButtons by creating and then calling a JavaScript function called __doPostBack that takes in two arguments — an EventTarget (the server-side function to be called) and an EventArgument (any arguments to that function).  This is important to note because if you now wanted to create your own JavaScript function that did some client-side processing and then called the appropriate server-side method, you would need to know the signature of this __doPostBack method.  It turns out you can get this method signature by calling Page.GetPostBackEventReference.  Tying this altogether, assume we have a LinkButton with ID = "lnkSubmit" and you want to set the NavigateUrl on PageLoad to your own JavaScript function that calls __doPostBack when it is finished.  You could do this in the following manner:

string PostBackReference = Page.GetPostBackEventReference(lnkSubmit);
lnkSubmit.NavigateUrl = BuildMyJavaScriptFunction("My first parameter", PostBackReference);

That should wrap it up.  If you have any questions, leave them in the comments!

Comments 5 Comments »

So, it’s time to tackle the next question in the original list of Scott Hanselman’s ASP.NET interview questions.  This time, the question asks to describe what events are fired when binding data to a data grid and what they could be used for.  If you are looking for a very technical overview, MSDN has the scoop on all of the data grid binding events.  Since this is a blog (and therefore not meant to be a technical document), I’ll try to approach the topic with a bit more of a pragmatic eye and give some example code usages.

On the the events!

The easiest way to figure out what events you have at your disposal is to create a DataGrid on your .aspx page and browse through the different intellisense options that pop-up beginning with "On".

Intellisense


As you can see in the image above, DataGrids in ASP.NET can do much more than display data.  However, in this case, we are only interested in the events that get fired as part of the process that binds the data to the DataGrid.  It turns out, out of the myriad of events that can be utilized, only two of them happen as part of the data binding process.  These two events are the ItemCreated event and the ItemDataBound event.

 

ItemCreated:

The ItemCreated event is fired when an item in a DataGrid control is created.  This means that at the time the event is fired, the DataGrid does not yet know about the data that will be bound to it.  So, if the logic of your method depends on this data being available to the control, you’re better off using the ItemDataBound event.  Other than that, the ItemCreate event differentiates itself in one other way from the ItemDataBound event: the ItemCreated event is raised when data is bound to the control and during round-trips (postbacks).  These qualities make the event especially well-suited to add custom attributes to a DataRow (such as onmouseover or other javascript events) or to control the appearance in ways that do not depend on the data within the DataRow (such as making every 10th row a different color).

 

ItemDataBound:

The ItemDataBound event is fired after after an item in a DataGrid control is bound.  This means that (unlike the ItemCreated event) you can add special formatting to a DataRow that is dependent upon the data contained within that row.  Since ItemDataBound is fired after the ItemCreated event, it is within this event that you are presented with the final opportunity to access the data before it is rendered to the client.  These qualities make the event well-suited for changing the appearance of a row or cell based on the data within that row or cell (such as highlighting outliers or other important information).

 

Example:

Assume we have the following DataGrid declared on our .aspx page:

<asp:DataGrid ID="MainDataGrid"
    runat
="server"
    AutoGenerateColumns
="true"
    OnItemDataBound
="MainDataGrid_ItemDataBound"
    OnItemCreated
="MainDataGrid_ItemCreated" />

On the code behind page then, we can create the following two methods to handle adding titles to header row, to specify more descriptive headers, and to change the row background color based on an employee’s salary:

protected void MainDataGrid_ItemCreated(object sender, DataGridItemEventArgs e)
{
   
//If the item is in the header
    if (e.Item.ItemType == ListItemType.Header)
   
{
       
//Iterate through each cell
        foreach(TableCell item in e.Item.Cells)
       
{
           
//Add the title attribute — we could just as easily
            //add a javascript onmouseover event here
            item.Attributes.Add("title", item.Text);
       
}

        //Since the header values are set before we have access
        //to the data, we can modify the third column header to
        //be a bit more descriptive
        e.Item.Cells[2].Text = "Salary (in US$)";
   
}
}

 
protected void MainDataGrid_ItemDataBound(object sender, DataGridItemEventArgs e)
{
   
//Since DataGrid differentiates between Items and AlternatingItems, you sometimes have to check
    //for one *or* the other
    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
   
{
       
//Here we will modify the row color based on the salary
        //We can only do this within ItemDataBound since it relies
        //on the data being available from the data source
        if (Convert.ToInt32(e.Item.Cells[2].Text) < 10000)
       
{
           
e.Item.BackColor = System.Drawing.Color.LightPink;
       
}
       
else if (Convert.ToInt32(e.Item.Cells[2].Text) < 1000000)
       
{
           
e.Item.BackColor = System.Drawing.Color.LightBlue;
       
}
       
else
       
{
           
e.Item.BackColor = System.Drawing.Color.LightGreen;
       
}
   
}
}

 

I created a sample DataTable that I have bound to.  Using the two methods above, I get the following output in the browser:

 SampleOutput 


If it helps, I have include a sample project that you can use to get started with your project.  You can download it here.

Hopefully that gives you a good idea of how best to take advantage of the events fired as part of binding data to a DataGrid.  If you have any questions or comments, please feel free to add them to the comment section.  I find these blog entries to be a great learning experience for me, so I’d love to know if they’ve been helpful to anyone else.

Comments 1 Comment »

Welcome to the third entry in my series of posted dedicated to answering Scott Hanselman’s ASP.NET interview questions.  In this entry, we will tackle using custom extensions (Scott uses *.jsp as an example to preserve backwards compatibility) to serve up ASP.NET pages.  By custom extensions, I mean that if you go to http://localhost/default.jsp you can actually direct the webserver to process the request using the ASP.NET worker process.

As it turns out, custom extensions are not all that difficult in ASP.NET assuming you have no aversions to getting under the hood and making some changes to IIS.  It also ties back nicely to the last post I did in this series that covered ASHX files and HttpHandlers.

To start out, lets first instruct IIS to send any request ending in a *.jsp extension to be passed on to the ASP.NET worker process.  To do this, open up Internet Information Services and find the website on your machine that you want to configure:

IIS


Next, select "Configuration" on the Properties page:

Properties


Here, you will be able to add the custom *.jsp extension.  For ease of use, I just copied the configuration values from the *.aspx extension.

Configuration


Extension


Click "OK" until you are back to the main IIS screen and then exit.  At this point, IIS knows that when it receives a request with a *.jsp extension to pass the request along to the ASP.NET worker process.  Next, we need to instruct our application to process these incoming requests using the PageHandlerFactory HttpHandler.  To do this, open up the web.config file and add the following lines to the httpHandlers section in the system.web node:

<httpHandlers>
 
<add path="*.jsp" verb="*" type="System.Web.UI.PageHandlerFactory" validate="true" />
</
httpHandlers>

Also, you’ll need to add the following lines to the compilation node (again in the system.web node):

<buildProviders>
 
<add extension=".jsp" type="System.Web.Compilation.PageBuildProvider" />
</
buildProviders>

Visual Studio 2005 automatically creates the compilation node as self-closing, so here is what it should look like after you’ve added the lines above:

<compilation debug="true" strict="false" explicit="true">
 
<buildProviders>
   
<add extension=".jsp" type="System.Web.Compilation.PageBuildProvider" />
  </
buildProviders>
</compilation>

Now, IIS knows how to pass the request along and your application knows how to process any request with a *.jsp extension.  At this point, we’re basically finished.  If you already have an *.aspx page that you’d like to serve up with a *.jsp extension, all that’s left is to rename it and rebuild your application.  Otherwise, I’ve found it easier to create your pages uses the *.aspx extension and then change it to *.jsp once you’re finished making your code changes.

Here is a screenshot from an application that I configured on my machine before the Page PostBack:

JspLoad


And after the PostBack:

JspPostBack


If you’d like, I also zipped up the solution which can be downloaded here.  If you have any additional questions, please feel free to leave them in the comments!

Comments 1 Comment »

I recently wanted to set up log4net on a project I’ve been working on and found the documentation somewhat lacking when trying to find a quick and easy setup guide.  So, once I had everything set up and working, I resolved to create one myself.

So, in less time than it takes to get a pizza delivered, here is how to quickly get log4net setup on your project.

What you’ll need:

  • The log4net dll (you can find the most recent version here)
  • A .Net project/solution that you’d like to add logging to (you’re on your own here)
  • Access to the Assembly.cs file for said project
  • Access to the app.config or web.config file for said project
  • A place to store your logging files (I will be using C:\ in this example, but this is one area in which the documentation actually excels)

Implementation:

  1. Place the log4net dll somewhere that you can reference it easily.  I like to keep a Libraries folder around in most of my projects to hold any 3rd party dlls, but the choice is up to you.
  2. Add a reference to the dll in your project solution:
    • References
  3. Add the following code to the Assembly.cs file.  More documentation here:
    • // Configure log4net using the .config file
      [assembly: log4net.Config.XmlConfigurator(Watch = true)]
      // This will cause log4net to look for a configuration file
      // called TestApp.exe.config in the application base
      // directory (i.e. the directory containing TestApp.exe)
      // The config file will be watched for changes.
  4. Add the following section to the web/app.config file in the <configuration> node:
    • <configSections>
       
      <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
      </
      configSections>
  5. Create a new section in the web/app.config using log4net as the node name:
    • <log4net>
       
      <appender name="FileAppender" type="log4net.Appender.FileAppender">
         
      <file value="C:\logfile.txt" />
          <
      appendToFile value="true" />
          <
      layout type="log4net.Layout.PatternLayout">
           
      <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] – %message%newline" />
          </
      layout>
       
      </appender>
       
      <root>
         
      <level value="DEBUG" />
          <
      appender-ref ref="FileAppender" />
        </
      root>
      </log4net>
  6. At the top of the class in which you want to implement logging, add the using log4net; directive.
  7. Define a static logger variable at the top of your class.  Something like this will work:
    • private static readonly ILog log = LogManager.GetLogger(typeof(Program));
  8. Start adding logging statements to your code, for example:
    • log.Info("Entering application.");
  9. Altogether then, your class might look something like this:
    • using System;
      using System.Collections.Generic;
      using System.Text;
      using log4net;

      namespace log4netDemo
      {
         
      class Program
         
      {
             
      // Define a static logger variable so that it references the name of your class
              private static readonly ILog log = LogManager.GetLogger(typeof(Program));

              static void Main(string[] args)
             
      {
                 
      log.Info("Entering application.");

                  for (int i = 0; i < 10; i++)
                 
      {
                     
      log.DebugFormat("Inside of the loop (i = {0})", i);
                 
      }

                  log.Info("Exiting application.");
             
      }
         
      }
      }

  10. Which would produce this output when run:
    • 2008-05-12 19:53:28,059 [11] INFO  log4netDemo.Program [(null)] – Entering application.
      2008-05-12 19:53:28,260 [11] DEBUG log4netDemo.Program [(null)] – Inside of the loop (i = 0)
      2008-05-12 19:53:28,280 [11] DEBUG log4netDemo.Program [(null)] – Inside of the loop (i = 1)
      2008-05-12 19:53:28,280 [11] DEBUG log4netDemo.Program [(null)] – Inside of the loop (i = 2)
      2008-05-12 19:53:28,280 [11] DEBUG log4netDemo.Program [(null)] – Inside of the loop (i = 3)
      2008-05-12 19:53:28,280 [11] DEBUG log4netDemo.Program [(null)] – Inside of the loop (i = 4)
      2008-05-12 19:53:28,280 [11] DEBUG log4netDemo.Program [(null)] – Inside of the loop (i = 5)
      2008-05-12 19:53:28,280 [11] DEBUG log4netDemo.Program [(null)] – Inside of the loop (i = 6)
      2008-05-12 19:53:28,280 [11] DEBUG log4netDemo.Program [(null)] – Inside of the loop (i = 7)
      2008-05-12 19:53:28,280 [11] DEBUG log4netDemo.Program [(null)] – Inside of the loop (i = 8)
      2008-05-12 19:53:28,280 [11] DEBUG log4netDemo.Program [(null)] – Inside of the loop (i = 9)
      2008-05-12 19:53:28,280 [11] INFO  log4netDemo.Program [(null)] – Exiting application.

 

That really should be all there is to it.  Although I did find the lack of a simple, quickstart guide daunting, there is actually a lot of good documentation on the log4net site.  Particularly, if you want to use a different appender or read a more general introduction.

If you’re interested, I’ve zipped up a sample solution using the code above.  You can download it here.

Comments 7 Comments »

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 »