8/22/10

Instant Cookies

Look at the two methods shown below :

private void ModifyCookies()
{
HttpCookie objCookie = Request.Cookies["Cowboy"];
if (objCookie.Values.Get("position") == null) objCookie.Values.Add("position", "Receiver");
Response.Cookies.add(objCookie);
SetPlayerProperties();
}


private void SetPlayerProperties()
{
HttpCookie objCookie = Request.Cookies["Cowboy"];
Player objPlayer = new Player();
objPlayer.Positon = objCookie.Values.Get("position");
}

In the first method ModifyCookies() we get the cookie from the HttpRequest cookies collection. Let as assume the cookie was as follows:
//Cowboy = FirstName=Miles&LastName=Austin&Location=Dallas&Age=25

We then added another key/value pair to the cookie and the modified cookie now looks like :
Cowboy = FirstName=Miles&LastName=Austin&Location=Dallas&Age=25&position=Receiver

We then add the cookie to the HttpResponse cookies collection.

We then call the second method SetPlayerProperties() in which we access the new key that we have added to the cookie above.

NOTE : At this point the response has not been sent to the client yet, but we are still able to access the new key from the Request.Cookies collection.

The point to remember is (reference : Microsoft MSDN):

After you add a cookie to the HttpResponse.Cookies collection, the cookie is immediately available in the HttpRequest.Cookies collection, even if the response has not been sent to the client.

8/15/10

When denormalization helps

I had developed a web page that displayed the log of all the invoices in a given project. There were about ten columns in the log, each one displaying a different piece of information about the invoice. These invoices were created against contracts and there is a one-many relationship between a contract and an invoice.

Two of those columns,"WorkCompletedToDate" and "MaterialPurchasedToDate" represented the amount of work done and material purchased(in dollars) prior to the current invoice on a given contract. So if we were looking at invoice No.3 on a contract X, the "WorkCompletedToDate" and "MaterialPurchasedToDate" represent the sum of the values for those fields from invoice No.1 and invoice No.2 on the same contract X.The values in these two columns were not stored in the database and were always being calculated at runtime.

There were thousands of invoices in the project and the runtime calculations for these two columns began to slow down the web page.I tried to optimize the stored procedure and functions and other code relating to the log, but nothing seemed to help.

I then hit upon the idea of denormalizing the invoices table by adding two columns to store these values, instead of calculating them at runtime. This would also require a script to populate these values for all the existing invoices in the database. After I made these changes, the page began to load real fast.

Though denormalization might not be the best approach in a lot of scenarios and must be used with caution, it does come handy in some situations, and is definetely an option that must be kept open, especially when faced with performance issues.

8/10/10

The State Design Pattern

Sometime ago I was given the task of designing a module for creating and managing work orders for one of our clients. For those of you wondering what a work order is..let me give you an example..

Let's say you live in an apartment and your air conditioning system is not working. what do you do? You immediately call up the apartment office to report it. So what you are doing is initiating a work order process. The office assistant takes your request and creates a work order for repairing the a/c. This work order is then sent to a technician who sends an estimate to the assistant. The assistant or the assistant's supervisor approves the cost estimate and the technician gets to work. The technician completes the job and reports back to the assistant. The assistant then closes the work order(after confirming with you obviously). This is a typical work order workflow process.

I had to develop a user interface to facilitate this entire process. I decided to browse through the GoF design patterns to see if I could find some pattern that would serve the purpose. I obviously ruled out the creational and structural patterns since I was not looking along those lines. So I started looking at the behavioral patterns wherein I came across the State Design Pattern. After carefully studying the pattern I decided that I was going to go with it.

Why the State Design Pattern?
The work order process goes through different stages and the behavior changes at every step. It is the same work order that appears to take on different forms at different stages. We can use a single object and keep altering it's underlying behavior with every step in the work flow process. We can tie the user interface to the underlying behavioral changes so that, as the flow changes, the UI will also change accordingly.

The UML is as follows:

















How it works:
  • The UI interacts with the State Manager which is the object that changes it's underlying behavior
  • The State Manager changes it's underlying behavior through an instance of  the Abstract State class, which happens to be one of its member fields.
  • This instance points to a different concrete instance of type State at different stages of the work order process. As this happens, it appears as if the State Manager is changing it's underlying behavior.
  • The UI also changes from step to step depending on the properties of the State Manager.

 Code:

public class WorkOrderUI: System.Web.UI.Page
{
   StateManager objStateManager;
   protected void Page_Load(object sender, EventArgs e)
  {
     objStateManager = new StateManager();
     DisplayUI();
   }
  
/*render the UI depending on the state manager's underlying state*/
private void DisplayUI()
{
    if(objStateManager.IsApproved) //do so and so
      btnApprove.visible = false;
}

  /*save handler, calls the statemanager that will change it    behavior as a result of this save*/
   protected void Save(object sender, EventArgs e)
  { 
     objStateManager.SaveState();
   }
}

public class StateManager
{
   State objState;
   public StateManager()
  {    
     objState = GetState();
  }

 private State GetState()
{
  /*depending on various properties this method returns the current state*/
   return new WorkOrderState();//example
}

public void SaveState()
{
   //saves state
    objState.SaveData();
}

}

public abstract class State
{
   protected abstract State GetData();
   protected abstract void SaveData();
}

public class WorkOrderRequest:State
{
   protected State GetData()
  {
     //implement functionality specific to this state
   }

  protected void SaveData()
  {
     //implement the save specific to this state
  }
}

other state classes are implemented in a similar manner.

8/9/10

Pros and Cons of using XML data type in SQL Server 2005

Recently I developed a web-based tool using ASP.NET and C#, that enables users to create custom forms in a matter of minutes.Every form can have any number of controls like Textboxes, Radiobuttons,Checkboxes,Labels etc.Since the form size can vary from say 5 fields to 20 fields to 50 fields,there was no way I could create a flat table structure to store this data. So I decided to use the XML data type in SQL Server 2005 to store the form fields configuration.


The rendering part of the tool parses this xml configuration(using LINQ to XML) and renders the form.Let us assume that this form is going to be used for survey purposes. The survey users can fill in the data and complete the survey. All this works just fine and the survey is successfully completed.


Then comes the reporting(SSRS). The management wants to see the results grouped and sorted in a multitude of ways. SQL Server does not have too much of an API for querying XML columns. So I had to use whatever was available(the query,value,exist,modify and nodes methods) along with some SQL cursors to come up with the desired results in the desired format.


The problem with this approach was that this parsing(which was happening at runtime) took time and the time taken was directly proportional to the number of survey instances, so as the data grew, the reporting became slower and slower. So while XML was very convenient way to store variable length data, it was not very easy to work with, in terms of reporting or analysis purposes.


I managed to solve the issue with reporting by creating a flat table structure for storing the survey data(since the configuration is constant once the form is created).I then created a SQL agent that runs as a scheduled task during the non-peak hours and performs the time consuming task of parsing instance xml data and populating the flat table. I then pointed the reports to the flat table. This speeded up the reporting process.


So while XML data type is suitable for storing variable length data, the developers need to note that it is not very easy to work with the XML, with the limited API in SQL Server. One way to solve the problem would be to get the data out of SQL and use the powerful .NET API to get the desired result. The other way would be to create SQL agent(as described above) to pre-populate data into flat tables and then work with those tables. But all said and done, the XML data type is a very powerful feature and provides tremendous flexibility. I would definetely recommend it.