Thursday 31 December 2009

Design Pattern 4 - Command Pattern

A Command pattern is an object behavioral pattern that allows us to achieve complete decoupling between the sender and the receiver. (A sender is an object that invokes an operation, and a receiver is an object that receives the request to execute a certain operation. With decoupling, the sender has no knowledge of the Receiver's interface.) The term request here refers to the command that is to be executed. The Command pattern also allows us to vary when and how a request is fulfilled. Therefore, a Command pattern provides us flexibility as well as extensibility.

To be continued...

Wednesday 14 October 2009

Design Pattern 3 - Factory Method Pattern

The Factory Method pattern allows for the instantiation of objects at runtime. We can think of Factory Pattern as a factory which is responsible for "manufacturing" an object. A Parameterized Factory receives the name of the class to instantiate as argument.

Obviously, a factory is not needed to make an object. A simple call to new will do it for you. However, the use of factories gives the programmer the opportunity to abstract the specific attributes of an Object into specific subclasses which create them. In addition, one principle in OOP programming is to reduce coupling. Avoid using new key work means we also avoid the dependency between classes which make it much easier for unit testing.



There is one very good article in Wikipedia about Factory Method pattern, where using an example of Pizza factory produce different type of Pizzas. The code is in Java, with a little effort I have re-written it in C# as the code shown below:

using System;

namespace FactoryMethodPattern
{
abstract class Pizza
{
public abstract double getPrice();
}

class HamAndMushroomPizza : Pizza
{
public override double getPrice()
{
return 8.5;
}
}

class DeluxePizza : Pizza
{
public override double getPrice()
{
return 10.5;
}
}

class HawaiianPizza : Pizza
{
public override double getPrice()
{
return 11.5;
}
}

class PizzaFactory
{
public enum PizzaType
{
HamMushroom,
Deluxe,
Hawaiian
}

public static Pizza createPizza(PizzaType pizzaType)
{
switch (pizzaType)
{
case PizzaType.HamMushroom:
return new HamAndMushroomPizza();
case PizzaType.Deluxe:
return new DeluxePizza();
case PizzaType.Hawaiian:
return new HawaiianPizza();
default:
return null;
}
}
}

class Program
{
static void Main(string[] args)
{
// Loop with foreach through a Enum
foreach (PizzaFactory.PizzaType pizzaType in
Enum.GetValues(typeof(PizzaFactory.PizzaType)))
{
Console.WriteLine("Price of " + pizzaType + " is £"
+ PizzaFactory.createPizza(pizzaType).getPrice());
}
}
}
}



Reference: Factory method pattern in Wikipedia.

Saturday 3 October 2009

Design Pattern 2 - Decorator Pattern

I finally can’t resist the temptation and joined the Sky Sports a few weeks ago, as I am a big fun of English premiere league. While I was placing the order on the internet, somehow the Decorator pattern came into my mind.

By definition, the Decorator Pattern is used for adding additional functionality to a particular object as opposed to a class of objects. It is easy to add functionality to an entire class of objects by subclassing an object, but it is impossible to extend a single object this way. With the Decorator Pattern, you can add functionality to a single object and leave others like it unmodified.



To implement Decorator Pattern for sky.com, let us create an interface first, we named it as ITVBundle.

public interface ITVBundle
{
string Description();
double Cost();
}

To subscribe sky sports or movie channels, you have to subscribe a basic pack even you don’t want to watch them. So the first class I need to create is BasicPack which implement ITVBundle interface.

public class BasicPack : ITVBundle
{
public double Cost()
{
return 18.50;
}

public String Description()
{
return "Basic Packs";
}
}

An decorator abstract class which also implement ITVBundle interface:

public abstract class AddOnDecorator : ITVBundle
{
public abstract string Description();
public abstract double Cost();
}

The next bit is my favourite, which is to add Sports packs or Movies Pack to the Basic Pack. This works by adding a new decorator class that wraps the original class. Let’s look at the example below:

public class AddSportsPack : AddOnDecorator
{
ITVBundle _itv;
public AddSportsPack(ITVBundle tvBundle)
{
this._itv = tvBundle;
}

public override string Description()
{
return _itv.Description() + ", with Sports Pack";
}

public override double Cost()
{
return _itv.Cost() + 9.99;
}
}

From the above you can see the wrapping is typically achieved by passing the original object as a parameter to the constructor of the decorator when it is created. The decorator implements the new functionality, but for functionality that is not new, the original (wrapped) class is used. The decorating class must have the same interface as the original class.

Here is the example on using Decorator Pattern:

BasicPack bp = new BasicPack();
AddSportsPack plan1 = new AddSportsPack(bp);

Please see the full working code:

using System;

namespace DecoratorPattern
{
public interface ITVBundle
{
string Description();
double Cost();
}

public class BasicPack : ITVBundle
{
public double Cost()
{
return 18.50;
}

public String Description()
{
return "Basic Packs";
}
}

public abstract class AddOnDecorator : ITVBundle
{
public abstract string Description();
public abstract double Cost();
}

public class AddMoviePack : AddOnDecorator
{
ITVBundle _itv;
public AddMoviePack(ITVBundle tvBundle)
{
this._itv = tvBundle;
}

public override string Description()
{
return _itv.Description() + ", with Movie Pack";
}

public override double Cost()
{
return _itv.Cost() + 9.99;
}
}

public class AddSportsPack : AddOnDecorator
{
ITVBundle _itv;
public AddSportsPack(ITVBundle tvBundle)
{
this._itv = tvBundle;
}

public override string Description()
{
return _itv.Description() + ", with Sports Pack";
}

public override double Cost()
{
return _itv.Cost() + 9.99;
}
}

class Program
{
static void Main(string[] args)
{
BasicPack bp = new BasicPack();
AddMoviePack plan1 = new AddMoviePack(bp);
AddSportsPack plan2 = new AddSportsPack(plan1);

Console.WriteLine("You have choosen plan 2: {0} \nThe cost is: £{1}",
plan2.Description().ToString(), plan2.Cost().ToString());
}
}
}

The output will be looking like:



Use the Decorator pattern when:

- You have an existing component class that may be unavailable for subclassing.
- You want to attach additional state or behaviour to an object dynamically.
- You want to make changes to some objects in a class without affecting others.
- Avoid subclassing because too many classes could result.

Tuesday 29 September 2009

Design Pattern 1 – Strategy Pattern

In the past 6 months, I have been reading and studying the well-known book Design Patterns, Elements of Reusable Object-Oriented Software by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (GOF). While studying the book, I do feel it has taken me to the next level of understanding OOP concepts and has given me more confidence to write elegant and reusable code. I think any Object-Oriented software developer should read the book. In my next few articles I will be covering the most frequently used patterns in .net applications.

The first design pattern I’d like to talk about is Strategy Pattern. The main purpose of the Strategy pattern is to decouple concrete code into separate classes, which promotes reusability. As your project grows in size, having reusable modules is a necessity. This pattern also allows you to easily add new modules into a C# ASP .NET software design with limited impact on the rest of the system.



Let’s assume one situation that you are trying to print out a greeting message on screen in different languages. Here is the non-pattern way how your code may look like:

class HelloWorldClientNoPattern
{
public void SayHello(string strName, string strLanguage)
{
switch (strLanguage)
{
case "english":
Console.WriteLine("Hello World " + strName);
break;
case "spanish":
Console.WriteLine("Hola mundo " + strName);
break;
case "german":
Console.WriteLine("Hallo Welt " + strName);
break;
}
}
}

class Program
{
static void Main(string[] args)
{

HelloWorldClientNoPattern client = new HelloWorldClientNoPattern();
client.SayHello("Can Lu", "english");
client.SayHello("Can Lu", "spanish");
client.SayHello("Can Lu", "german");

}
}

What is wrong with this approach? Well it is nothing wrong it works but there are at least couple of problems.
- The code above is not reusable. If we want to use the SayHello method somewhere else, I have to write the same code again.
- The code is not decoupled. If you want to add a new greeting language. For example if you want to print SayHello in Chinese, you have to modify the client class.

The strategy pattern is to solve this kind of problem. The most important part of the Strategy pattern is the main interface. This is what allows the polymorphism and allows us to pass the client any type of algorithm, as long as it uses the same interface. The interface will look like:

public interface IHelloWorldStrategy
{
void SayHello(string strName);
}

Then it’s time to create different classes to implement this interface. For example we could have:

class HelloWorldEnglish: IHelloWorldStrategy
{
public void SayHello(string strName)
{
Console.WriteLine("Hello world " + strName);
}
}

class HelloWorldChinese: IHelloWorldStrategy
{
public void SayHello(string strName)
{
Console.WriteLine("Ni Hao " + strName);
}
}

Now we can rewrite our client class. Instead of using Switch Case/If then else, we're using an Interface as the implementation of the strategy. This allows us a generic pointer to whichever algorithm we end up actually using.

class HelloWorldClient
{
IHelloWorldStrategy strategy;
public HelloWorldClient(IHelloWorldStrategy s)
{
this.strategy = s;
}

public void SayHello(string strName)
{
strategy.SayHello(strName);
}
}

Notice the constructor takes a variable of the interface type. This is powerful because, if we derive each algorithm class from the same interface, then we can pass the client algorithm and it will be able to handle any kind algorithms that we create; as long as they implement the same interface, can be utilized in this client.

Please find the full working code below:

using System;

namespace StrategyPatternDemo
{
public interface IHelloWorldStrategy
{
void SayHello(string strName);
}

class HelloWorldEnglish: IHelloWorldStrategy
{
public void SayHello(string strName)
{
Console.WriteLine("Hello world " + strName);
}
}

class HelloWorldSpanish : IHelloWorldStrategy
{
public void SayHello(string strName)
{
Console.WriteLine("Hola mundo " + strName);
}
}

class HelloWorldGerman : IHelloWorldStrategy
{
public void SayHello(string strName)
{
Console.WriteLine("Hallo Welt " + strName);
}
}

class HelloWorldClient
{
IHelloWorldStrategy strategy;
public HelloWorldClient(IHelloWorldStrategy s)
{
this.strategy = s;
}

public void SayHello(string strName)
{
strategy.SayHello(strName);
}
}

class Program
{
static void Main(string[] args)
{
HelloWorldClient myHelloWorld = new HelloWorldClient(new HelloWorldEnglish());
myHelloWorld.SayHello("Can Lu");

myHelloWorld = new HelloWorldClient(new HelloWorldSpanish());
myHelloWorld.SayHello("Can Lu");

myHelloWorld = new HelloWorldClient(new HelloWorldGerman());
myHelloWorld.SayHello("Can Lu");
}
}
}

The output will be like:



There are a number of advantages to structuring a family of algorithms in this manner, but the most important is that doing so decouples the client from the implementation details of any particular algorithm. This promotes extensibility in that additional algorithms can be developed and plugged in seamlessly, as long as they follow the base interface specification, thereby allowing algorithms to vary dynamically. Moreover, the Strategy pattern eliminates conditional statements that would otherwise litter client code. Whenever we have switch case statement in code, we probably need to think twice, should we use Strategy Pattern to replace it.

Two ways of deleting duplicated rows in Oracle

The most effective way to detect duplicate rows in Oracle is to join the table against itself as shown below. Assume table_name has two columns col1 and col2

SELECT *
FROM table_name A
WHERE A.rowid > (SELECT min(B.rowid)
FROM table_name B
WHERE A.col1 = B.col1
AND A.col2 = B.col2)

To delete the duplicate rows:

DELETE FROM table_name A
WHERE A.rowid > (SELECT min(B.rowid)
FROM table_name B
WHERE A.col1 = B.col1
AND A.col2 = B.col2)

You can also detect and delete duplicate rows using Oracle analytic functions:

delete from table_name
where rowid in (select rowid
from (select rowid,
row_number() over(partition by col1, col2 order by col1, col2) dup
from table_name)
where dup > 1);

Wednesday 23 September 2009

Get URL Querystring Parameters using Javascript

As we know in ASP.net we can use Request.QueryString["variableName"] to retrieve the values of the variables in the HTTP query string. However if we need to get the parameter value in the client script, for instance we want to have an alert window to display a parameter value is not as straight forward as we do in server-side programming. Use the gup() helper function in JavaScript below can help us with this

function gup(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(window.location.href);
if (results == null)
return "";
else
return results[1];
}

The way that the function is used is fairly simple. Let's say you have the following URL:

http://localhost/script/directory/NAMES.ASP?name=Fred&id=123

You want to get the value from the frank parameter so you call the javascript function as follows:

var name_param = gup( 'name' );

Thursday 13 August 2009

Exporting data to Excel from a GridView in ASP.net

Hate or like it, regardless how pretty your GridView looks like, how easy it’s to print, customers just want to export everything to excel to do their own manipulation. So willy-nilly we must find a good solution to handle this. In asp.net, it’s actually very easy to do, but there are a few things we need to be aware of. Let’s have a look at the function first.

private void Export2Excel(GridView gv, string strFileName)
{
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=" + strFileName);
Response.Charset = "";

// If you want the option to open the Excel file without saving then
// comment out the line below
// Response.Cache.SetCacheability(HttpCacheability.NoCache);

Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
gv.RenderControl(htmlWrite);

Response.Write(stringWrite.ToString());

Response.End();
}

By calling above method in button click event, we can export any GridView to excel.

protected void imgExp2Excel_Click(object sender, ImageClickEventArgs e)
{
Export2Excel(GridView1, "demo.xls");
}

However there are a few things you need be aware of:

1. If you receive a HttpException regarding to type 'GridView' must be placed inside a form tag with runat=server. You need to overide VerifyRenderingInServerForm Method as below:

public override void VerifyRenderingInServerForm(Control control) { }

2. In Ajax enabled environment. You will very likely to receive an exception error as: Exception is Sys.WebForms.PageRequestParserErrorException .The message received from the server could not be parsed. This is because modified Response object cannot work in Ajax Framework. The workaround is to use asynchronous post back through the trigger in asp:UpdatePanel. Here are the code:






3. We must turn off AllowPaging to false before we are doing the export.

protected void imgExp2Excel_Click(object sender, ImageClickEventArgs e)
{
GridView1.AllowPaging = false;
Export2Excel(GridView1, "Overview.xls");
GridView1.AllowPaging = true;
}

4. If you see this exception Exception RegisterForEventValidation can only be called during Render().You need to notify ASP.Net that not to validate the event by setting the EnableEventValidation flag to FALSE.

Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
CodeFile="demo.aspx.cs" Inherits="demo" EnableEventValidation = "false"

That has covered all errors I have seen in the past. Please let me know if there are any problems or questions. Another very good post I found on aspsnippet, is definitely worth a read.