Jay Harris is Cpt. LoadTest

a .net developers blog on improving user experience of humans and coders
Home | About | Speaking | Contact | Archives | RSS
 
Filed under: ASP.Net | Dev Basics

The first three parts of this series discuss the events that make up the ASP.NET Page Life Cycle, the order that these events execute on the page and on the controls, and that necessary evil called Data Binding, through which you add dynamic content to your new ASP.NET page. Raising those events happens automatically, without any developer oversight, but tapping in to those events—making them work for you—requires wiring special methods called Event Handlers to those events. This wiring can happen automatically by the system if you follow a few simple steps, or it can happen manually, with developers connecting each appropriate event to its handler. Both sides have their advantages as well as their drawbacks, but learning the nuances of event wiring can only strengthen your ASP.NET repertoire.

About the Series

When a request occurs for an ASP.NET page, the response is processed through a series of events before being sent to the client browser. These events, known as the ASP.NET Page Life Cycle, are a complicated headache when used improperly, manifesting as odd exceptions, incorrect data, performance issues, and general confusion. It seems simple when reading yet-another-book-on-ASP.NET, but never when applied in the real world. What is covered in a few short pages in many ASP.NET books (and sometimes even just a few short paragraphs), is much more complicated outside of a "Hello, World!" application and inside of the complex demands of the enterprise applications that developers create and maintain in their day-to-day work life. As close to the core as the life cycle is to any ASP.NET web application, the complications and catches behind this system never seems to get wide coverage on study guides or other documentation. But, they should.

Part 1: Events of the ASP.NET Page Life Cycle
Part 2: ASP.NET Page & WebControl Event Execution Order
Part 3: Getting Started with ASP.NET DataBinding
Part 4: Wiring Events to your Page

Automatic Event Wireup

Page events can be automatically wired to their event handlers. That is, the code to assign the event handler to your event can be made optional, with the system automatically making the connection for the page, and thus, saving the developer a little bit of work. Automatic event wiring is enabled through a boolean property called AutoEventWireup on the ASP.NET Page Directive.

<%@ Page AutoEventWireup="true" %>

With this attribute set in the page directive, ASP.NET will automatically search for and wire up any event handlers that match the specific naming convention of Page_EventName, such as Page_Init or Page_Load. These methods can exist with or without the sender and EventArgs method arguments, though do note they must both be absent or both be present from the method signature; you cannot have one without the other.

protected void Page_Init()
{
  //Do some stuff
}

protected void Page_Load(object sender, EventArgs e)
{
  //Do some stuff
}

Drawbacks to Event Auto-Wire

There is no fancy compiler magic to wire these event handlers to the event; under AutoEventWireup, ASP.NET wires each event at run time when executing the page. This means that for every event in the ASP.NET Page Life Cycle, the runtime engine reflects through your code to search for an appropriate method for that event, just in case it happens to exist, whether you create a handler method or not. To make matters worse, it is reflecting for each event twice, once for a method with handler method arguments (object sender, EventArgs e), and once for a method without the arguments.

There are ten Life Cycle events on the Page that are eligible for auto-wire (counting the Pre-and Post-Events such as PreInit and InitComplete) and four on the Control; for a single page with five user controls, .NET Reflection is searching for up to 60 different methods. That is a lot of run-time overhead! Needless to say, AutoEventWireup can have a significant negative impact on page performance.

Manual Event Wireup

Page events can also be wired manually. This is similar to wiring up any other .NET event. Using manual wire, you must explicitly wire the events you need to the appropriate event handler. However, since you controls the wiring, this allows you to follow any naming convention you wish and if needed, to wire multiple handlers to an event. Just remember to turn AutoEventWireup off.

<%@ Page AutoEventWireup="false" %>

Page Events can be wired to their handler within your page's constructor.

public MyPageClass()
{
	Init += InitializePage;
	Load += LoadPage;
}

protected void InitializePage(object sender, EventArgs e)
{
  //Do some stuff
}

protected void LoadPage(object sender, EventArgs e)
{
  //Do some stuff
}

Disadvantages to Manual Event Wireup

There is a little extra work involved to manually wire events. For the two events from the auto-wire example, add a constructor and two lines of code. However, this can be a bit of a daunting task if performed against an existing ASP.NET application with dozens of pages and dozens more user controls. Even on new applications, it can be easy to forget to wire the event, though it is easily identified in testing since without the wireup, the handler does not execute, and in most cases, the page does not function properly.

Another disadvantage is that AutoEventWireup is enabled by default in C# (it is turned off by default in Visual Basic). Even if you manually wire the events to handlers in the page constructor, you must remember to disable wireup in the Page Directive. Fail to do so will cause ASP.NET to wire up the events automatically in addition to the manual hookup, and the event handler will be executed twice. So, again, don't forget to turn off AutoEventWireup.

Balancing Effort with Performance

Using AutoEventWireup essentially comes down to the value of developer effort versus end-user performance. Auto-wire will save developers from one line of code per event, but at the cost of system performance due to the reflection that occurs to have the system wire the events rather than the developer. For a small utility web site or a demo for a presentation, I can understand using auto-wire. However, being a performance guy, I want to extract every ounce of horsepower I can out of my web applications, so I will always opt for manual wiring; with it only costing me one line of code, I feel that it is a good habit to have.

Tuesday, 26 April 2011 19:45:23 (Eastern Daylight Time, UTC-04:00)  #    Comments [1] - Trackback

Filed under: ASP.Net | Events | MVC | Speaking

"There was a time when everything was moving towards the desktop. This Internet thing was new and cool, but there was no way it would ever last. And no one knew how to code for the web, at least not anything beyond animated lava lamps and cute "Under Construction" images. So, to make coding for the web easier, they made ASP.NET to be just like coding for a desktop, using the same patterns, the same event-based model, and the same stateful approach. But the web isn't stateful, its only events are GET and POST, and is nothing like a desktop, so we tortured ourselves for years forcing a square peg through a round hole. The time has come for redemption, and its name is ASP.NET MVC. Spend an hour discovering how coding for the web is supposed to be--how it is today--and end your misery. Salvation awaits."

At various user groups throughout Southeast Michigan and Northwest Ohio, I have been presenting this topic since the last quarter of 2009. For those that are interested, I have made the slide deck available on SlideShare. The code demo used during the talk is available as a walkthrough via one of my installments of Learn to Code, where you can create, step-by-step, the same ASP.NET MVC 2 application as was built during the presentation.

If you attend one of my presentations for this topic, I would appreciate your feedback. If you are willing to tolerate a small registration process, SpeakerRate will allow you to give feedback and anonymous ratings to the session you attended. If you are interested in having me present this topic at your user group or conference, please contact me.

Past presentations on this topic:

Rate – Ann Arbor .NET Developers, Ann Arbor, Michigan, May 2010
Rate – GLUGnet, Lansing, Michigan, March 2010
Rate – A2<DIV>, Ann Arbor, Michigan, February 2010
Rate – NWNUG, Toledo, Ohio, February 2010
Rate – GLUGnet, Flint, Michigan, February 2010

Sunday, 23 May 2010 18:40:39 (Eastern Daylight Time, UTC-04:00)  #    Comments [2] - Trackback

Filed under: ASP.Net | MVC

In ASP.NET MVC, the default signature for a Details action includes an Int32 method argument. The system works fine when the expected data is entered, and the happy path is followed, but put in an invalid value or no value at all, and an exception explodes all over the user.

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Details(Int32)' in 'MvcSampleApplication.Controllers.WidgetController'.

The following solution applies to the ASP.NET MVC 2 framework. If you are looking for a solution in the first version of the ASP.NET MVC framework, try last November's post on Validating ASP.NET MVC Route Values with ActionFilterAttribute.

By default, the third section of an ASP.NET MVC Route is the Id, passed as a method argument to a controller action. This value is an optional URL Parameter (UrlParameter.Optional), as defined in the default routing tables, but the value can be parsed to other types such as an integer for a default Details action. The problem stems from when invalid values or missing values are passed to these integer-expecting actions; MVC handles the inability to parse the value into an integer, but then throws an exception trying to pass a null value to a Controller Action expecting a value type for a method argument.

A common solution is to convert the method argument to a nullable integer, which will automatically cause the argument to be null when the route value specified in the URL is an empty or non-integer value. The solution works fine, but seems a little lame to me; I want to avoid having to check HasValue within every action. I have to check for invalid identity values anyway (a user with an id of –1 isn’t going to exist in my system), so I would much rather default these invalid integers to one of these known, invalid values.

Under ASP.NET MVC 2, the solution lies with a DefaultValueAttribute. Prior to executing a Controller Action, the DefaultValueAttribute can validate that the specified route value meets an expected type, and correct the value to a default value if this validation fails; this allows me to keep that method argument as a value-type integer and avoid Nullable<int>.HasValue.

The attribute is a member of the System.ComponentModel namespace, and accepts any one of many different base values as the default to assign to the route value should the parsing fail. Unlike the ActionFilterAttribute used to solve this problem in the first version of the ASP.NET MVC framework, there are no route redirects, which also means we do not modify the browser URL. (Using the ActionFilterAttribute, the browser location is redirected from ~/Widgets/Details/ or ~/Widgets/Details/Foo to ~/Widgets/Details/0, but with the DefaultValueAttribute, no such redirect occurs.)

Usage

public class WidgetsController : Controller
{
  public ActionResult Details([DefaultValue(0) int id)
  {
    return View();
  }
}

There is very little code to make this all happen. With one attribute added to the method argument, MVC validates that my identity is an integer or otherwise provides a replacement default value. I can depend on my user input without having to laden my code with unnecessary value checks and without risk of unhandled exceptions. However, the DefaultValueAttribute is just for providing a default value for your value-type method arguments. Unlike the ActionFilterAttribute, the DefaultValueAttribute will not perform any filtering, such as making sure a string argument begins with "Foo" or that a decimal input only contains two decimal places; for this type of logic, continue to use the ActionFilterAttribute. DefaultValueAttribute is a perfect fit for eliminating Nullable<int> in Action arguments, making the code clean, simple, and elegant. Eliminate the extra code, and let the framework do the work for you.

Sunday, 04 April 2010 22:08:03 (Eastern Daylight Time, UTC-04:00)  #    Comments [0] - Trackback

Filed under: ASP.Net | Dev Basics

The previous installments of this series cover the core events of the ASP.NET Page class, of the ASP.NET Controls, and how the page and controls work together to co-exist in the same sandbox. We've gotten to the point where we know how these controls will interact with the page so that we can make our page more than just a sea of crazy peach gradient backgrounds, but that still isn't enough. Static content is so 1999, and that party broke up long ago. The next step in a quality, modern web site is creating dynamic content, and rendering it to the page. To do this, we need Data Binding.

About the Series

When a request occurs for an ASP.NET page, the response is processed through a series of events before being sent to the client browser. These events, known as the ASP.NET Page Life Cycle, are a complicated headache when used improperly, manifesting as odd exceptions, incorrect data, performance issues, and general confusion. It seems simple when reading yet-another-book-on-ASP.NET, but never when applied in the real world. What is covered in a few short pages in many ASP.NET books (and sometimes even just a few short paragraphs), is much more complicated outside of a "Hello, World!" application and inside of the complex demands of the enterprise applications that developers create and maintain in their day-to-day work life. As close to the core as the life cycle is to any ASP.NET web application, the complications and catches behind this system never seems to get wide coverage on study guides or other documentation. But, they should.

Part 1: Events of the ASP.NET Page Life Cycle
Part 2: ASP.NET Page & WebControl Event Execution Order
Part 3: Getting Started with ASP.NET Data Binding
Part 4: Wiring Events to your Page

Getting Started with ASP.NET Data Binding

When we load up data from the database, we could use a for-each loop to iterate through the data, manually create every new control, such as a table row, and manually write our data as the content for each new control, but that would be a lot of useless, repetitive, and senseless boilerplate code. Instead, we should use functionality that is built in to the ASP.NET framework, and allow the framework to do a lot of the work for us. This process of using the framework for binding dynamic data to the page, or to controls within the page, is called Data Binding.

As we've discussed before, there are several events that handle the processing and rendering of a page. Similarly, there are several events that handle the process of binding data to a page (and its child controls). Each of these events handle a very specific sub-set of the process. And as before, knowing the execution order of these events will make you more proficient at ASP.NET development.

For our examples, we will have a page for displaying Company data. The page will host a TextBox control containing the name of the company, and a repeater for departments within the company. Each repeater item will display the name of the department and a DropDownList containing the names of employees within the department.

public partial class CompanyInformation : Page
{
  private Repeater _deparmentsRepeater;
  private TextBox _companyNameTextbox;

  public _Default()
  {
    Init += Page_Init;
    Load += Page_Load;
  }

  void Page_Init(object sender, EventArgs e)
  {
    var container = new Panel();
    _companyNameTextbox = new TextBox();
    _companyNameTextbox.ID = "companyNameTextbox";
    _companyNameTextbox.DataBinding += TBox_DataBinding;
    container.Controls.Add(_companyNameTextbox);
    myForm.Controls.Add(container);

    _deparmentsRepeater = new Repeater();
    _deparmentsRepeater.ID = "departmentsRepeater";
    _deparmentsRepeater.ItemCreated += Rpt_ItemCreated;
    _deparmentsRepeater.ItemDataBound += Rpt_ItemDataBound;
    myForm.Controls.Add(_deparmentsRepeater);
  }
}

ASP.NET Data Binding Events

Page.DataBind() / Control.DataBind()

The first "Event" of ASP.NET's Data Binding Life Cycle is not an event at all; it is a method that gets everything started. The DataBind method initiates the process of binding all controls on the page, attaching your dynamic loaded classes or lists to the areas of your page where the data will be displayed. DataBind can be executed at the Page level, or on any bindable Control. Whenever it is executed, DataBind also cascades through all child controls of the execution point. If you have an ASP.NET Panel Control that contains several TextBox controls, executing DataBind on the panel will run the method on the Panel first, then all of the child text boxes. If you execute on the Page, it will fire first on the page, then on the panel, then on all of the text boxes. The cascading rules are the same as the event execution order discussed in Part 2 of this series.

Traditionally, DataBind is executed from within the Page Load event, though it can be executed from other places instead, as long as you keep the rest of the page life cycle in mind. For example, do not run DataBind on your page in PreInit; none of your controls have been instantiated, yet. Also, as my personal preference, I put all of my data retrieval logic in an override of the DataBind method, keeping all of my binding logic in a centralized location, though this can also occur elsewhere providing that it is prior to the execution of the base Page.DataBind() or Control.DataBind() method.

void Page_Load(object sender, EventArgs e)
{
  DataBind();
}
public override void DataBind()
{
  Trace.Write("Beginning to bind all controls");
  _myRepeater.DataSource = MyCompany.Departments();
  base.DataBind();
}

Here, the Page Load event kicks off our override of the DataBind method. This override retrieves a list of Departments for the company, and assigns the required properties from the company class instance to controls as needed, which includes all controls with a DataSource property. DataSource is usually a collection of objects to be used for binding collections to list-based controls from DropDownLists to Repeaters, though some other controls may have different needs and uses for DataSource. Above, we assign the Departments list to the repeater's DataSource property, so that later on in the binding process, the repeater can pass appropriate Department information on to each of its RepeaterItems and child controls. With the DataSource defined, the base DataBind method is executed to initiate binding to all controls on the page.

DataBinding Event

DataBinding is the first actual event that fires in the DataBinding series, and it will fire for every bindable control and child control from the point where the DataBind method was executed, top-down. When the event executes, binding has not yet been executed, but the data to be bound is available for manipulation. As such, binding has also not yet executed on any of the child controls of the event target. With the exception of list-based container controls like a DataGrid, GridView, or Repeater, during the DataBinding event would be where any dynamic child controls are created and their DataSources assigned.

// Use with: _companyNameTextbox.DataBinding += TBox_DataBinding;
void TBox_DataBinding(object sender, EventArgs e)
{
  ((TextBox) sender).Text = MyCompany.Name;
}

Above, we bind our TextBox control to the name of our company. TextBox does not have a DataSource property, so the company name is manually assigned directly to the TextBox's Text property.

RowCreated / ItemCreated Event

Note: RowCreated is used for GridView Control, only. ItemCreated is used for DataGrid, ListView, Repeater, and all other list-based container controls.
The RowCreated and ItemCreated events are very similar in nature to the DataBinding event, and are used for list-based container controls like a DataGrid, GridView, or Repeater. This event will execute once for each item in the DataSource collection, and correspond to one Row or Item in the control. On execution, the individual Row or Item in your control has been created, any child controls specified in your markup have been initialized and loaded, and the individual data item is available for manipulation. However, Data Binding has not yet been executed on the row or any of its child controls. This event cannot be dependent upon any control data since the binding has yet to occur. An example scenario that would use this event would be if your data item contained another list, such as our Department class instance that contains a list of Employees, and the Employees will display in a dropdown. During Created, the dropdown's DataSource can be assigned to the list contained within the Employees property. After the Created event finished for the Row or Item, ASP.NET will automatically execute the DataBind method on the Employees dropdown, binding the list data to populate the control. This automatic execution of DataBind applies to all child controls of the Row or Item, including controls defined in the Code-In-Front markup or those that were manually created in the code-behind.

Be aware that any code in the Created events cannot be dependent upon Control data. Even if you specify the DataSource property of a child dropdown, the DropDownList.Items list property is still empty. Executing code dependant upon control data, such as setting the selected item, will fail.

// Use with: _myRepeater.ItemCreated += Rpt_ItemCreated;
void Rpt_ItemCreated(object sender, RepeaterItemEventArgs e)
{
  //Preparing another Repeater Item for binding
  var dataItem = (Department) e.Item.DataItem;

  var departmentLabel = new Label();
  departmentLabel.Text = dataItem.Name;
  e.Item.Controls.Add(departmentLabel);

  var dropdownOfEmployees = new DropDownList();
  dropdownOfEmployees.DataSource = dataItem.Employees;
  dropdownOfEmployees.DataTextField = "Name";
  e.Item.Controls.Add(dropdownOfEmployees);

  e.Item.Controls.Add(new LiteralControl("
")); }

The ItemCreated event creates a label for the name of the department, assigning the name, and a DropDownList of Employees, assigning only the list's DataSource. ItemCreated is repeated for every item in the repeater's DataSource collection, or in other words, every department associated with our company. Because DataBinding has not yet executed for any child control, none of the Employee ListItems exist in our DropDownList, but because it has not yet executed, we also do not need to manually create the ListItems or manually re-execute DropDownList.DataBind().

RowDataBound / ItemDataBound

Note: RowDataBound is used for GridView Control, only. ItemDataBound is used for DataGrid, ListView, Repeater, and all other list-based container controls.
The final event in the Data Binding Life Cycle is the Bound events, RowDataBound and ItemDataBound. This event fires when the data binding process has completed for all child controls within the Row or Item. All controls within the row have their data, and code that is dependant upon control data, such as setting a selected item, can now be executed. It is strongly advised that this event contains no modifications to the item data that would require a DataBind method to be executed; this sort of data manipulation should occur instead in the Created events, prior to Data Binding the child control tree. If DataBind were to be executed again on this control, the Data Binding process for this control and all children is restarted and re-executed, causing controls to be Data Bound two or more times and potentially leading to an unknown state and adverse outcomes in your application.

The DataBound events indicate that binding has been completed for this item and all child controls; for us, this means our DropDownList of employees has been fully bound, and that a ListItem exists for each Employee. We can use this post-binding event to perform any data-dependent logic. In this case, we now set the SelectedIndex of our DropDownList; the method would fail if it was executed during ItemCreated. As with ItemCreated, this event will execute for each item in our repeater's DataSource collection.

// Use with: _myRepeater.ItemDataBound += Rpt_ItemDataBound;
void Rpt_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
  var dropdownOfEmployees = (DropDownList) e.Item.Controls[1];
  dropdownOfEmployees.SelectedIndex = 2;
}

Proper Data Binding

This is the essence of Data Binding within ASP.NET Web Forms: one method and three events. When done properly, the DataBind method should only be called once on a control tree. Execute DataBind directly on the page, or execute it once on individual controls such as each of your top-level Repeaters, but whatever path you follow, make sure that the method is not executed twice on any single control. Use the binding events to make this happen. Failure to do so can cause unfortunate side effects and extensive pain.

  • DataSources should be assigned prior to execution of a control's DataBind method.
  • Controls without a DataSource property can be manually bound using the controls DataBinding event, after executing DataBind.
  • For collection-based container controls, define child controls and assign their DataSource using the RowCreated/ItemCreated events.
  • For collection-based container controls, perform data-dependent logic on child controls in the RowDataBound/ItemDataBound event.

The ASP.NET Page Life Cycle may seem like a monotonous mess, but it is a useful tool if you understand the events, their order, and their relationship to each other. If you missed them, go back and review Part 1 for the core Page Life Cycle events and to Part 2 for the Event Execution Order between a page and its controls. Once you have these down, there still are some oddities to look out for (and some tricks to help you out). As the series continues, we discuss some of these tips, tricks, and traps to help you unleash the full power of your ASP.NET applications.

Tuesday, 23 March 2010 19:32:53 (Eastern Standard Time, UTC-05:00)  #    Comments [0] - Trackback

Filed under: ASP.Net | Learn to Code | MVC

On Tuesday, February 9th, I was scheduled lead a jam session for Come Jam With Us, the software developer study group in Ann Arbor. The session was to be on ASP.NET MVC 2, aimed to give attendees enough of an introduction to the product to empower developers to be able to start coding their own ASP.NET MVC 2 projects. Unfortunately, Mother Nature did not cooperate that day, half of the state of Michigan seemingly shut down under 8" of snow, and the session was cancelled and rescheduled for February 23rd. The goal of these Learn to Code exercises is to give you an introduction to building applications with ASP.NET MVC 2. In the near future, I also hope to provide a screen cast of these same exercises.

About this Exercise

This coding exercise is designed to give you an introduction to ASP.NET MVC 2. In this exercise, developers will create their first database-driven ASP.NET MVC 2 application within Visual Studio, primarily using code generation built in to Visual Studio. Developers performing this exercise should be familiar with ASP.NET development and Visual Studio, but no previous experience with ASP.NET MVC is required.

Prerequisites

You will need few things for ASP.NET MVC 2 application development and to complete these exercises. Please complete the following prerequisites prior to moving on. The session is designed to be completed in about an hour, but prerequisite setup is not included in that time.

Exercise 0: Getting Started

Creating a Project

Before any coding can occur, the first thing that we have to do is create a new ASP.NET MVC 2 project from within Visual Studio.

  1. In Visual Studio, create a new "ASP.NET MVC 2 Web Application" named MvcJamSession. You can create your project in either Visual Basic or Visual C#, though all of the examples in this post will be in C#.
  2. After selecting the project type and solution/project name, you will be prompted for creating a unit test project. Select "Yes." Though we will not be using these tests in this exercise, we will be in future installments.
  3. Be sure that your MvcJamSession.Test project includes a project reference back to your MvcJamSession project.
  4. Compile and run. Your browser should display a blue web site showing "Welcome to ASP.NET MVC!" Congratulations. You now have your first ASP.NET MVC application.

Convention-Based Development

Project Folder Structure of MVC Jam Session Project Development within ASP.NET MVC is based on convention over configuration. Certain naming conventions are built in the system to eliminate the amount of boiler-plate code that you need to recreate. That is not to say that you must follow these naming conventions—you may use whatever convention you like—but by straying from the standardized conventions, you will be creating a lot of extra work for yourself. With our new ASP.NET MVC 2 Project, a few of these conventions are immediately visible.

  • Controllers folder. This is where all Controller classes must go. Individual classes must be named <Name>Controller. The default project includes HomeController, which governs the Home and About actions, and AccountController, which governs the log in, log out, change password, and registration actions. If we were to make an application that manages Widgets, we would likely have a class named WidgetController.
  • Views folder. This is where all of the Views must go. By default, views are paired one-to-one with controller actions, such as one view for new user registration and another view for changing your password. Views are also separated into folders matching the associated controller name—/Views/<ControllerName>/<ActionName>. Thus, HomeController's About action is associated with the /Views/Home/About view.
    The Views folder also contains a Shared folder. This folder is where any common views, such as a Master Page, would reside. The Shared folder is also where the ViewEngine cascades to when it can't find an appropriate view in the /Views/<ControllerName> folder; if /Views/Home/About didn't exist, the ViewEngine would look for /Views/Shared/About. This can come in handy for common pages shared by all controllers, such as an error page.

Session Exercise 1: Building an Application

Using the project we just created, we're going to create an application that manage a list of employees, including their name, job title, date of hire, and date of termination. Though the default project is a great help on some applications, it can get in the way on others; we're not going to need any account services in our application, so we need to first trim the project down a little.

  1. Delete the entire Account folder under /Views/.
  2. Delete AccountController.cs from the Controllers folder.
  3. Delete shared partial view /Views/Shared/LogOnUserControl.ascx.
  4. Delete reference to this partial view by removing the "LoginDisplay" DIV from /Views/Shared/Site.Master, lines 18-20.
  5. Removing LoginDisplay will cause a slight layout problem from the CSS. To fix it, modify the #menucontainer definition in /Content/Site.css on line 263.
    #menucontainer
    {
        padding-top:40px;
    }
  6. Save all, compile, and Run. The site should be functioning normally, but without the Log In link in the top right of the home page.

Creating a Database

Like any dynamic web site, we need a storage mechanism. Create a database in SQL Server or SQL Server Express with an Employee table containing columns for name, job title, hired date, and termination date, as well as an identity column for finding records.MvcJamSession-EmployeeTable

  • For those with SQL Server Express, create a new database through right-clicking the App_Data folder, and adding a new item. The new item should be a SQL Server Database.
  • For those with SQL Server, create a new database through SQL Server Management Studio (SSMS).
  1. Create a new table called Employee.
  2. Create the following columns within the new table:
    • Id (primary key, identity, int, not null)
    • Name (varchar(50), not null)
    • JobTitle (varchar(50), not null)
    • HiredOn (date, not null)
    • TerminatedOn (date, null)
  3. Add a record or two to the table for good measure.

Creating a Model

The next thing we need to create is our Model. Not only is it the code representation for our business entity (An Employee class contains Name, JobTitle, HiredOn, and TerminatedOn properties), it is also responsible for how to get, save, or delete data from the database. We will be using Microsoft Entity Framework through Visual Studio to generate our model for us.

  1. To create our new Model, right-click the Model folder and select Add New Item. The new item should be an ADO.NET Entity Data Model, found within the Data category of the Add New Item dialog. Name it MvcJamSessionEntities.
  2. Generate the Model from a database, connecting to your MVC Jam Session database created in the previous section. On the step where you select your database connection, be sure to allow Visual Studio to add the connection string to your web.config by checking the appropriate checkbox.
  3. The Employee table is the only Data Object that needs to be generated.
  4. When the dialog completes, your Entity Data Model (a .edmx file) should be displayed in design view.
  5. Save all and compile.

Creating a Controller

Now that our model is in place, we need to create a controller. The controller is responsible for managing all interaction between the end-user and the application, including identifying what data to get, save, or delete. (Remember, though the Controller is responsible for what, the Model is responsible for how.)

  1. To create our new Controller, right-click the Controller folder and select Add Controller. Since the name matters in ASP.NET MVC's convention-over-configuration style, name it EmployeeController.cs (or .vb, if you happen to be working in Visual Basic .NET). Be sure to check the "Add action methods for Create, Update, Detail, and Delete scenarios" as we will be using them later.
  2. We now have a basic controller, but it doesn't do anything yet. First, we want to modify our Index action, as it is the default action in the controller. We will use this action to list all of the Employees that currently exist in our database. Your Index() action method should contain the following code:
    var _entities = new MvcJamSession.Models.MvcJamSessionEntities();
    return View(_entities.Employee.ToList());
  3. Save all and compile.

Creating a View

We have our Model and we have our Controller, so it is time for our View. The View is responsible for display only—it should contain virtually no logic. Our controller doesn't do anything yet, but we can at least get the base file structure and navigation in place. Since our Model governs how and our Controller governs what, think of the View as governing where, as it is responsible for deciding where each data element gets displayed on your page.

  1. Once you have saved and compiled your Controller, right-click on the Index action name and select Add View.
  2. The View should be named Index, just like your Controller action. Also, make your View strongly typed to the Employee model. Since a list of Employees is being passed to the View from the Controller, making the View strongly-typed prevents us from having to cast our View Model from object to Employee. Finally, since we are providing a list of Employees, the View Content should be a List.
  3. The Employee folder should be automatically created under the /Views/ folder, and the Index.aspx View inside of this new Employee folder.
  4. The last thing we need to do is provide some navigation to this view. Open up /Views/Shared/Site.Master and add an ActionLink within the Menu Container section to the Index action of the Employee controller. When you are done, the Menu Container should look like this:
    <ul id="menu">              
      <li><%= Html.ActionLink("Home", "Index", "Home")%></li>
      <li><%= Html.ActionLink("About", "About", "Home")%></li>
      <li><%= Html.ActionLink("Employees", "Index", "Employee")%></li>
    </ul>
  5. Save all and run. When you navigate to your Employees link, you should get a list of all employees currently in the database with an Edit, Details, and Delete links.
New in ASP.NET MVC 2: Strongly Typed HTML Helpers

In the previous version of ASP.NET MVC, HTML helpers were simple generic classes. Generated views were full of Magic Strings for each property in your model, such as <%= Html.TextBox("Name") %>, opening the door for a fat-fingered property name. MVC 2 includes strongly-typed HTML helpers on strongly-typed views. For form-based views, use the new strongly-typed "For" methods, such as <%= Html.TextBoxFor(model => model.Name) %> or <%= Html.EditorFor(model => model.Name) %> to eliminate the risk of incorrectly entering a property name. For display fields, use Html.DisplayFor() to provide similar benefits for your read-only data, including the elimination of HTML encoding for each field.

Adding New Data

A list of employees is great, but we also need the ability to manipulate that data. First, let's start with the ability to create new data.

  1. Within Visual Studio, open /Controllers/EmployeeController and navigate to the POST Create action. POST is an HTTP verb associated with pushing data to the server in the HTTP header, commonly associated with form submits. GET is the HTTP verb for pure retrieval, commonly associated with a direct URL request, such as clicking a link. In this case, the POST action can be identified by the [HttpPost] decoration.
  2. The method arguments currently include only a FormCollection object that will contain all of the header values associated with the POST. However, MVC is smart; it can automatically transform this collection into a type-safe Model, based on the names of the header variables (the identities of the HTML form inputs match the names of the Model's properties). The one exception is the Id attribute, which is available in the Model but not populated until after the object is saved to the database. To get strong typing, and avoid having to manually cast or map form collection data to a new instance of our Model, change the method signature to the following:
    public ActionResult Create([Bind(Exclude="Id")] Employee newEmployee)
  3. Now that we have a populated Model, we just need to save the Model to the database and redirect back to the List when we are done. Do this by replacing the contents of the action method with the following code:
    try
    {
      if (!ModelState.IsValid) return View();
    
      var _entities = new MvcJamSession.Models.MvcJamSessionEntities();
      _entities.AddToEmployee(employee);
      _entities.SaveChanges();
      return RedirectToAction("Index");
    }
    catch
    {
      return View();
    }
  4. Save and compile.
  5. Now we must create the View for adding data. As we did with Index, we can create the view by right-clicking the Action method and selecting Add View. The view content should be Create.
  6. The only modification for the Create view is the Id property. The generated code creates an input for this property, but it is not needed since the column value is auto-populated by the database when saving the entity. Remove this input and label from the form.
  7. Save and run. You should now be able to add new records to the database.
New in ASP.NET MVC2: Better Verb Attributes

In the first version of ASP.NET MVC, HTTP Verb conditions were placed on an Action via the AcceptVerbsAttribute, such as the Create action's [AcceptVerbs(HttpVerbs.Post)]. In ASP.NET MVC 2, these attributes have been simplified with the introduction of the HttpGetAttribute, HttpDeleteAttribute, HttpPostAttribute, and HttpPutAttribute.

Routing and Updates

The end user can view a list of Employees, and can create new employees, but when the end user clicks the Edit or Detail links, they get an error since these Views haven't been created yet and the Actions are not implemented. One by one, we will get the new views in place.

  1. Within Visual Studio, open /Controllers/EmployeeController and navigate to the Details action. You may notice that the method already accepts an integer as input, and shows example usage of the action in a commented URL above the method: /Employee/Details/5. This integer is the identity value of the Employee record, and is already populated in the links of our List view created in the previous section.
  2. Within Visual Studio, open Global.asax and navigate to the RegisterRoutes method. The default route for ASP.NET MVC is /{controller}/{action}/{id}/. By parsing out any URL into the application, MVC can determine which Controller to use, which Action to execute, and which arguments to pass to the Action. Later portions of the URL path are often optional, and when not specified, are replaced with the default values: Home, Index, and String.Empty. The URLs of "/", "/Home", "/Home/", "/Home/Index", and "/Home/Index/" are all equivalent URLs in the eyes of ASP.NET MVC.

Go back to the Employee controller. Now that we know what the integer argument is for, we need to retrieve the Employee matching the associated identity and pass it to a view for editing or display.

  1. Replace the contents of the GET version of the Edit action method with the following code to retrieve the Employee from the database that matches the identity specified in the route:
    var _entities = new MvcJamSession.Models.MvcJamSessionEntities();
    return View(_entities.Employee.Where(emp => emp.Id == id).First());
  2. Save and compile.
  3. Right-click the Action and add the View. The View should still be strongly typed, but this time the view content should be Edit.
  4. The Details and GET Delete actions are largely similar as the GET Edit action, except that the view is labels instead of text boxes. Repeat the above three steps for the Details action method with a Details view content and for the GET Delete action method with a Delete view content.
  5. As with the Create view, the Id property should be removed from the Edit view, as it is not an item that should be edited by the end user.
  6. Save and run. You should see the details of an Employee when clicking on the Edit and Details links.
  7. We can view Employee details within the Edit form, but when we make changes and submit, nothing happens. We need to modify the POST Edit action to save our changes back to the database. The default POST Edit action accepts an id and a FormCollection as input arguments, but similarly to the POST Create action, we can change this to use our strongly typed model to avoid having to cast or map data. However, unlike our Create action, we need to bind the id property so that the system knows which record to update. To make these modifications, replace the POST Edit signature with the following:
    public ActionResult Edit(MvcJamSession.Models.Employee employee)
  8. Replace the contents of the POST Edit action method with the following code to save the changes to the database:
    try
    {
      if (!ModelState.IsValid) return View();
    
      var _entities = new MvcJamSession.Models.MvcJamSessionEntities();
      var _originalEmployee =
        _entities.Employee.Where(emp => emp.Id == employee.Id).First();
      _entities.ApplyPropertyChanges(_originalEmployee.EntityKey.EntitySetName,
                                     employee);
      _entities.SaveChanges();
      return RedirectToAction("Index");
    }
    catch
    {
      return View();
    }
  9. Replace the signature of the POST Delete action method with the following code to provide strong typing on our model:
    public ActionResult Delete(MvcJamSession.Models.Employee employee)
  10. Finally, replace the contents of the POST Delete action method with the following code to delete a record:
    var _entites = new MvcJamSession.Models.MvcJamSessionEntities();
    var originalEmployee =
      _entites.Employee.Where(emp => emp.Id == deletedEmployee.Id).First();
    _entites.DeleteObject(originalEmployee);
    _entites.SaveChanges();
    return RedirectToAction("Index");
  11. Save, compile, and run. You should now be able to modify existing Employee records.

We now have a fully-functional ASP.NET MVC application to manage our Employee records. Congratulations!

Tuesday, 23 February 2010 17:38:00 (Eastern Standard Time, UTC-05:00)  #    Comments [3] - Trackback

Filed under: ASP.Net | Events | MVC

On Tuesday, February 23rd, I will be leading the jam session for Come Jam With Us, the software developer study group in Ann Arbor. The session will be on ASP.NET MVC, and aims to give attendees enough of an introduction to the product to empower developers to be able to start coding their own ASP.NET MVC 2 projects. Like all of the Come Jam With Us sessions for the winter/spring of 2010, it will be held at the offices of SRT Solutions in Ann Arbor at 5:30p.

Prerequisites

You will need few things for ASP.NET MVC 2 application development and to complete this exercise. Please complete the following prerequisites prior to the session, otherwise you likely will spend the hour downloading and installing rather than coding.

Rescheduled

Due to weather, the original February 9th meeting was cancelled. This session is rescheduled for Tuesday, February 23rd.

Sunday, 07 February 2010 23:45:36 (Eastern Standard Time, UTC-05:00)  #    Comments [2] - Trackback

Filed under: ASP.Net | MVC

In ASP.NET MVC, the default signature for a Details action includes an Int32 method argument. The system works fine when the expected data is entered, and the happy path is followed, but put in an invalid value or no value at all, and an exception explodes all over the user.

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Mvc.ActionResult Details(Int32)' in 'MvcSampleApplication.Controllers.WidgetController'.

The following solution applies to the first version of the ASP.NET MVC framework. If you are looking for a solution in the ASP.NET MVC 2 framework, try Validating ASP.NET MVC 2 Route Values with DefaultValueAttribute.

By default, the third section of an ASP.NET MVC Route is the Id, passed as a method argument to a controller action. This value is a string, defaulting to String.Empty, but it can be parsed to other types such as an integer for a default Details action. The problem stems from when invalid values or missing values are passed to these integer-expecting actions; MVC handles the inability to parse the value into an integer, but then throws an exception trying to pass a null value to a Controller Action expecting a value type for a method argument.

A common solution is to convert the method argument to a nullable integer, which will automatically cause the argument to be null when the route value specified in the URL is an empty or non-integer value. The solution works fine, but seems a little lame to me; I want to avoid having to check HasValue within every action. I have to check for invalid identity values anyway (a user with an id of –1 isn’t going to exist in my system), so I would much rather default these invalid integers to one of these known, invalid values.

Using a custom ActionFilterAttribute, I can accomplish my goal. Prior to executing my Controller Action, an ActionFilterAttribute can validate that the specified route value meets an expected type, and correct the value to a default value if this validation fails; this will allowing me to keep that method argument as a value type integer and avoid Nullable<int>.HasValue.

ForceIntegerRouteValueAttribute class

public sealed class ForceIntegerRouteValueAttribute : ActionFilterAttribute
{
  private readonly int _defaultValue;
  private readonly string _routeValueName;

  public ForceIntegerRouteValueAttribute(string valueName, int defaultValue)
  {
    _routeValueName = valueName;
    _defaultValue = defaultValue;
  }

  public override void OnActionExecuting(ActionExecutingContext context)
  {
    base.OnActionExecuting(context);

    int testValue;
    if (!context.ActionParameters.ContainsKey(_routeValueName) ||
        !int.TryParse(context.RouteData.Values[_routeValueName].ToString(),
                      out testValue))
    {
      context.RouteData.Values[_routeValueName] = _defaultValue;
      context.Result = new RedirectToRouteResult(context.RouteData.Values);
    }
  }
}

The attribute accepts a string matching the name of the route value to analyze and a default value to assign to the route value should the validation fail. The override on OnActionExecuting will cause the validation to fire immediately prior to the Action being executed. The method attempts to parse the route value to an integer, and if it fails it will set the route value to the default value and restart processing of the route. RedirectToRouteResult restarts the route processing over again, since to get to this point, the method must have changed a route value, and without the redirect, the action would continue on with the original value. This will also redirect the browser to route matching the new route value, such as redirecting ~/Widgets/Details/Foo to ~/Widgets/Details/0.

Usage

public class WidgetsController : Controller
{
  [ForceIntegerRouteValue("id", 0)]
  public ActionResult Details(int id)
  {
    return View();
  }
}

By simply adding the attribute to the Action, I can now validate that my identity is an integer, allowing for some level of trust into user input values, and do so without having to laden my code with unnecessary value checks. This same idea can be used for any sort of pre-filtering, which could also include checking that the number contains no more than two decimal places. Just don’t go too far with this idea. Familiarize yourself with Route Constraints, too, as there will be times that a constraint can better serve your business needs than an Action Filter. But for areas where this solution does serve well, such as eliminating Nullable<int> in Action arguments, this option just seems cleaner to me. And in the ASP.NET MVC World of keeping Controllers as light as possible, I like clean.

Monday, 30 November 2009 23:12:51 (Eastern Standard Time, UTC-05:00)  #    Comments [1] - Trackback

Filed under: ASP.Net | Events | Speaking
Lansing Day of .Net, 1 August 2009 - I'll be there!

This Saturday, August 1st, I will be speaking at Lansing Day of .NET 2009, at the Breslin Student Events Center at Michigan State University, East Lansing, Michigan. This session will be the same ASP.NET Page Life Cycle talk that I gave last month at CodeStock.

Dev Basics: The ASP.NET Page Life Cycle

Jay Harris / Session Level: 100
When a request occurs for an ASP.NET page, the response is processed through a series of events before being sent to the client browser. These events, known as the Page Life Cycle, are a complicated headache when used improperly, manifesting as odd exceptions, incorrect data, performance issues, and general confusion. It seems simple when reading yet-another-book-on-ASP.NET, but never when applied in the real world. In this session, we decompose this mess, and turn the Life Cycle into an effective and productive tool. No ASP.NET MVC, no Dynamic Data, no MonoRail, no technologies of tomorrow, just the basics of ASP.NET, using the tools we have available in the office, today.

If you can make it, I recommend attending LDODN09. There are some great sessions lined up, and it is all being provided free-of-charge (though the event organizers are encouraging donations). Last year's event, held at Lansing Community College, was the first Lansing Day of .NET and the first event that I was involved in organizing. It went well, and from the moment it was over I was looking forward to the next one. I'm not on the organizing committee this year, but I am still sure that this one is destined to be great as well. They rented the Breslin Center! If I knew nothing else, that would be enough.

So come out to Lansing Day of .NET this Saturday. Registration is still open.

I hope to see you there.

Tuesday, 28 July 2009 19:18:18 (Eastern Daylight Time, UTC-04:00)  #    Comments [0] - Trackback

Filed under: ASP.Net | Dev Basics

The first installment of this series goes back to the beginning and describes each of the events within ASP.NET Page Life Cycle. Understanding the basic fundamentals of the ASP.NET Page Life Cycle, including the order and scope of influence for each of the Page Life Cycle events, will help ensure that you are executing your custom code at the right time, and in the right order, rather than stepping on yourself by conflicting with core ASP.NET framework functionality. But this is only part of the story, since there is more to the ASP.NET Page Life Cycle than just the page, itself.

ASP.NET Page & WebControl Event Execution Order

Pages would be nothing but a sea of crazy peach gradient backgrounds without the controls to display content and to interact with the user. In addition to the order of the various page events, it is often helpful to know the order in which a page and its controls execute a single event. Does Page.Load execute before Control.Load? Does Page.Init execute before Control.Init? Does myTextBox.TextChanged fire before myButton.Click? And what about myTextBox1.TextChanged versus myTextBox2.TextChanged?

Knowing the execution order of events within the control tree will make you a better ASP.NET developer. If you cannot answer each of those questions above (and maybe even if you can), keep reading.

About the Series

When a request occurs for an ASP.NET page, the response is processed through a series of events before being sent to the client browser. These events, known as the ASP.NET Page Life Cycle, are a complicated headache when used improperly, manifesting as odd exceptions, incorrect data, performance issues, and general confusion. It seems simple when reading yet-another-book-on-ASP.NET, but never when applied in the real world. What is covered in a few short pages in many ASP.NET books (and sometimes even just a few short paragraphs), is much more complicated outside of a "Hello, World!" application and inside of the complex demands of the enterprise applications that developers create and maintain in their day-to-day work life. As close to the core as the life cycle is to any ASP.NET web application, the complications and catches behind this system never seems to get wide coverage on study guides or other documentation. But, they should.

Part 1: Events of the ASP.NET Page Life Cycle
Part 2: ASP.NET Page & WebControl Event Execution Order
Part 3: Getting Started with ASP.NET Data Binding
Part 4: Wiring Events to your Page

Event Execution Order within the Control Hierarchy

At the core of the control-level event execution order is where the events fire with respect to the page. The majority of the events in the ASP.NET Page Life Cycle execute from the top, down, which is also referred to as outside-in. That is, the event is first executed on the page, such as Page.Load, then executed recursively through each of the page's controls, Control.Load, to the controls within controls, and so on. The two exceptions to this rule are Initialization and Unload. With these two events, the event is fired first on the child control, then on the container control, and finally on the page, known as a bottom-up or inside-out order.

But what if a control is dynamically added to the page during a later event? In this case, a control will fire events to catch up to the page (though a control will never exceed beyond what Page Event is currently executing). In other words, if a control is dynamically added during the PreInit page event, the control will immediately fire its own PreInit. However, if a control is dynamically added during the PreLoad event, it will fire PreInit, Init, InitComplete, and PreLoad, all in quick succession.

private void Page_PreInit(object sender, EventArgs e)
{
    Trace.Write("Executing Page PreInitialization");
    var textbox = new TextBox();
    textbox.Init += Control_Init;
    textbox.Load += Control_Load;
    textbox.ID += "TextBoxFromPreInit";
    form1.Controls.Add(textbox);
}

private void Page_Init(object sender, EventArgs e)
{
    Trace.Write("Executing Page Initialization (Should occur after controls)");
}

private void Page_Load(object sender, EventArgs e)
{
    Trace.Write("Executing Page Load (Should occur before controls)");
    var textbox = new TextBox();
    textbox.Init += Control_Init;
    textbox.Load += Control_Load;
    textbox.ID += "TextBoxFromLoad";
    form1.Controls.Add(textbox);
}

private void Control_Init(object sender, EventArgs e)
{
    Trace.Write("Executing Control Init for " + ((Control)sender).UniqueID);
}

private void Control_Load(object sender, EventArgs e)
{
    Trace.Write("Executing Control Load for " + ((Control)sender).UniqueID);
}

/*
Output: 

Begin PreInit		
Executing Page PreInitialization
End PreInit
Begin Init
Executing Control Init for TextBoxFromPreInit
Executing Page Initialization (Should occur after controls)
End Init
Begin Load
Executing Page Load (Should occur before controls)
Executing Control Init for TextBoxFromLoad
Executing Control Load for TextBoxFromPreInit
Executing Control Load for TextBoxFromLoad
End Load
*/

Event Execution Order for Sibling WebControls

The event execution order of parent and child controls is simple and straightforward. As if to maintain balance in The Force, the event execution order for sibling controls is a bit complicated. For siblings, this order is governed by three main and cascading criteria: the type of event that is being executed, the Page Event executing when the control was added to the page, and the index of the control within the parent's (or page's) Controls collection.

First, the event type is the primary governor of when an event is fired. Just like the order of Page Events, Initialize events always occur before Load events, and Load events always occur before Render events. The complication surrounds the several control-specific "PostBack Events," such as Click or TextChanged, as there are three PostBack event types: Changed Events, Validation Events, and actual PostBack Events. The first that fire are Changed Events, which include any event where the value changes, such as TextBox.TextChanged or DropDownList.SelectedIndexChanged. Changed events should include any custom Value manipulation for each of your form controls. Once the values are defined, Validation events are executed to assist with ensuring data integrity. Finally, once all values are defined and validated, PostBack Events, such as Button.Command or Button.Click, are executed. In most cases, these PostBack events will include the form submission logic, such as sending the email, transmitting data through a Web Service, or saving data to a database. The Changed Events type of events always fire before Validation events, which always fire before the PostBack Events types; TextBox.TextChanged before Validator.Validate before Button.Click.

If the events are the same, such as two TextBox controls that are both executing TextChanged, the second criteria to determine sibling event execution is when the control was added to the page. If a control was added in any of the Initialization events (PreInit, Init, InitComplete), it is executed first. If a control was added in any of the Load events, it is executed second. So, for the two TextBoxes, the TextChanged event for the TextBox added during Initialization will be fired before the same event for the TextBox added during Load. (txtAddedDuringInit.TextChanged will fire before txtAddedDuringLoad.TextChanged.)

If the executing event is the same, and the controls were added during the same Page Event, the final criterion for sibling execution is the index within the Controls collection. After the above two criteria are considered, events that still have equal weight are executed according to their index in their parent's Controls collection.

private void Page_Init(object sender, EventArgs e)
{
    TextBox textbox;
    textbox = new TextBox();
    textbox.TextChanged += Control_TextChanged;
    textbox.ID += "TextBoxFromInit1";
    form1.Controls.Add(textbox);
    textbox = new TextBox();
    textbox.TextChanged += Control_TextChanged;
    textbox.ID += "TextBoxFromInit2";
    form1.Controls.Add(textbox);
    textbox = new TextBox();
    textbox.TextChanged += Control_TextChanged;
    textbox.ID += "TextBoxFromInit3At0";
    form1.Controls.AddAt(0, textbox);
}

private void Page_Load(object sender, EventArgs e)
{
    TextBox textbox;
    textbox = new TextBox();
    textbox.TextChanged += Control_TextChanged;
    textbox.ID += "TextBoxFromLoad1";
    form1.Controls.Add(textbox);
    textbox = new TextBox();
    textbox.TextChanged += Control_TextChanged;
    textbox.ID += "TextBoxFromLoad2";
    form1.Controls.Add(textbox);
    textbox = new TextBox();
    textbox.TextChanged += Control_TextChanged;
    textbox.ID += "TextBoxFromLoad3At0";
    form1.Controls.AddAt(0, textbox);
}

private void Control_TextChanged(object sender, EventArgs e)
{
    Trace.Write("Executing Control TextChanged for " + ((Control) sender).UniqueID
                + " / Position: " + form1.Controls.IndexOf((Control) sender));
}

/*
Trace Output: 

Begin Raise ChangedEvents
Executing Control TextChanged for TextBoxFromInit3At0 / Position: 1
Executing Control TextChanged for TextBoxFromInit1 / Position: 2
Executing Control TextChanged for TextBoxFromInit2 / Position: 3
Executing Control TextChanged for TextBoxFromLoad3At0 / Position: 0
Executing Control TextChanged for TextBoxFromLoad1 / Position: 4
Executing Control TextChanged for TextBoxFromLoad2 / Position: 5
End Raise ChangedEvents
*/

So, to address the questions from above: Page.Load does execute before Control.Load, as the Load event is executed outside-in, however, Page.Init executes after Control.Init, as the Init event is executed inside-out. The TextChanged event on myTextBox is fired prior to myButton.Click, as control ChangedEvents are executed before control PostBackEvents. And finally, regarding myTextBox1.TextChanged versus myTextBox2.TextChanged, it depends; the order is dependent upon where the controls exist within the entire hierarchy, when the controls were created, and upon their position within the Controls collection.

The execution order of control events within the page life cycle is a complicated mess, and fortunately does not come in to play often. But for when it does, it is important to know how everything plays together. I find that most often, the order is important when dynamically adding controls to the page outside of DataBinding (though I would consider this a design smell), when creating custom WebControls, or when working with control Changed Events and validation. Still, as with before, committing this to memory (or at least a link to a reference, such as this post) will help with making you a better ASP.NET developer and with creating higher quality applications.

So what's next? Part 1 covered the base ASP.NET Page Life Cycle, and this post covers the execution order of events on the page. As this series continues, we will discuss the details of the DataBinding events, and will dig in to some tips, tricks, and traps when developing ASP.NET applications.

Tuesday, 14 July 2009 18:26:15 (Eastern Daylight Time, UTC-04:00)  #    Comments [2] - Trackback

Filed under: ASP.Net | Dev Basics

When a request occurs for an ASP.NET page, the response is processed through a series of events before being sent to the client browser. These events, known as the ASP.NET Page Life Cycle, are a complicated headache when used improperly, manifesting as odd exceptions, incorrect data, performance issues, and general confusion. It seems simple when reading yet-another-book-on-ASP.NET, but never when applied in the real world. What is covered in a few short pages in many ASP.NET books (and sometimes even just a few short paragraphs), is much more complicated outside of a "Hello, World!" application and inside of the complex demands of the enterprise applications that developers create and maintain in their day-to-day work life. As close to the core as the life cycle is to any ASP.NET web application, the complications and catches behind this system never seems to get wide coverage on study guides or other documentation. But, they should.

Posts in this Series

Part 1: Events of the ASP.NET Page Life Cycle
Part 2: ASP.NET Page & WebControl Event Execution Order
Part 3: Getting Started with ASP.NET Data Binding
Part 4: Wiring Events to your Page

A little help on the Page Life Cycle is never a bad thing. In this series, I will go over the events that make up the ASP.NET Page Life Cycle, as well as some tips and tricks on how to get the most out of this event structure while avoiding the traps and pitfalls. Rather than pursuing broad coverage of the entire ASP.NET Framework, we'll dive deeply into the "small" portion that is the ASP.NET Page Life Cycle.

Events of the ASP.NET Page Life Cycle

I want to start at the beginning. The primary make-up of the Page Life Cycle is the events that process any ASP.NET requests. Unlike the public static void main of a WinForms application, where everything based on methods, the execution of a page request is the execution of these events. These events, which execute in a particular order, handle the entire request, including loading all of the controls, processing all of the form data, handling all user-initiated actions, and rendering the page to the web browser. Knowing the order in which these events are executed, as well as the responsibility of each event in processing your request, is important for developing solid, quality ASP.NET applications.

Start

This is where the page object is instantiated, and where the initial properties of the page are set. Page properties such as Response and Request, UICulture (similar to the UICulture property within a WinForms thread), and the value of IsPostBack are all determined and assigned. No controls are available at this time, so do not try to set the value of that TextBox control, as it doesn't exist, yet. Fortunately, no event handlers can be attached to this event, anyway, so there isn't much you can do to customize this processing or to access that TextBox's value property; "Move along. There is nothing to see here." But, be aware that this event does occur after the Constructor, so if you try to access properties such as IsPostBack prior to the Start event, they have yet to be assigned, and will likely be incorrect.

Page Initialization

During page initialization, the controls are created, initialized, and added to the Page's controls collection. This is the first time that you can access a control by its UniqueID. Do note that all control properties are set to their code values, be it from code-behind or code-in-front, regardless of what may be available in ViewState and Form Post values. Control state has yet to be restored, so ViewState and Form Post values have not yet been pushed to the controls. Finally, Initialization (specifically, PreInit) is the only time that the Theme and Master Page can be programmatically modified.

Page Load

Page Load is where control state is restored. If the request is a PostBack, rather than a new request, all available property values are restored from ViewState and Form Post data and pushed to the applicable controls. Under most scenarios, this is where you're going to get what you need from the Database, such as pulling a value from the query string and loading an item with the matching identity.

Validation

The Validation event only applies to PostBack requests, and only when Validators are present in the control collection. The Validate method is executed for each Validator present, through which the IsValid property is set for each Validator. These IsValid property values are then cascaded up to the Page's IsValid property. Be aware that even if all Validators on the page are disabled, the Validation event will still fire; if a Validator is present, Validate is executed, without regard to any other property. Also, note that the Validation event is a child of the Page's Load event, so it is executed within the Page Load event chain, after Page Load, but prior to PostBack Events and LoadComplete.

PostBack Events

Once Validation is complete (if applicable), all PostBack events are executed, including the OnChange event of a DropDownList and the OnClick event of a command button. Post Back Events are also a child of the Page's Load event, executing after Validation and before LoadComplete.

Render

Finally, once all of the data is processed and Post Back events handled, the Page is rendered within the Web Browser. The Render event consists of saving all control property data to ViewState, processing the Page and each Control into HTML, and writing the HTML to the output stream. This is the last opportunity to modify the HTML output.

Remembering the Order

If you are having trouble remembering the order, instead try and remember this simple mnemonic: SILVER; Start, Initialize, Load, Validation, Events, Render.

If you are doing a lot of ASP.NET programming, or anticipate that you will be in the near future, try to commit to memory the order of each of these events, and their scope of influence. Understanding these basic fundamentals of the ASP.NET Page Life Cycle will help ensure that you are executing your custom code at the right time, and in the right order, rather than stepping on yourself by conflicting with the core functionality.

Now that we know the order of execution on Page Events, what is the order of the Controls? Does Page.Load execute before Control.Load? How about the order of sibling controls? What is the order of myTextBox1.TextChanged versus myTextBox2.TextChanged? Also, what are some things to look out for? As this series continues, we will discuss the details of event execution order within the ASP.NET Page Life Cycle, as well as some tips, trick, and traps when developing ASP.NET applications.

Monday, 22 June 2009 23:53:57 (Eastern Daylight Time, UTC-04:00)  #    Comments [0] - Trackback

Filed under: ASP.Net | Events | Speaking

Next month, I will be speaking at CodeStock, a developer conference in Knoxville, Tennessee, held June 26-27. We will be discussing the ASP.NET Page Life Cycle, to help get over the fears and troubles with validation, event handing, data binding, and the conflicts between page load and page initialization.

Dev Basics: The ASP.NET Page Life Cycle

Jay Harris / Session Level: 100
When a request occurs for an ASP.NET page, the response is processed through a series of events before being sent to the client browser. These events, known as the Page Life Cycle, are a complicated headache when used improperly, manifesting as odd exceptions, incorrect data, performance issues, and general confusion. It seems simple when reading yet-another-book-on-ASP.NET, but never when applied in the real world. In this session, we decompose this mess, and turn the Life Cycle into an effective and productive tool. No ASP.NET MVC, no Dynamic Data, no MonoRail, no technologies of tomorrow, just the basics of ASP.NET, using the tools we have available in the office, today.

It's a long drive from Michigan to Knoxville, but the conference is worth the trip (the first of two Tennessee conferences I will be attending this year). A few other local speakers will be making the trip to Knoxville, as well. Check out the full session list for more information, and while you are at it, register for the event if you haven't already done so; the cost is only $25 if you sign up before the end of May. I was there last year for the first CodeStock, and I had a great time; I'm excited about this years event, not only because I am speaking, but to see what other new things that people are talking about, catch up with friends, and to meet new people in the community.

I hope to see you there.

Technorati Tags: ,,
Monday, 18 May 2009 09:27:01 (Eastern Daylight Time, UTC-04:00)  #    Comments [0] - Trackback

Filed under: ASP.Net | Blogging | Programming | SEO

Did you know that yourdomain.com and www.yourdomain.com are actually different sites? Are they both serving the same content? If so, it may be negatively impacting your search engine rankings.

Subdomains and the Synonymous 'WWW'

Sub-domains are the prefix to a domain (http://subdomain.yourdomain.com), and are treated by browsers, computers, domain name systems (DNS), search engines, and the general internet as separate, individual web sites. Google's primary web presence, http://www.google.com, is very different than Google Mail, http://mail.google.com, or Google Documents, http://docs.google.com, all because of subdomains. However, what many do not realize is that www is, itself, a subdomain.

A domain, on its own, requires no www prefix; a subdomain-less http://yourdomain.com should be sufficient for serving up a web site. And since www is a subdomain, dropping the prefix could potentially return a different response. There are some sites that will fail to return without the prefix, and some sites that fail with it, but the most common practice is that the www subdomain is synonymous for no subdomain at all.

The Synonymous WWW and SEO

The issue with having two synonymous URLs (http://yourdomain.com and http://www.yourdomain.com) is that search engines may interpret them as separate sites, even if they are serving the same content. The two addresses are technically independent and are potentially serving unique content; to a cautious search engine, even if pages appear to contain the same content, there may be something different under the covers. This means your audience's search results returns two entries for the same content. Some users will happen to click on yourdomain.com while others navigate to www.yourdomain.com, splitting your traffic, your page hits, your search ranking between two sites, unnecessarily.

HTTP Redirects will cure the issue. If you access http://google.com, your browser is instantly redirected to http://www.google.com. This is done through a HTTP 301 permanent redirect. Search Spiders recognize HTTP response codes, and understand the 301 as a "use this other URL instead" command. Many search engines, such as Google, will then update all page entries for the original URI (http://yourdomain.com) and replace it with the 301's destination URL (http://www.yourdomain.com). If there is already an entry for the destination URL, the two entries will be merged together. The search entries for yourdomain.com and www.yourdomain.com will now share traffic, share page hits, and share search ranking. Instead of having two entries on the second and third pages of search results, combining these entries may be just enough to place you on the first page of results.

In addition to combining search entries for subdomains, you can also combine root-level domains through HTTP 301. On this site, in addition to adding the www prefix if no subdomain is specified, captainloadtest.com will HTTP 301 redirect to www.cptloadtest.com.

Combining the Synonyms

We need a way to implement an HTTP 301 redirect at the domain level for all requests to a site; however, often we are using applications that may not grant us access to the source, or we don't have the access into IIS through our host to set up redirects for ourselves. URL Rewrite, Part 2 covers a great drop-in redirect module by Fritz Onion that uses a stand-alone assembly with a few additions in web.config to HTTP 301 redirect paths in your domain (it also supports HTTP 302 redirects). This module is perfect for converting a WordPress blog post URL, such as cptloadtest.com/?p=56, to a DasBlog blog post URL like cptloadtest.com/2006/05/31/VSNetMacroCollapseAll.aspx. However, to redirect domains and subdomains, the module must go a step further and redirect based on matches against the entire URL, such as directing http:// to https:// or captainloadtest.com to cptloadtest.com, which it does not support. It's time for some modifications.

private void OnBeginRequest(object src, EventArgs e) {
  HttpApplication app = src as HttpApplication;
  string reqUrl = app.Request.Url.AbsoluteUri;
  redirections redirs
    = (redirections) ConfigurationManager.GetSection("redirections");

  foreach (Add a in redirs.Adds) {
    Regex regex = new Regex(a.targetUrl, RegexOptions.IgnoreCase);
    if (regex.IsMatch(reqUrl)) {
      string targetUrl = regex.Replace(reqUrl, a.destinationUrl, 1);

      if (a.permanent) {
        app.Response.StatusCode = 301; // make a permanent redirect
        app.Response.AddHeader("Location", targetUrl);
        app.Response.End();
      }
      else
        app.Response.Redirect(targetUrl);

      break;
    }    
  }
}

By converting app.Request.RawURL to app.Request.AbsoluteUri, the regular expression will now match against the entire URL, rather than just the requested path. There is one downside to this change: the value is the actual path processed, not necessarily what was in the originally requested URL. To this effect, the value of AbsoluteUri for requesting http://www.cptloadtest.com?p=56 is actually http://www.cptloadtest.com/default.aspx?p=56; by requesting the root directory, the default page is being processed, not the directory itself, so default.aspx is added to the URL. Keep this in mind when setting up your redirection rules. Also, the original code converted the URL to lower case; with my modifications, I chose to maintain the case of the URL, since sometimes case matters, and instead ignore case in the regular expression match using RegexOptions.IgnoreCase. Finally, I made some other minor enhancements, like using the ConfigurationManager, since ConfigurationSettings is now obsolete, and reusing the matching Regex instance for replacements.

Download: RedirectModule.zip

Includes:

  • Source code for the drop-in Redirect Module
  • Sample web.config that uses the module
  • Compiled version of redirectmodule.dll

The code is based on the original Redirect Module by Fritz Onion and the Xml Serializer Section Handler by Craig Andera. As always, this code is provided with no warranties or guarantees. Use at your own risk. Your mileage may vary. Thanks to Fritz Onion for the original work, and allowing me extend his code further.

The usage is the same as Fritz Onion's original module. Drop the assembly into your site's bin, and place a few lines into the web.config. The example below contains the rules as they would apply to this site, 301 redirecting http://www.captainloadtest.com to http://www.cptloadtest.com, and adding the www subdomain to any domain requests that have no subdomain.

<?xml version="1.0"?>
<configuration>
  <configSections>
    <section name="redirections"
      type="Pluralsight.Website.XmlSerializerSectionHandler, redirectmodule" />
  </configSections>
  <!-- Redirect Rules -->
  <redirections type="Pluralsight.Website.redirections, redirectmodule">
    <!-- Domain Redirects //-->
    <add targetUrl="captainloadtest\.com/Default\.aspx"
      destinationUrl="cptloadtest.com/" permanent="true" />
    <add targetUrl="captainloadtest\.com"
      destinationUrl="cptloadtest.com" permanent="true" />

    <!-- Add 'WWW' to the domain request //-->
    <add targetUrl="://cptloadtest\.com/Default\.aspx"
      destinationUrl="://www.$1.com/" permanent="true" />
    <add targetUrl="://cptloadtest\.com"
      destinationUrl="://www.$1.com" permanent="true" />

    <!-- ...More Redirects -->
  </redirections>
  <system.web>
    <httpModules>
      <add name="RedirectModule"
        type="Pluralsight.Website.RedirectModule, redirectmodule" />
    </httpModules>
  </system.web>
</configuration>

The component is easy to use, and can redirect your site traffic to any URL you choose. Neither code changes to the application nor configuration changes to IIS are needed. By using this module to combine synonymous versions of your URLs, such as alternate domains or subdomains, you will improve your page ranking through combining duplicate search result entries. One more step towards your own search engine optimization goals.

URL Rewrite

Thursday, 04 December 2008 16:43:10 (Eastern Standard Time, UTC-05:00)  #    Comments [4] - Trackback

Filed under: ASP.Net | Programming

A few months ago I switched my blogging engine from WordPress to DasBlog, and was left with a pile of broken post links. The WordPress format of formatting URLs, such as cptloadtest.com/?p=56, no longer applied; DasBlog has its own way of building the URL: cptloadtest.com/2006/05/31/VSNetMacroCollapseAll.aspx. Other people, with links to my posts on their own blogs, and search engines, with search results pointing to the old format, no longer directed people to the proper page. Fortunately, the old WordPress way directed users to the domain root, so they saw the main page instead of a 404, but what I really needed was a way to get users to the content they came for. But, I wanted a way that didn't involve customizing DasBlog code.

Part 1 discusses some client-side options for redirecting traffic. As a developer, I would only need to add some quick JavaScript or HTML to my pages to reroute traffic, but I wanted a better way. I wanted Google's links to be updated, rather than just for the link to correctly route. I want a solution that worked without JavaScript. I wanted a solution that didn't download the page twice, as any client-side processor would do. I wanted the HTTP 301.

HTTP 301, Move Permanently, is a server-side redirection of traffic. No client-side processing is involved. And Google recognizes that this is a permanent redirect, as it's name implies, so the Google result link is updated to the new URL. But since this is a server-side process, and I don't have full access to IIS settings with my hosting provider, I needed some code.

response.StatusCode = 301;
response.AddHeader("Location", "http://www.cptloadtest.com");
response.End();

You may have noticed that, unlike the title of this blog post, I did not use a URL rewrite. HTTP 301 (and 302) redirects are HTTP Response Codes that are returned to the client browser, and the client then requests the new URL. A URL Rewrite leaves the original URL in place, and renders a different page instead, without visibility to the client browser or end-user. If I were to URL rewrite my blog from page1.aspx to page2.aspx, the URL in your address bar would still list page1.aspx, even though the content was from page2.aspx. The end-user (and the search engine) never know about the URL for page2.aspx. However, with a HTTP redirect, the content and the address bar would both be page2.aspx.

I ran through Google to see if anyone had solved this problem in the past. I came across a Scott Hanselman post on HTTP 301, which mentions a fantastic drop-in redirect module by Fritz Onion. I was elated when I found this module, and it was very easy to implement. Drop the assembly into your application's bin, add a few lines into the web.config, and enjoy redirection bliss. The module also supports both HTTP 302 and HTTP 301 redirects through the "permanent" attribute in the redirection rules.

<?xml version="1.0"?>
<configuration>
  <configSections>
    <section name="redirections"
      type="Pluralsight.Website.XmlSerializerSectionHandler, redirectmodule" />
  </configSections>
  <!-- Redirect Rules -->
  <redirections type="Pluralsight.Website.redirections, redirectmodule">
    <!-- Wordpress Post Redirects //-->
    <add targetUrl="/default\.aspx\?p=86"
      destinationUrl="/2007/09/22/ManagingMultipleEnvironmentConfigurationsThroughNAnt.aspx"
      permanent="true" />
    <add targetUrl="/default\.aspx\?p=74"
      destinationUrl="/2007/02/09/Flash8DepthManagerBaffledByThoseWithoutDepth.aspx"
      permanent="true" />
    <add targetUrl="/default\.aspx\?p=72"
      destinationUrl="/2006/10/20/IE7Released.aspx"
      permanent="true" />
    <add targetUrl="/default\.aspx\?p=70"
      destinationUrl="/2006/10/17/ClearingFlashIDEWSDLCache.aspx"
      permanent="true" />
    <add targetUrl="/default\.aspx\?p=69"
      destinationUrl="/2006/10/10/CruiseControlNetV11ReleasedOct1.aspx"
      permanent="true" />

    <!-- ...More Redirects -->
  </redirections>
  <system.web>
    <httpModules>
      <add name="RedirectModule"
        type="Pluralsight.Website.RedirectModule, redirectmodule" />
    </httpModules>
  </system.web>
</configuration>

The entire implementation took only a few minutes. It seemed like it took longer to upload the changes to the blog than it did to make the local edits. The solution is also very clean, as it required no modification to the existing application beyond integrating the configuration blocks into the web.config. Blog traffic will now seamlessly redirect from links that use the old WordPress URL to post that use the new DasBlog URL. Search Engines also update their links, and the page ranking for each post isn't lost into the ether just because the URL changed. All is well with the world, again.

Next up: Part 3. URL redirection also plays a role in Search Engine Optimization. In Part 3, I will go over some ways that you can use HTTP redirects to improve your search engine listings, as well as discuss some improvements I made to Fritz Onion's redirect module in the name of SEO.

URL Rewrite

Technorati Tags: ,,
Tuesday, 11 November 2008 12:36:34 (Eastern Standard Time, UTC-05:00)  #    Comments [0] - Trackback

Filed under: ASP.Net | Programming

A few months ago I switched my blogging engine from WordPress to DasBlog. Though I do feel that WordPress is a more mature engine, with a more robust feature set and a better plug-in community, I wanted a site that was built on .NET. Being a .NET developer, I wanted something I could tinker with,  modify, and adjust to my liking.

Redirecting WordPress URL Format to DasBlog

One of the pain points of the switch was with the differences in how the two blogging engines generated their URLs. As an example, my post on the Collapse All macro for the Visual Studio Solution Explorer, originally written in WordPress, went from a URL of cptloadtest.com/?p=56 to cptloadtest.com/2006/05/31/VSNetMacroCollapseAll.aspx. A few sites, such as Chinhdo.com, link to the post's old URL, which without effort to put a redirect in place would return HTTP 404: File Not Found under the new engine.

Enter URL redirects. I needed a way to translate one URL into another. More specifically, since WordPress retrieves all of its posts by query string (using the 'p' key), I needed to translate a specific query string key/value pair into a URL. But, I didn't want to have to recompile any code.

There are a view client-side redirecting options available:

Meta Refresh

<meta http-equiv="refresh" content="0;url=http://www.cptloadtest.com/">

The Old-School HTML way of redirecting a page. Nothing but HTML is needed. Only access to the base HTML page is required. Place the above HTML within your <HEAD> tag, reformatting the content value with "X;url=myURL", where X is the number of seconds to wait before initiating the redirect, and myURL is the destination URL. Any browsers will obey Meta-Refresh, regardless of JavaScript's enabled setting, but the simple implementation brings with it simple features. Meta-Refresh will redirect any request the page, regardless of the query string, and there is no simple way to enable it only for the specific key/value query string pair. Because all WordPress requests are to the domain root--a single page--and referenced by query string, this would not work for my needs. If the old request was instead to a unique former page, such as /post56.html, I could go create a new copy of post56.html as just a stub, and have each page Meta-Refresh to the post's new location. But even if this did apply, it's too much work to create 56 stub pages for 56 former posts.

JavaScript Redirect

<script type="text/javascript">
<!--
window.location = "http://www.cptloadtest.com/"
//-->
</script>

This one requires JavaScript to work. Since the query string is on the domain root, the request is serving up Default.aspx and applying the query string to it. DasBlog doesn't observe the "p" query string key, so it will not perform any action against it, but the query string is still available to client-side scripts. I can add JavaScript code to perform regular expression matches on the URL (window.location), and upon match rewrite the old URL to the new and redirect. It's relatively simple to create new match patterns for each of my 56 posts, and I can place all of my new client-side code atop Default.aspx.

var oldPath = "/?p=56";
var newPath = "/2006/05/31/VSNetMacroCollapseAll.aspx";
if (document.URL.indexOf(oldPath) > 0)
{
  window.location.replace(document.URL.replace(oldPath, newPath));
}

However, since the patterns are in client-side code, they are visible to end-users who view source. Users will also see page-flicker, as the Default.aspx is served up using the old URL, only to be redirected and refreshed under the new URL; a side-effect of downloading the page twice is that my bandwidth is also doubled for that single request, since users downloaded the page twice.

What it all means

All of the options above result in functionality similar a HTTP 302, otherwise known as a Temporary Redirect. This class of redirect is meant for simple forwarding or consolidation that is either of temporary nature or part of intended functional implementation. An example of where this would be used is if after one page is finished processing, another should be returned, such as if authentication is complete on a login page and the client should be redirected to a home page or landing page. With a 302, the original page is still a valid page, and users should still go to it in the future, but under certain scenarios there is an alternate page should be used.

The alternative to a 302 is a HTTP 301, otherwise known as Moved or a Permanent Redirect. The 301 is for files which have permanently changed locations and come with an implied "please update your links" notice. The HTTP 301 is ultimately what I was looking for. cptloadtest.com/?p=56 is a defunct URL that will never again see light of day; users, web sites, and (most importantly) search engines should update their references to the new DasBlog format of the post's URL. Client-side coding doesn't have the ability to create an HTTP 301, so it was beginning to look like I may either have to modify DasBlog code to get my 301s or live without. But, I found a way; this site now has all of the 301 goodness I craved, while keeping the DasBlog code pure.

It's all about HTTP Modules.

In Part 2, I will go over how to use HTTP Modules to implement both HTTP 301 and HTTP 302 redirects, all with simply dropping a file into your application bin and adding a new section to your web.config. No compile required.

URL Rewrite

Technorati Tags: ,
Thursday, 06 November 2008 10:01:33 (Eastern Standard Time, UTC-05:00)  #    Comments [1] - Trackback

Filed under: ASP.Net | Programming

Many .Net developers that have experience in presentation-layer development have previous exposure to this one, but to those who haven’t, I must share: Request.ApplicationPath is evil! Request.Application path should never be used. Ever. I hate it!

It’s misgivings are most commonly exposed when concatenating strings to the end of it to create a URL of some sort.

sURL = Request.ApplicationPath & “/someDirectory/somePage.aspx”

This is evil. Neither will work in all situations due to the method’s inconsistency with trailing slashes.

If the application root is in a sub-directory, say “http://server/myRoot/index.aspx”, then the appPath is “/myRoot”. Note: there is no slash at the end, and the above sURL gets a value of “/myRoot/someDirectory/somePage.aspx”.

If the application root is not in a sub-directory, say “http://server/index.aspx”, then the appPath is “/”. Note: there is a slash at the end, and the above sURL gets a value or “//someDirectory/somePage.aspx”. In this case, rather than requesting “http://server/someDirectory/somePage.aspx”, wonderful Internet Explorer requests “http://somedirectory/somePage.aspx”. (I don’t fault IE for this. I commend it. It is actually one of the few cases where IE doesn’t kludge together a band-aid for Developer mistakes.)

So, don’t use Request.ApplicationPath. Ever. With no exception. You could make a method, perhaps MyUtilities.ApplicationPath, that checks to see if the return contains a trailing ‘/’, and if it does, give it the axe. This will turn your domain-root appPath to an empty string. Use your new method rather than Request.ApplicationPath, and all will be well with the world. But, don’t do it! Don’t make a new method. That just continues the evilness.

Use Page.ResolveURL(”~/someDirectory/somePage.aspx”) or the counterpart Control.ResolveURL if you want it to be relative to the control’s location. This is the only scenario you should use. ApplicationPath is evil!

Wednesday, 26 July 2006 08:19:23 (Eastern Daylight Time, UTC-04:00)  #    Comments [4] - Trackback

NAnt hates .Net’s resource files, or .resx. Don’t get me wrong–it handles them just fine–but large quantities of resx will really bog it down.

Visual Studio loves resx. The IDE will automatically create a resource file for you when you open pages and controls in the ‘designer’ view. Back when we still used Visual SourceSafe as our SCM, Visual Studio happily checked the file in and forgot about it. Now, our 500+ page application has 500+ resource files. Most of these 500+ resource files contain zero resources, making them useless, pointless, and a detriment to the build.

This morning I went through the build log, noting every resx that contained zero resources, and deleted all of these useless files.

The compile time dropped by 5 minutes.

Moral of the story: Be weary of Visual Studio. With regards to resx, VS is a malware program that’s just filling your hard drive with junk. If you use resx, great, but if you don’t, delete them all. NAnt will love you for it.

Wednesday, 15 February 2006 11:31:31 (Eastern Standard Time, UTC-05:00)  #    Comments [0] - Trackback

Filed under: ASP.Net | Programming | Tools | Visual Studio

“It compiles! Ship it!”

Microsoft has sent Visual Studio 2005 to the printers. That brings .Net 2.0 to the table in all of its glory. The official release date is still November 7, and though it is available now to all of us MSDN subscribers (though the site is too flooded to ping, let alone download), there is still some question on if the media will be ready in time to go in all of the pretty little VS05 boxes at your local Microsoft store.

Friday, 28 October 2005 13:40:03 (Eastern Daylight Time, UTC-04:00)  #    Comments [0] - Trackback

Filed under: ASP.Net | Programming | Task Automation

The default settings of NUnit, TestRunner, and Test Driven Development all want different copies of the app.config at different locations. If ProjectName creates ProjectName.dll, then NUnit wants ProjectName.config, TR wants ProjectName.dll.config, and TDD wants TargetDir\ProjectName.dll.config. This is a lot of work to put in the post-build event of every unit test project, and can be even more work when another testing tool comes along that wants yet a new config filename. The best way to manage all of these file copies is through a common post-build event call.

Many probably opt for a NAnt script, but we found that passing in the required paths can sometimes cause NAnt to get confused, and it won’t properly parse the parameter listing. So, we went with a command file, instead.

CopyConfigs.cmd

rem for nunit

copy “%~1App.config” “%~1%~2.config”

 

rem for testrunner

copy “%~1App.config” “%~1%~2.dll.config”

 

rem for testdrivendevelopment

copy “%~1App.config” “%~3.config”

VS.Net Post Build Event

call “C:\MyPath\CopyConfigs.cmd” “$(ProjectDir)” “$(ProjectName) “$(TargetPath)”

VS.Net already includes a series of NAnt-like properties for project names, project directories, target [assembly] filenames, etc; these come in handy for creating a universal script. Placing the path references in quotes allows for spaces and other characters (Except more quotes) in the path. Executing the command file through a call allows us a little more versatility with the argument references (%~1 removes the surrounding quotes from the argument value, allowing us to append a few together without jacking the subsequent path).

Monday, 08 August 2005 13:48:20 (Eastern Daylight Time, UTC-04:00)  #    Comments [0] - Trackback

Filed under: ASP.Net | Tools

In code deployment, it is often necessary to perform tasks that must be executed locally on the destination box, such as installing through an MSI or installing assemblies to the GAC through GACUtils. Thankfully, there is a way that this can all be done remotely, with any process, as long as it can be accessed through a command prompt. The destination computer will think that you are working on it directly, though it may just be your NAnt script doing the work for you.

SysInternals publishes a tool called PsExec. It allows you to execute a program remotely on a remote machine. To the remote machine the process is running locally. Because of this, you can use traditional command line tools to run programs and utilities, such as GACUtil to install a new assembly to the GAC on a remote box–a feature that most other options don’t support.

PSExec \MyServer "C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\GACUtil.exe" "C:\bin\MyAssembly.dll"

Note: the paths are all ‘local’ paths on \\MyServer, just as you would enter from a command prompt in an RDP session to MyServer. You will also need to customize the paths to include whatever location and framework version your remote machine uses.

As for me, because our web applications make thorough use of the GAC, our only deployment method is a VS.Net Deployment project to create a MSI. We have NAnt scripts that upload the MSI to remote machines then execute PsExec run the installation (MSIExec) in unattended mode. It has brought our deployment time down from a manual 30-45 minutes to an automated 15 minutes, and allows code managers to spend those 30-45 minutes doing something else. We save even more time when we deploy to production, which contains an 8-server web farm.

Tuesday, 26 July 2005 11:39:49 (Eastern Daylight Time, UTC-04:00)  #    Comments [0] - Trackback

Filed under: ASP.Net | Programming

Scott Hanselman has a good post today about the HttpOnly cookie attribute. It secures the cookie from access via the DOM. “The value of this property is questionable since any sniffer or Fiddler could easily remove it. That said, it could slow down the average script kiddie for 15 seconds.”

Read Scott’s full blog entry.

Here’s the meat-and-potatoes of what Scott came up with; it’s for your global.asax:

protected void Application_EndRequest(Object sender, EventArgs e)
{
    foreach(string cookie in Response.Cookies)
    {
        const string HTTPONLY = ";HttpOnly";
        string path = Response.Cookies[cookie].Path;
        if (path.EndsWith(HTTPONLY) == false)
        {
            //force HttpOnly to be added to the cookie
            Response.Cookies[cookie].Path += HTTPONLY;
        }
    }
}
Friday, 22 July 2005 14:01:58 (Eastern Daylight Time, UTC-04:00)  #    Comments [0] - Trackback