Monday, July 14, 2008

Factroy Design Pattern

Abstract Factory is commonly known as factory pattern. In this pattern all the classes involved implement/realize the same interface and the compiler only knows that the created object implements the specific interface but not the object's type. This is very flexible when you need to make a creation decision at runtime depending on some aspect of object's behavior rather than it's type.

Example: Imagine that there is a rental store of cars, bikes, trucks, etc but you want to deliver a vehicle depending on the customer's choice.

Programmatically you can make a run time decision using a switch statement to return a new instance of a class which implements the specific interface depending on the customer's choice. As you can see in the constructor of "Journey" class we are getting vehicletype of the current customer and passing it to the VehicleSupplier class's static method "GetVehicle". VehicleSupplier relies on a switch statement to return the vehicle needed, so if you observe here compiler just knows that newly created object implements the "IVehicle" interface but not if it's a car, truck or a bike upfront.

public class Journey

{

public IVehicle rentedVehicle;
public Journey(string customerID)
{
VehicleType vType = Customer.GetVehicleType(customerID);
/*Here is the late binding. Compiler doesn't know the type of the object except that it implements the IVehicle interface*/

rentedVehicle = VehicleSupplier.GetVehicle(vType);

}

//Method for beginning the journey
public void BeginJourney()
{
if (rentedVehicle != null)
{
rentedVehicle.Drive();
}
}
//Method for parking the vehicle
public void ParkTheVehicle()
{
if (rentedVehicle != null)
{
rentedVehicle.Park();
}
}
}
//The class which returns the new vehicle instance depending on the //vehicle type
public class VehicleSupplier
{
public static IVehicle GetVehicle(VehicleType vType)
{
switch (vType)
{
case VehicleType.CAR:
return new Car();
case VehicleType.TRUCK:

return new Truck();
case VehicleType.BIKE:
return new Bike();
}
return null;
}
}
//The interface which will be implemented by Car, Truck and Bike //classes
public interface IVehicle
{
void Drive();
void Park();
}
//enum of the vehicle types
public enum VehicleType{ CAR = 1, TRUCK, BIKE };

Best Regards

Observer Design Pattern


Observer pattern involves a one-many dependency between objects where a change in an object(subject) needs to be notified to all it's dependents(observers).

Example: Consider a scenario where a job posting at some company got multiple applications. Whenever the job status changes (filled, removed or suspended) all the applicants of the job should be notified. In this case job object is subject and all the applicants are observers.

As you can see below "Job" is the subject class and all applicants of that particular job are observers. Job class has "Add" and "Remove" methods for adding and removing applicants to it's list. Whenever job status changes all the applicant objects would be notified through Notify method which in turn calls the "Update" method of the applicant object.

public class Job

{
private ArrayList applicants;
private JobStatus statusOfJob;
public Job()
{
applicants = new ArrayList();
}
public void Add(Applicant candidate)
{
applicants.Add(candidate);
}
public void Remove(Applicant candidate)
{
applicants.Remove(candidate);
}
public void Notify()
{
foreach (Applicant candidate in applicants)
{

candidate.Update(this);

}
}
public JobStatus Status {
get
{
return statusOfJob;
}
set
{
statusOfJob = value;

Notify();

}

}

}

//Jobstatus enumerator

public enum JobStatus

{

FILLED,

SUSPENDED,

REMOVED

};

/// This is Observer.

public class Applicant

{

//declare variables
string fname;
string lname;
string emailID;
string phoneNo;
public Applicant()
{
//
// TODO: Add constructor logic here //
}

#region Properties for exposing the member variables

#endregion
public void Update(Job appliedJob)

{

switch(appliedJob.Status)

{

case JobStatus.FILLED:
//Do something like sending email, //updating database, etc
break;
case JobStatus.REMOVED:

//Do something like sending email, //updating database, etc
break;
case JobStatus.SUSPENDED:

//Do something like sending email, //updating database, etc
break;
}
//Your own functionality
//End Of Functionality
}
}

Best Regards

Recursive Queries using Common Table Expressions (CTE) in SQL Server

Problem
In SQL Server 2000, you need to implement recursive queries to retrieve data which is presented in a hierarchical format. We normally resort to implementing views, cursors or derived tables and perform queries against them. The problem arises when the hierarchy level increases as SQL Server is limited to 32 levels of recursion. We need a better way to implement recursive queries in SQL Server 2005. How do we do it?

Solution
Common Table Expression (CTE) was introduced in SQL Server 2005 and can be thought of as a temporary result set that is defined within the execution scope of a single SELECT, INSERT, UPDATE, DELETE, or CREATE VIEW statement. You can think of CTE as an improved version of derived tables that more closely resemble a non-persistent type of view. Look at CTEs as your derived tables in SQL Server 2000. A CTE can be used in many of the same ways you use a derived table. CTEs can also contain references to themselves. This allows the developer to write complex queries simpler. CTEs can also be used in place of views. The use of CTEs provides two main advantages. One is that queries with derived table definitions become more simple and readable. While traditional T-SQL constructs that are used to work with derived tables normally requires a separate definition for the derived data such as a temporary table or a table-valued function, using CTEs make it easier to see the definition of the derived table with the code that uses it. The other thing is that CTEs significantly reduces the amount of code required for a query that traverses recursive hierarchies.

To understand what a CTE is all about, let's first take a look at the syntax to create it in SQL Server 2005.

Syntax
In general form a recursive CTE has the following syntax:

WITH cte_alias (column_aliases
AS 
(
cte_query_definition   --initialization
UNION ALL
cte_query_definition2 --recursive execution

SELECT FROM cte_alias 

You provide the CTE with an alias and an optional list of aliases for its result columns following the keyword WITH which usually defines the derived table based on the query definition; write the body of the CTE; and refer to it from the outer query.

To put this in the right perspective, let's come up with a simple example which uses recursion. We'll look at the Employees table in the Northwind database and see that a particular employee reports to another employee. One question we can come up with is, "Who reports to whom?" The Employees table is designed in such a way that the ReportsTo column is a foreign key field that refers to the primary key field EmployeeID. Thus, we can create a query to answer our question. A sample query using CTE will look something like this.

WITH Managers AS
(
--initialization
SELECT EmployeeIDLastNameReportsTo 
FROM Employees
WHERE ReportsTo IS NULL
UNION ALL
--recursive execution
SELECT e.employeeID,e.LastNamee.ReportsTo
FROM Employees e INNER JOIN Managers m 
ON e.ReportsTo m.employeeID
)
SELECT FROM Managers 

Code Walkthrough

  1. The recursive CTE, Managers, defines an initialization query and a recursive execution query
  2. The initialization query returns the base result and is the highest level in the hierarchy.  This is identified by the ReportsTo value of NULL, which means that the particular Employee does not report to anybody.  Depending on how the table is designed, the value can be anything as long as it represents the highest level in the hierarchy
  3. The recursive execution query is then joined to the initialization query using the UNION ALL keyword.  The result set is based on the direct subordinate as returned by the initialization query, which then appears as the next level in the hierarchy. Recursion occurs because of the query referencing the CTE itself based on the Employee in the Managers CTE as input. The join then returns the employees who have their managers as the previous record returned by the recursive query.  The recursive query is repeated until it returns an empty result set.
  4. The final result set is returned by querying the Managers CTE 

The sample query contains the elements that a recursive CTE must contain. What's more is that the code is a lot more readable. This enables the developers to write complex queries with ease.

You can also use a query hint to stop a statement after a defined number of loops. This can stop a CTE from going into an infinite loop on a poorly coded statement. You do this by including the MAXRECURSION keyword in the SELECT query referring to the CTE. To use it in the previous example

SELECT FROM Managers OPTION (MAXRECURSION 4

To create a similar yet non-recursive query that produces the same result in SQL Server 2000, you might come up with something similar to this code:

DECLARE @rowsAdded INT

--table variable to hold accumulated results
DECLARE @managers TABLE --initialize @managers who do not have managers
   
(EmpID INTMgrID INTprocessed INT DEFAULT(0))

INSERT @managers 
SELECT EmployeeIDReportsTo
FROM Employees 
WHERE ReportsTo IS NULL

SET @rowsAdded=@@rowcount 

--do this while new employees are added in the previous iteration 
WHILE @rowsAdded 
BEGIN

   
--mark employee records going to be found in this iteration with --processed=1 
   
UPDATE @managers SET processed=WHERE processed=0

   
--insert employees who report to employees not yet processed 
   
INSERT @managers 
   
SELECT EmployeeIDReportsTo
   
FROM Employees e 
   
INNER JOIN @managers ON e.ReportsTo r.EmpID 
   
WHERE ReportsTo <> EmployeeID AND r.processed 
          
   
SET @rowsAdded @@rowcount 

   
--mark employee records found in this iteration as processed 
   
UPDATE @managers SET processed=WHERE processed=

END 

SELECT 
FROM @managers 

Next Steps

Given the example above, hierarchical data structures, organizational charts and other parent-child table relationship reports can easily benefit from the use of recursive CTEs. Common Table Expression is just one of those T-SQL enhancements available for SQL Server 2005. CTEs bring us the chance to create much more complex queries while retaining a much simpler syntax. They also can lessen the administrative burden of creating and testing views for situations where the view will not be reused.

Saturday, June 28, 2008

TSQL : Paging with ROW_NUMBER()

In MSSQL 2000 we used to do paging either by dynamic sql or by some advanced techniques,In MSSQL 2005 with the introduction of ROW_NUMBER function life is a lot easier.
You can use ROW_NUMBER to make light work of paging , such as front-end web applications that need to retrieve ten records at a time.
The next query returns ten names from the Contact table beginning at the specified row number.
DECLARE @start INT;
SELECT @start = 10;
WITH PageContacts AS
(
SELECT ROW_NUMBER() OVER
(
ORDER BY LastName,
FirstName,
MiddleName
)
AS PosNo, FirstName, MiddleName, LastName
FROM Contact
)
SELECT PosNo, FirstName, MiddleName, LastName
FROM PageContacts
WHERE PosNo BETWEEN @start AND @start + 10;

The script begins by defining the start position as the ten :

DECLARE @start INT;
SELECT @start = 10;

To use the ROW_NUMBER function to limit the result set to the ten rows beginning at the start position, the sample uses a CTE to wrap the ROW_NUMBER–generating query:

WITH PageContacts AS
(
SELECT ROW_NUMBER() OVER
(
ORDER BY LastName,
FirstName,
MiddleName
)
AS PosNo, FirstName, MiddleName, LastName
FROM Contact
)

SQL, and consequently T-SQL, has absolutely no concept of guaranteed row order without an ORDER BY clause. The OVER keyword provides the mandatory ORDER BY clause to guarantee this proper row numbering order. The final step is to select the columns from the CTE and use the BETWEEN operator to limit the result set to ten rows:

SELECT PosNo,
FirstName,
MiddleName,
LastName
FROM PageContacts
WHERE PosNo BETWEEN @start AND @start + 9;

By changing the @start you can get another page

Best regards

Friday, June 27, 2008

Composite Design Pattern

Is an object that have other objects as their children. The goal of the Composite pattern is to be able to treat individual objects and compositions of objects the same way. All objects in the Composite are derived from Composite itself.
The essential players in the Composite pattern UML diagram are:



IComponent : Defines the operations for objects in the composition, and any default behavior
that will be applicable across objects of both types
Operation : Performs an operation on IComponent-conforming objects.
Component : Implements IComponent .
Composite : Implements IComponent and containing a list of components.
The client deals only with the IComponent interface, which simplifies its task.

And this the implementation :

using System;
using System.Collections.Generic;
using System.Text; // for StringBuilder
using System.Collections.Generic;
namespace CompositePattern
{
// The Interface
public interface IComponent
{
void Add(IComponent c);
IComponent Remove(T s);
string Display(int depth);
IComponent Find(T s);
T Name { get; set; }
}
// The Component
public class Component : IComponent
{
public T Name { get; set; }
public Component(T name)
{
Name = name;
}
public void Add(IComponent c)
{
Console.WriteLine("Cannot add to an item");
}
public IComponent Remove(T s)
{
Console.WriteLine("Cannot remove directly");
return this;
}
public string Display(int depth)
{
return new String('-', depth) + Name + "\n";
}
public IComponent Find(T s)
{
if (s.Equals(Name))
return this;
else
return null;
}
}
// The Composite
public class Composite : IComponent
{
List> list;
public T Name { get; set; }
public Composite(T name)
{
Name = name;
list = new List>();
}
public void Add(IComponent c)
{
list.Add(c);
}
IComponent holder = null;
// Finds the item from a particular point in the structure
// and returns the composite from which it was removed
// If not found, return the point as given
public IComponent Remove(T s)
{
holder = this;
IComponent p = holder.Find(s);
if (holder != null)
{
(holder as Composite).list.Remove(p);
return holder;
}
else
return this;
}
// Recursively looks for an item
// Returns its reference or else null
public IComponent Find(T s)
{
holder = this;
if (Name.Equals(s)) return this;
IComponent found = null;
foreach (IComponent c in list)
{
found = c.Find(s);
if (found != null)
break;
}
return found;
}
// Displays items in a format indicating their level in the composite structure
public string Display(int depth)
{
StringBuilder s = new StringBuilder(new String('-', depth));
s.Append("Set " + Name + " length :" + list.Count + "\n");
foreach (IComponent component in list)
{
s.Append(component.Display(depth + 2));
}
return s.ToString();
}
}

class CompositeApp
{
static void Main()
{
IComponent album = new Composite("Album");
string parameter = "photo";
album.Add(new Component(parameter));
album = album.Find(parameter);
Console.WriteLine(album.Display(0));
album = album.Remove(parameter);
Console.ReadLine();
}
}
}


Best regards

Thursday, June 26, 2008

Bridge Design Pattern

The Bridge pattern is useful when a new version of software is brought out that will replace an existing version, but the older version must still run for its existing client base. The client code will not have to change, as it is conforming to a given abstraction, but the client will need to indicate which version it wants to use.(ex. You can have several versions of the .NET Framework loaded on your computer at any time and can select which one to use by externally setting a path to it in the Windows operating system. Setting the path is the bridge between what applications want from the Framework and the actual version they will get).

The design of a bridge and its players is shown in the UML diagram



From this diagram, we can see that the role players for the Bridge pattern are:


Abstraction : The interface that the client sees


Operation : A method that is called by the client


Bridge : An interface defining those parts of the Abstraction that might vary


ImplementationA and ImplementationB :Implementations of the Bridge interface


OperationImp : A method in the Bridge that is called from the Operation in the Abstraction


And this the implementation :


using System;
namespace BridgePattern {
class Abstraction


{
Bridge bridge;
public Abstraction(Bridge implementation) {
bridge =implementation;


}
public string Operation ( )


{
return "Abstraction" +" <<< BRIDGE >>>>"+bridge.OperationIm( );


}
}
interface Bridge


{
string OperationImp( );


}
class ImplementationA :Bridge {
public string OperationImp ( )


{
return"ImplementationA";


}
}
class ImplementationB :Bridge {
public string OperationImp ( )


{
return "ImplementationB";


}
}
class BridgeApp
{
static void Main()
{
Console.WriteLine("Bridge Pattern\n");
Console.WriteLine(new Abstraction(new
ImplementationA()).Operation());
Console.WriteLine(new Abstraction(new
ImplementationB()).Operation());


}
}
}
/* Output
Bridge Pattern
Abstraction <<< BRIDGE >>>> ImplementationA
Abstraction <<< BRIDGE >>>> ImplementationB
*/


Best Regards

Tuesday, June 24, 2008

Proxy Design Pattern

The Proxy pattern controlling the creation and access to other objects.


Use the Proxy pattern when You have objects that:


• Are expensive to create.


• Need access control.


• Access remote sites.


• Need to perform some action whenever they are accessed.


The design of a proxy and its players is shown in the UML diagram




The players in the pattern are:
ISubject : A common interface for subjects and proxies that enables them to be used Interchangeably.
Subject :The class that a proxy represents.
Proxy : A class that creates, controls, enhances, and authenticates access to a Subject
Request : An operation on the Subject that is routed via a proxy
And this the implementation :
using System;
// Proxy Pattern Judith Bishop Dec 2006
// Shows virtual and protection proxies
class SubjectAccessor {

public interface ISubject

{
string Request ( );
}
private class Subject

{
public string Reques( ) {
return "Subject Request " + "Choose left door\n";
}
}
public class Proxy : ISubject

{
Subject subject;
public string Reques( ) {
// A virtual proxy creates the object only on its first method call
if (subject == null) {
Console.WriteLine("Subject inactive");
subject = new Subject( );
}
Console.WriteLine("Subject active");
return "Proxy: Call to" + subject.Request( );

}
}
public class ProtectionProxy :ISubject {
// An authentication proxy first asks for a password
Subject subject;
string password = "Abracadabra";
public string Authenticate(string supplied)

{
if (supplied!=password) return "Protection Proxy: No access";
else
subject = new Subject( );
return
"Protection Proxy: Authenticated";
}
public string Request( )

{
if (subject==null)
return "Protection Proxy: Authenticate first";
else
return "Protection Proxy: Call to "+
subject.Request( );
}
}
}
class Client : SubjectAccessor

{

static void Main( ) {
Console.WriteLin("Proxy Pattern\n");
ISubject subject = new Proxy( );
Console.WriteLine(subject.Request( ));
Console.WriteLine(subject.Request( ));
subject = new ProtectionProxy( );
Console.WriteLine(subject.Request( ));
Console.WriteLine((subject as ProtectionProxy).Authenticate("Secret"));
Console.WriteLine((subject as ProtectionProxy).Authenticate("Abracadabra"));
Console.WriteLine(subject.Request( ));
Console.ReadLine();
}
}


/* Output
Proxy Pattern
Subject inactive
Subject active

Proxy: Call to Subject Request Choose left door

Subject active
Proxy: Call to Subject Request Choose left door
Protection Proxy: Authenticate first
Protection Proxy: No access
Protection Proxy: Authenticated
Protection Proxy: Call to Subject Request Choose left door


*/




The central class, Proxy, implements the ISubject interface. The Client can use


ISubject to abstract away from proxies. Each Proxy object maintains a reference to a Subject, which is where the action really takes place.