Best site for know something more about dot net controls
Click here to -> Move
Wednesday, October 31, 2007
Tuesday, October 30, 2007
Sunday, October 28, 2007
Design Patterns #6 - ActiveRecord
Design Patterns #6 - ActiveRecord
Across here Colin MacKay has a good posting about using the Data Abstraction Layer pattern (DAL). That got me thinking, since I’m a bear of little brain, I like to keep things simple. A simpler pattern than DAL is the ActiveRecord pattern where the database function is a responsibility of the business object. This pattern (implemented below) is suitable for departmental (or smaller) scale applications.
namespace garyshort.org.patterns.activerecord
{
///
/// GS - ActiveRecord implementation
///
public class ActiveRecord
{
private int _Id = 0;
public int Id
{
get { return _Id; }
set { _Id = value; }
}
public void Save()
{
if (_Id > 0)
{
Update();
}
else
{
Create();
}
}
public void Create()
{
//GS - Save object to db and insert returned Id
}
public void Read(int targetId)
{
//GS - Read row from db and fill in attributes
}
public void Update()
{
//GS - Save changes to db don’t forget optimistic
//locking check
}
public void Delete()
{
//GS - Delete row from db where PK = Id
}
}
///
/// GS - Impliment a business object that extends ActiveRecord
///
public class BusinessObject : ActiveRecord
{
//GS - Business specific code here
}
///
/// GS - Implement a class to test our implementation
///
public class Tester
{
public void Test()
{
BusinessObject bo = new BusinessObject();
//GS - Set BO specific attributes here
bo.Save(); //GS - Will call Create()
//GS - Change specific BO attributes here
bo.Save(); //GS - Will call Update()
bo.Read(bo.Id);
bo.Delete();
}
}
}
Across here Colin MacKay has a good posting about using the Data Abstraction Layer pattern (DAL). That got me thinking, since I’m a bear of little brain, I like to keep things simple. A simpler pattern than DAL is the ActiveRecord pattern where the database function is a responsibility of the business object. This pattern (implemented below) is suitable for departmental (or smaller) scale applications.
namespace garyshort.org.patterns.activerecord
{
///
/// GS - ActiveRecord implementation
///
public class ActiveRecord
{
private int _Id = 0;
public int Id
{
get { return _Id; }
set { _Id = value; }
}
public void Save()
{
if (_Id > 0)
{
Update();
}
else
{
Create();
}
}
public void Create()
{
//GS - Save object to db and insert returned Id
}
public void Read(int targetId)
{
//GS - Read row from db and fill in attributes
}
public void Update()
{
//GS - Save changes to db don’t forget optimistic
//locking check
}
public void Delete()
{
//GS - Delete row from db where PK = Id
}
}
///
/// GS - Impliment a business object that extends ActiveRecord
///
public class BusinessObject : ActiveRecord
{
//GS - Business specific code here
}
///
/// GS - Implement a class to test our implementation
///
public class Tester
{
public void Test()
{
BusinessObject bo = new BusinessObject();
//GS - Set BO specific attributes here
bo.Save(); //GS - Will call Create()
//GS - Change specific BO attributes here
bo.Save(); //GS - Will call Update()
bo.Read(bo.Id);
bo.Delete();
}
}
}
Saturday, October 27, 2007
Design Patterns #5 - The Decorator Pattern
Design Patterns #5 - The Decorator Pattern
The Decorator Pattern is a simple pattern that allows the developer to add responsibilities to an object dynamically. This pattern is useful for extending classes that are locked by use of the “sealed” keyword. The UML diagram for this pattern looks something like this..

An example implimentation would be similar to…
using System;
using System.Collections.Generic;
using System.Text;
namespace garyshort.org.patterns.decorator
{
//GS - Define our decorator
public class DecoratoredDateTime
{
protected DateTime _itemToDecorate;
///
/// GS - Construct the decorator passing the object to decorate
///
/// DateTime
public DecoratoredDateTime(DateTime aDateTime)
{
_itemToDecorate = aDateTime;
}
///
/// GS - Answer whether or not the decorated DateTime
/// is a holiday or not
///
public bool isHoliday
{
get
{
//GS - Simulate a database lookup or similar here
Random rnd = new Random();
return (rnd.Next() % 2) == 0;
}
}
///
/// GS - Answer the short date string of the
/// underlying DateTime
///
///string
public string ToShortDateString()
{
return _itemToDecorate.ToShortDateString();
}
}
///
/// GS - Demonstrate adding the knowledge of whether or not a
/// DateTime is a holiday to the DateTime struct
///
class Program
{
static void Main(string[] args)
{
//GS - Create a DateTime
DateTime aDateTime = DateTime.Now;
//GS - Create the decorator so we can add behaviour to
//the DateTime
DecoratoredDateTime aDecoratedDateTime =
new DecoratoredDateTime(aDateTime);
//GS - Ask the decorated DateTime if it is a holiday
//date or not
if (aDecoratedDateTime.isHoliday)
{
Console.WriteLine(aDecoratedDateTime.ToShortDateString() +
” is a holiday”);
}
else
{
Console.WriteLine(aDecoratedDateTime.ToShortDateString() +
” is not a holiday”);
}
//GS - Wait for the user to press a key before closing
//the DOS box
Console.Read();
}
}
}
Update: Of course the real power of this pattern lies in implementing interfaces so that multiple decorators can be applied to a decorated class. I didn’t include that here, for brevity, but there is a good example provided by Greg.
The Decorator Pattern is a simple pattern that allows the developer to add responsibilities to an object dynamically. This pattern is useful for extending classes that are locked by use of the “sealed” keyword. The UML diagram for this pattern looks something like this..
An example implimentation would be similar to…
using System;
using System.Collections.Generic;
using System.Text;
namespace garyshort.org.patterns.decorator
{
//GS - Define our decorator
public class DecoratoredDateTime
{
protected DateTime _itemToDecorate;
///
/// GS - Construct the decorator passing the object to decorate
///
/// DateTime
public DecoratoredDateTime(DateTime aDateTime)
{
_itemToDecorate = aDateTime;
}
///
/// GS - Answer whether or not the decorated DateTime
/// is a holiday or not
///
public bool isHoliday
{
get
{
//GS - Simulate a database lookup or similar here
Random rnd = new Random();
return (rnd.Next() % 2) == 0;
}
}
///
/// GS - Answer the short date string of the
/// underlying DateTime
///
///
public string ToShortDateString()
{
return _itemToDecorate.ToShortDateString();
}
}
///
/// GS - Demonstrate adding the knowledge of whether or not a
/// DateTime is a holiday to the DateTime struct
///
class Program
{
static void Main(string[] args)
{
//GS - Create a DateTime
DateTime aDateTime = DateTime.Now;
//GS - Create the decorator so we can add behaviour to
//the DateTime
DecoratoredDateTime aDecoratedDateTime =
new DecoratoredDateTime(aDateTime);
//GS - Ask the decorated DateTime if it is a holiday
//date or not
if (aDecoratedDateTime.isHoliday)
{
Console.WriteLine(aDecoratedDateTime.ToShortDateString() +
” is a holiday”);
}
else
{
Console.WriteLine(aDecoratedDateTime.ToShortDateString() +
” is not a holiday”);
}
//GS - Wait for the user to press a key before closing
//the DOS box
Console.Read();
}
}
}
Update: Of course the real power of this pattern lies in implementing interfaces so that multiple decorators can be applied to a decorated class. I didn’t include that here, for brevity, but there is a good example provided by Greg.
Design Patterns #4 - The Adaptor Pattern
Design Patterns #4 - The Adaptor Pattern
The trouble with large enterprises is that… well, they’re large, and that means that they are made up of smaller departments, and these departments may have a different “view” of the same business entity. For example, the billing department’s view of a Customer is going to be different from the sales department’s view.
So, what happens if you are in the sales department and you have to use a Customer object built by the billing department? I mean, you can’t change the interface of the class, otherwise you will break it for the billing department, and you don’t want to create another version of a Customer, otherwise where would it end, you could have dozens of Customer classes in the enterprise. No, what you want to do is to implement the Adaptor Pattern.
The Adaptor Pattern uses an intermediary class to transform the implementation of one interface into an implementation of another interface.
The UML diagram for this pattern looks like this

And the implementation looks something like this
using System;
using System.Collections.Generic;
using System.Text;
namespace garyshort.org.patterns.adaptor
{
//Define a Customer interface
public interface ICustomerOld
{
string GetName();
string GetAddress();
string GetEmail();
DateTime GetLastOrderedDate();
string GetCreditRating();
}
//Define a Customer to implement the interface
public class Customer : ICustomerOld
{
private string _Name;
private string _Address;
private string _Email;
private DateTime _LastOrderedDate;
private string _CreditRating;
public Customer(string name, string address,
string email, DateTime lastOrderedDate,
string creditRating)
{
_Name = name;
_Address = address;
_Email = email;
_LastOrderedDate = lastOrderedDate;
_CreditRating = creditRating;
}
public string GetName()
{
return _Name;
}
public string GetAddress()
{
return _Address;
}
public string GetEmail()
{
return _Email;
}
public DateTime GetLastOrderedDate()
{
return _LastOrderedDate;
}
public string GetCreditRating()
{
return _CreditRating;
}
}
//Define an new interface that the customer
//must now support
public interface ICustomerNew
{
string CustomerName();
string CustomerEmailAddress();
bool HasGoodCreditRating();
}
//Define a class to adapt the old interface
//to the new one
public class AdaptedCustomer : ICustomerNew
{
private Customer _Customer;
public AdaptedCustomer(Customer c)
{
_Customer = c;
}
public string CustomerName()
{
return _Customer.GetName();
}
public string CustomerEmailAddress()
{
return _Customer.GetEmail();
}
public bool HasGoodCreditRating()
{
return _Customer.GetCreditRating() == “GOOD“;
}
}
class Program
{
static void Main(string[] args)
{
//Let’s test the pattern!
//Create a customer object
Customer c = new Customer(”Gary Short“,
“My house in Scotland“, “me@myhouse.com“,
DateTime.Now, “GOOD“);
//Show it implements the ICustomerOld interface
StringBuilder sb = new StringBuilder();
sb.AppendLine(c.GetName());
sb.AppendLine(c.GetAddress());
sb.AppendLine(c.GetEmail());
sb.AppendLine(c.GetLastOrderedDate()
.ToLongDateString());
sb.AppendLine(c.GetCreditRating());
Console.Write(sb.ToString());
//Wrap the customer in the adaptor
AdaptedCustomer ac = new AdaptedCustomer(c);
//Show the adapted customer
//implements ICustomerNew
sb.Remove(0, sb.Length - 1);
sb.AppendLine(ac.CustomerName());
sb.AppendLine(ac.CustomerEmailAddress());
sb.AppendLine(ac.HasGoodCreditRating()
.ToString());
Console.Write(sb.ToString());
//Wait for the user to press a key before closing the
//command window
Console.WriteLine(Environment.NewLine +
“Press any key to continue…“);
Console.Read();
}
}
The trouble with large enterprises is that… well, they’re large, and that means that they are made up of smaller departments, and these departments may have a different “view” of the same business entity. For example, the billing department’s view of a Customer is going to be different from the sales department’s view.
So, what happens if you are in the sales department and you have to use a Customer object built by the billing department? I mean, you can’t change the interface of the class, otherwise you will break it for the billing department, and you don’t want to create another version of a Customer, otherwise where would it end, you could have dozens of Customer classes in the enterprise. No, what you want to do is to implement the Adaptor Pattern.
The Adaptor Pattern uses an intermediary class to transform the implementation of one interface into an implementation of another interface.
The UML diagram for this pattern looks like this
And the implementation looks something like this
using System;
using System.Collections.Generic;
using System.Text;
namespace garyshort.org.patterns.adaptor
{
//Define a Customer interface
public interface ICustomerOld
{
string GetName();
string GetAddress();
string GetEmail();
DateTime GetLastOrderedDate();
string GetCreditRating();
}
//Define a Customer to implement the interface
public class Customer : ICustomerOld
{
private string _Name;
private string _Address;
private string _Email;
private DateTime _LastOrderedDate;
private string _CreditRating;
public Customer(string name, string address,
string email, DateTime lastOrderedDate,
string creditRating)
{
_Name = name;
_Address = address;
_Email = email;
_LastOrderedDate = lastOrderedDate;
_CreditRating = creditRating;
}
public string GetName()
{
return _Name;
}
public string GetAddress()
{
return _Address;
}
public string GetEmail()
{
return _Email;
}
public DateTime GetLastOrderedDate()
{
return _LastOrderedDate;
}
public string GetCreditRating()
{
return _CreditRating;
}
}
//Define an new interface that the customer
//must now support
public interface ICustomerNew
{
string CustomerName();
string CustomerEmailAddress();
bool HasGoodCreditRating();
}
//Define a class to adapt the old interface
//to the new one
public class AdaptedCustomer : ICustomerNew
{
private Customer _Customer;
public AdaptedCustomer(Customer c)
{
_Customer = c;
}
public string CustomerName()
{
return _Customer.GetName();
}
public string CustomerEmailAddress()
{
return _Customer.GetEmail();
}
public bool HasGoodCreditRating()
{
return _Customer.GetCreditRating() == “GOOD“;
}
}
class Program
{
static void Main(string[] args)
{
//Let’s test the pattern!
//Create a customer object
Customer c = new Customer(”Gary Short“,
“My house in Scotland“, “me@myhouse.com“,
DateTime.Now, “GOOD“);
//Show it implements the ICustomerOld interface
StringBuilder sb = new StringBuilder();
sb.AppendLine(c.GetName());
sb.AppendLine(c.GetAddress());
sb.AppendLine(c.GetEmail());
sb.AppendLine(c.GetLastOrderedDate()
.ToLongDateString());
sb.AppendLine(c.GetCreditRating());
Console.Write(sb.ToString());
//Wrap the customer in the adaptor
AdaptedCustomer ac = new AdaptedCustomer(c);
//Show the adapted customer
//implements ICustomerNew
sb.Remove(0, sb.Length - 1);
sb.AppendLine(ac.CustomerName());
sb.AppendLine(ac.CustomerEmailAddress());
sb.AppendLine(ac.HasGoodCreditRating()
.ToString());
Console.Write(sb.ToString());
//Wait for the user to press a key before closing the
//command window
Console.WriteLine(Environment.NewLine +
“Press any key to continue…“);
Console.Read();
}
}
Design Patterns #3 - The Prototype Pattern
Design Patterns #3 - The Prototype Pattern
This pattern allows you to create an object by copying a prototype instead of “newing” it up. Why would you want to do that? Well, let’s say you had an object and the creation of this object was computationally expensive. If you created this object by “newing” it every time, you’d suffer the same creation cost every time. However, if you create it (or a prototype of it) only once and then clone it the second and subsequent times you need it, then you save yourself a lot of computational expense.
The UML model for this pattern looks something like this

Here’s an example implementation in C#
using System;
using System.Collections.Generic;
using System.Text;
namespace garyshort.org.patterns.prototype
{
class Program
{
///
/// GS - Define a class to be a prototype
/// for our “expensive to create” object
///
public class MortgagePrototype
{
private int _Atribute1;
public int Attribute1
{
get { return _Atribute1; }
set { _Atribute1 = value; }
}
//GS - Lots more attributes making
//this object expensive to create
private int _AttributeN;
public int AttributeN
{
get { return _AttributeN; }
set { _AttributeN = value; }
}
public MortgagePrototype Clone()
{
return this.MemberwiseClone() as
MortgagePrototype;
}
}
///
/// GS - Now add in the extra attributes
/// that make a commercial mortgage
///
public class CommercialMortgagePrototype :
MortgagePrototype
{
private int _CMAttribute1;
public int CMAttribute1
{
get { return _CMAttribute1; }
set { _CMAttribute1 = value; }
}
//GS - Lots more attributes making this
//object expensive to create
private int _CMAttributeN;
public int CMAttributeN
{
get { return _CMAttributeN; }
set { _CMAttributeN = value; }
}
public override string ToString()
{
return “I am a commercial mortgage“;
}
}
public class ResidentialMortgagePrototype :
MortgagePrototype
{
private int _RMAttribute1;
public int RMAttribute1
{
get { return _RMAttribute1; }
set { _RMAttribute1 = value; }
}
//GS - Lots more attributes making this
//object expensive to create
private int _RMAttributeN;
public int RMAttributeN
{
get { return _RMAttributeN; }
set { _RMAttributeN = value; }
}
public override string ToString()
{
return “I am a residential mortgage“;
}
}
static void Main(string[] args)
{
//GS - Let’s test the pattern
//GS - These objects are expensive to create
//so create them once here, early on in the
//application
CommercialMortgagePrototype cmp =
new CommercialMortgagePrototype();
ResidentialMortgagePrototype rmp =
new ResidentialMortgagePrototype();
//Okay let’s create a new commercial mortgage
CommercialMortgagePrototype cm1 = cmp.Clone() as
CommercialMortgagePrototype;
//GS - And a residental mortgage too
ResidentialMortgagePrototype rm1 = rmp.Clone() as
ResidentialMortgagePrototype;
//GS - Do work here…
//GS - Create more expensive objects here…
//GS - etc…
//GS - Let’s make sure they work
Console.WriteLine(cm1.ToString());
Console.WriteLine(rm1.ToString());
}
}
}
The output from this implimentation looks like this
This pattern allows you to create an object by copying a prototype instead of “newing” it up. Why would you want to do that? Well, let’s say you had an object and the creation of this object was computationally expensive. If you created this object by “newing” it every time, you’d suffer the same creation cost every time. However, if you create it (or a prototype of it) only once and then clone it the second and subsequent times you need it, then you save yourself a lot of computational expense.
The UML model for this pattern looks something like this

Here’s an example implementation in C#
using System;
using System.Collections.Generic;
using System.Text;
namespace garyshort.org.patterns.prototype
{
class Program
{
///
/// GS - Define a class to be a prototype
/// for our “expensive to create” object
///
public class MortgagePrototype
{
private int _Atribute1;
public int Attribute1
{
get { return _Atribute1; }
set { _Atribute1 = value; }
}
//GS - Lots more attributes making
//this object expensive to create
private int _AttributeN;
public int AttributeN
{
get { return _AttributeN; }
set { _AttributeN = value; }
}
public MortgagePrototype Clone()
{
return this.MemberwiseClone() as
MortgagePrototype;
}
}
///
/// GS - Now add in the extra attributes
/// that make a commercial mortgage
///
public class CommercialMortgagePrototype :
MortgagePrototype
{
private int _CMAttribute1;
public int CMAttribute1
{
get { return _CMAttribute1; }
set { _CMAttribute1 = value; }
}
//GS - Lots more attributes making this
//object expensive to create
private int _CMAttributeN;
public int CMAttributeN
{
get { return _CMAttributeN; }
set { _CMAttributeN = value; }
}
public override string ToString()
{
return “I am a commercial mortgage“;
}
}
public class ResidentialMortgagePrototype :
MortgagePrototype
{
private int _RMAttribute1;
public int RMAttribute1
{
get { return _RMAttribute1; }
set { _RMAttribute1 = value; }
}
//GS - Lots more attributes making this
//object expensive to create
private int _RMAttributeN;
public int RMAttributeN
{
get { return _RMAttributeN; }
set { _RMAttributeN = value; }
}
public override string ToString()
{
return “I am a residential mortgage“;
}
}
static void Main(string[] args)
{
//GS - Let’s test the pattern
//GS - These objects are expensive to create
//so create them once here, early on in the
//application
CommercialMortgagePrototype cmp =
new CommercialMortgagePrototype();
ResidentialMortgagePrototype rmp =
new ResidentialMortgagePrototype();
//Okay let’s create a new commercial mortgage
CommercialMortgagePrototype cm1 = cmp.Clone() as
CommercialMortgagePrototype;
//GS - And a residental mortgage too
ResidentialMortgagePrototype rm1 = rmp.Clone() as
ResidentialMortgagePrototype;
//GS - Do work here…
//GS - Create more expensive objects here…
//GS - etc…
//GS - Let’s make sure they work
Console.WriteLine(cm1.ToString());
Console.WriteLine(rm1.ToString());
}
}
}
The output from this implimentation looks like this
Design Patterns #2 - The Builder Pattern
Design Patterns #2 - The Builder Pattern
The purpose of the Builder pattern is to abstract the complex creation of an object from the object’s implementation. In other words, if you have a simple object, let’s say a Person, you can construct that object with a simple constructor that takes a number of parameters such as, name, age, address, place of birth, etc.
However, if you have a complex object, say a 747 or a nuclear submarine, then the code to construct that object may swamp the implementation code for the object. To avoid this the construction code is abstracted away from the implementation.
The UML diagram for this pattern looks a little like this.

The C# implementation would be something like this…
using System;
using System.Collections.Generic;
using System.Text;
namespace garyshort.Patterns.Builder
{
//Define the classes and interfaces
public class Director
{
public ProductBase
Constructor(iBuilder builder)
{
builder.Build();
return builder.GetResult();
}
}
public interface iBuilder
{
ProductBase GetResult();
void Build();
}
public abstract class ProductBase
{
private string _Owner;
public string Owner
{
get { return _Owner; }
set { _Owner = value; }
}
}
public class Car : ProductBase
{
private bool _Wheels;
private bool _Chasis;
private bool _Body;
private bool _Interior;
public bool Interior
{
set { _Interior = value; }
}
public bool Body
{
set { _Body = value; }
}
public bool Chasis
{
set { _Chasis = value; }
}
public bool Wheels
{
set { _Wheels = value; }
}
public void Drive()
{
Console.WriteLine
(”Car is driving!“);
}
}
public class Plane : ProductBase
{
private bool _Cockpit;
public bool Cockpit
{
set { _Cockpit = value; }
}
private bool _Fussilage;
public bool Fussilage
{
set { _Fussilage = value; }
}
private bool _Tail;
public bool Tail
{
set { _Tail = value; }
}
private bool _Wings;
public bool Wings
{
set { _Wings = value; }
}
private bool _Undercarriage;
public bool Undercarriage
{
set { _Undercarriage = value; }
}
public void Fly()
{
Console.WriteLine(”Plane is flying!“);
}
}
public class CarBuilder : iBuilder
{
private Car _Car = new Car();
public void Build()
{
Console.WriteLine
(”Beginning car construction.“);
Console.WriteLine
(”Setting owner.“);
_Car.Owner = “Gary Short“;
Console.WriteLine
(”Building chasis“);
_Car.Chasis = true;
Console.WriteLine(
“Building body“);
_Car.Body = true;
Console.WriteLine(
“Building wheels“);
_Car.Wheels = true;
Console.WriteLine
(”Building interior“);
_Car.Interior = true;
Console.WriteLine
(”Car construction complete.“);
}
public ProductBase GetResult()
{
return _Car;
}
}
public class PlaneBuilder : iBuilder
{
private Plane _Plane = new Plane();
public void Build()
{
Console.WriteLine
(”Beginning plane construction.“);
Console.WriteLine
(”Setting owner.“);
_Plane.Owner = “Richard Branson.“;
Console.WriteLine
(”Building cockpit.“);
_Plane.Cockpit = true;
Console.WriteLine
(”Building fussilage.“);
_Plane.Fussilage = true;
Console.WriteLine
(”Building tail.“);
_Plane.Tail = true;
Console.WriteLine
(”Building wings.“);
_Plane.Wings = true;
Console.WriteLine
(”Building undercarriage.“);
_Plane.Undercarriage = true;
Console.WriteLine
(”Plane construction complete.“);
}
public ProductBase GetResult()
{
return _Plane;
}
}
class Program
{
static void Main(string[] args)
{
//Test the pattern
//I want a car and a plane,
//so ask the director to
//build them for me.
Director d = new Director();
Car MyCar = d.Constructor(
new CarBuilder()) as Car;
Plane myPlane = d.Constructor(
new PlaneBuilder()) as Plane;
//Now make the car and plane do stuff
MyCar.Drive();
myPlane.Fly();
}
}
}
The output from this pattern looks like this.
The purpose of the Builder pattern is to abstract the complex creation of an object from the object’s implementation. In other words, if you have a simple object, let’s say a Person, you can construct that object with a simple constructor that takes a number of parameters such as, name, age, address, place of birth, etc.
However, if you have a complex object, say a 747 or a nuclear submarine, then the code to construct that object may swamp the implementation code for the object. To avoid this the construction code is abstracted away from the implementation.
The UML diagram for this pattern looks a little like this.

The C# implementation would be something like this…
using System;
using System.Collections.Generic;
using System.Text;
namespace garyshort.Patterns.Builder
{
//Define the classes and interfaces
public class Director
{
public ProductBase
Constructor(iBuilder builder)
{
builder.Build();
return builder.GetResult();
}
}
public interface iBuilder
{
ProductBase GetResult();
void Build();
}
public abstract class ProductBase
{
private string _Owner;
public string Owner
{
get { return _Owner; }
set { _Owner = value; }
}
}
public class Car : ProductBase
{
private bool _Wheels;
private bool _Chasis;
private bool _Body;
private bool _Interior;
public bool Interior
{
set { _Interior = value; }
}
public bool Body
{
set { _Body = value; }
}
public bool Chasis
{
set { _Chasis = value; }
}
public bool Wheels
{
set { _Wheels = value; }
}
public void Drive()
{
Console.WriteLine
(”Car is driving!“);
}
}
public class Plane : ProductBase
{
private bool _Cockpit;
public bool Cockpit
{
set { _Cockpit = value; }
}
private bool _Fussilage;
public bool Fussilage
{
set { _Fussilage = value; }
}
private bool _Tail;
public bool Tail
{
set { _Tail = value; }
}
private bool _Wings;
public bool Wings
{
set { _Wings = value; }
}
private bool _Undercarriage;
public bool Undercarriage
{
set { _Undercarriage = value; }
}
public void Fly()
{
Console.WriteLine(”Plane is flying!“);
}
}
public class CarBuilder : iBuilder
{
private Car _Car = new Car();
public void Build()
{
Console.WriteLine
(”Beginning car construction.“);
Console.WriteLine
(”Setting owner.“);
_Car.Owner = “Gary Short“;
Console.WriteLine
(”Building chasis“);
_Car.Chasis = true;
Console.WriteLine(
“Building body“);
_Car.Body = true;
Console.WriteLine(
“Building wheels“);
_Car.Wheels = true;
Console.WriteLine
(”Building interior“);
_Car.Interior = true;
Console.WriteLine
(”Car construction complete.“);
}
public ProductBase GetResult()
{
return _Car;
}
}
public class PlaneBuilder : iBuilder
{
private Plane _Plane = new Plane();
public void Build()
{
Console.WriteLine
(”Beginning plane construction.“);
Console.WriteLine
(”Setting owner.“);
_Plane.Owner = “Richard Branson.“;
Console.WriteLine
(”Building cockpit.“);
_Plane.Cockpit = true;
Console.WriteLine
(”Building fussilage.“);
_Plane.Fussilage = true;
Console.WriteLine
(”Building tail.“);
_Plane.Tail = true;
Console.WriteLine
(”Building wings.“);
_Plane.Wings = true;
Console.WriteLine
(”Building undercarriage.“);
_Plane.Undercarriage = true;
Console.WriteLine
(”Plane construction complete.“);
}
public ProductBase GetResult()
{
return _Plane;
}
}
class Program
{
static void Main(string[] args)
{
//Test the pattern
//I want a car and a plane,
//so ask the director to
//build them for me.
Director d = new Director();
Car MyCar = d.Constructor(
new CarBuilder()) as Car;
Plane myPlane = d.Constructor(
new PlaneBuilder()) as Plane;
//Now make the car and plane do stuff
MyCar.Drive();
myPlane.Fly();
}
}
}
The output from this pattern looks like this.
Design Patterns #1 - The Abstract Factory Pattern
Design Patterns #2 - The Abstract Factory Pattern
Much like the Factory Pattern, discussed earlier, the Abstract Factory Pattern let’s us create concrete objects based on information that we do not know until run time. However, the Abstract Factory pattern let’s us group like factory classes together. In the example below we group a factory for creating military vehicles and a factory for creating civilian vehicles together and then we decide what “kind of” vehicles to create based on the information which we will get at run time.
The UML diagram for this pattern looks something like this:-

And below there is an implementation in C#
using System;
using System.Collections.Generic;
using System.Text;
namespace AbstractFactoryPattern
{
//Create an enum to define whether or not we are at war
public enum WarStatus
{
AtWar,
NotAtWar
}
//Create an enum to define ground type
public enum GroundType
{
OnRoad,
OffRoad
}
//Create Factory hierarchy
public abstract class VehicleFactory
{
public abstract Vehicle GetVehicle(GroundType gt);
}
public class MilitaryVehicleFactory : VehicleFactory
{
public override Vehicle GetVehicle(GroundType gt)
{
Vehicle v = null;
switch (gt)
{
case GroundType.OffRoad :
v = new MilitaryTrackedVehicle();
break;
case GroundType.OnRoad :
v = new MilitaryWheeledVehicle();
break;
}
return v;
}
}
public class CivilianVehicleFactory : VehicleFactory
{
public override Vehicle GetVehicle(GroundType gt)
{
Vehicle v = null;
switch (gt)
{
case GroundType.OffRoad :
v = new CivilianTrackedVehicle();
break;
case GroundType.OnRoad :
v = new CivilianWheeledVehicle();
break;
}
return v;
}
}
//Create Vehicle hierarchy
public abstract class Vehicle
{
public abstract void Drive();
public abstract void FireWeapon();
}
public class CivilianTrackedVehicle : Vehicle
{
public override void Drive()
{
Console.WriteLine(
“Civilian vehicle driving off road!”);
}
public override void FireWeapon()
{
Console.WriteLine(
“Civilian tracked vehicle is unarmed!”);
}
}
public class CivilianWheeledVehicle : Vehicle
{
public override void Drive()
{
Console.WriteLine(
“Civilian vehicle driving on the road!”);
}
public override void FireWeapon()
{
Console.WriteLine(
“Civilian wheeled vehicle is unarmed!”);
}
}
public class MilitaryTrackedVehicle : Vehicle
{
public override void Drive()
{
Console.WriteLine(
“Military vehicle driving off road!”);
}
public override void FireWeapon()
{
Console.WriteLine(
“Military tracked vehicle firing!”);
}
}
public class MilitaryWheeledVehicle : Vehicle
{
public override void Drive()
{
Console.WriteLine(
“Military vehicle driving on the road!”);
}
public override void FireWeapon()
{
Console.WriteLine(
“Military wheeled vehicle firing!”);
}
}
class Program
{
static void Main(string[] args)
{
//Test the factories
//We’re at war, let’s create vehicles
MilitaryVehicleFactory mvf =
new MilitaryVehicleFactory();
Vehicle mv1 =
mvf.GetVehicle(GroundType.OffRoad);
Vehicle mv2 =
mvf.GetVehicle(GroundType.OnRoad);
//The war’s over, lets create more vehicles
CivilianVehicleFactory cvf =
new CivilianVehicleFactory();
Vehicle cv1 =
cvf.GetVehicle(GroundType.OffRoad);
Vehicle cv2 = c
vf.GetVehicle(GroundType.OnRoad);
//Let’s make our vehicles work!
Vehicle[] vehicles = { mv1, mv2, cv1, cv2 };
foreach (Vehicle v in vehicles)
{
v.Drive();
v.FireWeapon();
}
}
}
}
The output from this implementation looks like this:-
Technorati tags: Abstract Factory Pattern, Design Patterns, C#
This entry was posted on Thursday, March 15th, 2007 at 1:04 pm and is filed under Design Patterns, C# 2.0. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from you
Much like the Factory Pattern, discussed earlier, the Abstract Factory Pattern let’s us create concrete objects based on information that we do not know until run time. However, the Abstract Factory pattern let’s us group like factory classes together. In the example below we group a factory for creating military vehicles and a factory for creating civilian vehicles together and then we decide what “kind of” vehicles to create based on the information which we will get at run time.
The UML diagram for this pattern looks something like this:-
And below there is an implementation in C#
using System;
using System.Collections.Generic;
using System.Text;
namespace AbstractFactoryPattern
{
//Create an enum to define whether or not we are at war
public enum WarStatus
{
AtWar,
NotAtWar
}
//Create an enum to define ground type
public enum GroundType
{
OnRoad,
OffRoad
}
//Create Factory hierarchy
public abstract class VehicleFactory
{
public abstract Vehicle GetVehicle(GroundType gt);
}
public class MilitaryVehicleFactory : VehicleFactory
{
public override Vehicle GetVehicle(GroundType gt)
{
Vehicle v = null;
switch (gt)
{
case GroundType.OffRoad :
v = new MilitaryTrackedVehicle();
break;
case GroundType.OnRoad :
v = new MilitaryWheeledVehicle();
break;
}
return v;
}
}
public class CivilianVehicleFactory : VehicleFactory
{
public override Vehicle GetVehicle(GroundType gt)
{
Vehicle v = null;
switch (gt)
{
case GroundType.OffRoad :
v = new CivilianTrackedVehicle();
break;
case GroundType.OnRoad :
v = new CivilianWheeledVehicle();
break;
}
return v;
}
}
//Create Vehicle hierarchy
public abstract class Vehicle
{
public abstract void Drive();
public abstract void FireWeapon();
}
public class CivilianTrackedVehicle : Vehicle
{
public override void Drive()
{
Console.WriteLine(
“Civilian vehicle driving off road!”);
}
public override void FireWeapon()
{
Console.WriteLine(
“Civilian tracked vehicle is unarmed!”);
}
}
public class CivilianWheeledVehicle : Vehicle
{
public override void Drive()
{
Console.WriteLine(
“Civilian vehicle driving on the road!”);
}
public override void FireWeapon()
{
Console.WriteLine(
“Civilian wheeled vehicle is unarmed!”);
}
}
public class MilitaryTrackedVehicle : Vehicle
{
public override void Drive()
{
Console.WriteLine(
“Military vehicle driving off road!”);
}
public override void FireWeapon()
{
Console.WriteLine(
“Military tracked vehicle firing!”);
}
}
public class MilitaryWheeledVehicle : Vehicle
{
public override void Drive()
{
Console.WriteLine(
“Military vehicle driving on the road!”);
}
public override void FireWeapon()
{
Console.WriteLine(
“Military wheeled vehicle firing!”);
}
}
class Program
{
static void Main(string[] args)
{
//Test the factories
//We’re at war, let’s create vehicles
MilitaryVehicleFactory mvf =
new MilitaryVehicleFactory();
Vehicle mv1 =
mvf.GetVehicle(GroundType.OffRoad);
Vehicle mv2 =
mvf.GetVehicle(GroundType.OnRoad);
//The war’s over, lets create more vehicles
CivilianVehicleFactory cvf =
new CivilianVehicleFactory();
Vehicle cv1 =
cvf.GetVehicle(GroundType.OffRoad);
Vehicle cv2 = c
vf.GetVehicle(GroundType.OnRoad);
//Let’s make our vehicles work!
Vehicle[] vehicles = { mv1, mv2, cv1, cv2 };
foreach (Vehicle v in vehicles)
{
v.Drive();
v.FireWeapon();
}
}
}
}
The output from this implementation looks like this:-
Technorati tags: Abstract Factory Pattern, Design Patterns, C#
This entry was posted on Thursday, March 15th, 2007 at 1:04 pm and is filed under Design Patterns, C# 2.0. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from you
Passing Values between ASP.NET Web Forms
Passing Values between ASP.NET Web Forms
Introduction
ASP.NET web forms provide excellent event driven programming model to developers. This does simplifies the overall design of your application but poses some problems of its own. For example, in traditional ASP you can easily pass values from one ASP page to another ASP page using POST. The same thing is not possible in ASP.NET if you want to stick to web form model (i.e. Server side form and control processing.). There are, however, some ways that can be used to overcome this situation. This article examines various possibilities to do the same. More specifically we will cover how to pass values using querystring, how to use session variables to do the same and finally how to use Server.Transfer method to do that.
Using Querystring
Querystring is a day old mechanism to pass values across pages. The main advantage of this method is it is very simple. However, disadvantages are the values are visible in the browser address bar and you can not pass objects this way. This method is best suited when you want to pass small number of values that need not be secured from others. In order to implement this method you will follow these steps:
* Create the web form with controls
* Provide some button or link button that posts the form back
* In the click event of the button create a string that holds URL for another
* Add control values to this URL as querystring parameters
* Response.Redirect to another form with this URL
Following code snippet shows how it works:
Source Web Form
private void Button1_Click
(object sender, System.EventArgs e)
{
string url;
url="anotherwebform.aspx?name=" +
TextBox1.Text + "&email=" +
TextBox2.Text;
Response.Redirect(url);
}
Destination Web Form
private void Page_Load
(object sender, System.EventArgs e)
{
Label1.Text=Request.QueryString["name"];
Label2.Text=Request.QueryString["email"];
}
Using Session variables
This is yet another way to pass values across pages. Here you store control values in session variables and access them in another web form. However, as you know storing too much data in session can be an overhead on the server. So, you should use this method with care. Also, it requires some kind of clean up action from your side so that unwanted session variables are removed. The typical sequence of steps will be as follows:
* Create the web form with controls
* Provide some button or link button that posts the form back
* In the click event of the button add session variables and set them to control values
* Response.Redirect to another form
* In that form access Session variables and remove them if necessary
Following code shows this in action:
Source Web Form
private void Button1_Click
(object sender, System.EventArgs e)
{
//textbox1 and textbox2 are webform
//controls
Session["name"]=TextBox1.Text;
Session["email"]=TextBox2.Text;
Server.Transfer("anotherwebform.aspx");
}
Destination Web Form
private void Page_Load
(object sender, System.EventArgs e)
{
Label1.Text=Session["name"].ToString();
Label2.Text=Session["email"].ToString();
Session.Remove("name");
Session.Remove("email");
}
Using Server.Transfer
This is somewhat complex but sophisticated method of passing values across pages. Here you expose the values you want to access in other pages as properties of the page class. This methods require you to code extra properties that you can access in another web form. However, the efforts are worth considering. Overall this method is much cleaner and object oriented than earlier methods. The entire process works as follows:
* Create the web form with controls
* Create property Get procedures that will return control values
* Provide some button or link button that posts the form back
* In the button click event handler call Server.Transfer method that will transfer execution to the specified form
* In the second form you can get a reference to the first form instance by using Context.Handler property. Then you will use the get properties we created to access the control values.
The code to accomplish this is somewhat complex and is shown below:
Source Web Form
Add following properties to the web form:
public string Name
{
get
{
return TextBox1.Text;
}
}
public string EMail
{
get
{
return TextBox2.Text;
}
}
Now, call Server.Transfer.
private void Button1_Click
(object sender, System.EventArgs e)
{
Server.Transfer("anotherwebform.aspx");
}
Destination Web Form
private void Page_Load
(object sender, System.EventArgs e)
{
//create instance of source web form
WebForm1 wf1;
//get reference to current handler instance
wf1=(WebForm1)Context.Handler;
Label1.Text=wf1.Name;
Label2.Text=wf1.EMail;
}
Summary
In this article we saw various ways to pass data between two ASP.NET web forms. The three methods viz. Querystring, Session and Server.Transfer provide ways to pass our values across pages. We also saw pros and cons of each method.
I hope you must have found this article useful. See you soon. Till then keep coding!
Introduction
ASP.NET web forms provide excellent event driven programming model to developers. This does simplifies the overall design of your application but poses some problems of its own. For example, in traditional ASP you can easily pass values from one ASP page to another ASP page using POST. The same thing is not possible in ASP.NET if you want to stick to web form model (i.e. Server side form and control processing.). There are, however, some ways that can be used to overcome this situation. This article examines various possibilities to do the same. More specifically we will cover how to pass values using querystring, how to use session variables to do the same and finally how to use Server.Transfer method to do that.
Using Querystring
Querystring is a day old mechanism to pass values across pages. The main advantage of this method is it is very simple. However, disadvantages are the values are visible in the browser address bar and you can not pass objects this way. This method is best suited when you want to pass small number of values that need not be secured from others. In order to implement this method you will follow these steps:
* Create the web form with controls
* Provide some button or link button that posts the form back
* In the click event of the button create a string that holds URL for another
* Add control values to this URL as querystring parameters
* Response.Redirect to another form with this URL
Following code snippet shows how it works:
Source Web Form
private void Button1_Click
(object sender, System.EventArgs e)
{
string url;
url="anotherwebform.aspx?name=" +
TextBox1.Text + "&email=" +
TextBox2.Text;
Response.Redirect(url);
}
Destination Web Form
private void Page_Load
(object sender, System.EventArgs e)
{
Label1.Text=Request.QueryString["name"];
Label2.Text=Request.QueryString["email"];
}
Using Session variables
This is yet another way to pass values across pages. Here you store control values in session variables and access them in another web form. However, as you know storing too much data in session can be an overhead on the server. So, you should use this method with care. Also, it requires some kind of clean up action from your side so that unwanted session variables are removed. The typical sequence of steps will be as follows:
* Create the web form with controls
* Provide some button or link button that posts the form back
* In the click event of the button add session variables and set them to control values
* Response.Redirect to another form
* In that form access Session variables and remove them if necessary
Following code shows this in action:
Source Web Form
private void Button1_Click
(object sender, System.EventArgs e)
{
//textbox1 and textbox2 are webform
//controls
Session["name"]=TextBox1.Text;
Session["email"]=TextBox2.Text;
Server.Transfer("anotherwebform.aspx");
}
Destination Web Form
private void Page_Load
(object sender, System.EventArgs e)
{
Label1.Text=Session["name"].ToString();
Label2.Text=Session["email"].ToString();
Session.Remove("name");
Session.Remove("email");
}
Using Server.Transfer
This is somewhat complex but sophisticated method of passing values across pages. Here you expose the values you want to access in other pages as properties of the page class. This methods require you to code extra properties that you can access in another web form. However, the efforts are worth considering. Overall this method is much cleaner and object oriented than earlier methods. The entire process works as follows:
* Create the web form with controls
* Create property Get procedures that will return control values
* Provide some button or link button that posts the form back
* In the button click event handler call Server.Transfer method that will transfer execution to the specified form
* In the second form you can get a reference to the first form instance by using Context.Handler property. Then you will use the get properties we created to access the control values.
The code to accomplish this is somewhat complex and is shown below:
Source Web Form
Add following properties to the web form:
public string Name
{
get
{
return TextBox1.Text;
}
}
public string EMail
{
get
{
return TextBox2.Text;
}
}
Now, call Server.Transfer.
private void Button1_Click
(object sender, System.EventArgs e)
{
Server.Transfer("anotherwebform.aspx");
}
Destination Web Form
private void Page_Load
(object sender, System.EventArgs e)
{
//create instance of source web form
WebForm1 wf1;
//get reference to current handler instance
wf1=(WebForm1)Context.Handler;
Label1.Text=wf1.Name;
Label2.Text=wf1.EMail;
}
Summary
In this article we saw various ways to pass data between two ASP.NET web forms. The three methods viz. Querystring, Session and Server.Transfer provide ways to pass our values across pages. We also saw pros and cons of each method.
I hope you must have found this article useful. See you soon. Till then keep coding!
Wednesday, October 10, 2007
.Net Interview Questions Resource
.Net Interview Questions Resource
http://www.hanselman.com/blog/WhatGreatNETDevelopersOughtToKnowMoreNETInterviewQuestions.aspx
http://www.hanselman.com/blog/WhatGreatNETDevelopersOughtToKnowMoreNETInterviewQuestions.aspx
Complete Javascript Reference
Complete Javascript Reference
http://www.hunlock.com/blogs/The_Complete_Javascript_Strings_Reference
http://www.hunlock.com/blogs/The_Complete_Javascript_Strings_Reference
Lock, Logoff, Reboot, Shutdown, Hibernate, Standby in .Net
Lock, Logoff, Reboot, Shutdown, Hibernate, Standby in .Net
Introduction
This article is about locking, logging off , rebooting, shutting down, hibernating and putting the system on stand by mode in .Net. Here we are going to use both unmanaged code and .Net framework for these functions.
Getting Started
Let us start by creating a windows application. To our newly created form, add seven buttons entitled btnLockComp, btnLogOff, btnReboot, btnShutdown, btnForceLogOff, btnHibernate, btnStandby.
Lock Workstation
Let us start with locking the workstation, which is supposed to lock the current user session. We will call a windows API for doing this. For calling an un-managed piece of code, we need to add the System.Runtime.InteropServices namespace to the using directive.
using System.Runtime.InteropServices;
Now we are ready to import the windows API library and define the function that we intend to use. The function to lock the workstation resides in the user32.dll library. And the function for locking the desktop is LockWorkStation. The following statements should be added to the class to import the library.
[DllImport("user32.dll")]
public static extern void LockWorkStation();
Next step is to double click the btnLockComp button to create a click event handler and call the LockWorkStation API to lock the workstation.
LockWorkStation();
Log Off
For logging off we are going to use an unmanaged API function called ExitWindowsEx(). This function accepts two arguments, one for flag(logoff, shutdown, reboot, etc.,) and the other for reason for this action(maintenance, software update, etc.,). Now import the user32.dll once again, this time so we can use the ExitWindowsEx() function, as shown below:
[DllImport("user32.dll")]
public static extern int ExitWindowsEx(int uFlags, int dwReason);
Double click the log off button and add the following function call to the event. Flag 0 indicates logoff,
ExitWindowsEx(0, 0);
To force processes to terminate while logging off, change the flag to 4 in the function as below
ExitWindowsEx(4, 0);
Reboot
To reboot we are going to use the same function ExitWindowsEx but with a different flag. Add the following code to the click event handler of the reboot button.
ExitWindowsEx(2, 0);
Shutdown
Now add the following code to the button Shutdown's click event handler.
ExitWindowsEx(1, 0);
Hibernate and Standby
To put the system in hibernate and standby modes, we are going to use Application class's SetSuspendState method. There are three arguments for this function, power state, force and disable wake event. The first argument, power state is where we mention the state of the system (hibernate/suspend)
// Hibernate
Application.SetSuspendState(PowerState.Hibernate, true, true);
// Standby
Application.SetSuspendState(PowerState.Suspend true, true);
Introduction
This article is about locking, logging off , rebooting, shutting down, hibernating and putting the system on stand by mode in .Net. Here we are going to use both unmanaged code and .Net framework for these functions.
Getting Started
Let us start by creating a windows application. To our newly created form, add seven buttons entitled btnLockComp, btnLogOff, btnReboot, btnShutdown, btnForceLogOff, btnHibernate, btnStandby.
Lock Workstation
Let us start with locking the workstation, which is supposed to lock the current user session. We will call a windows API for doing this. For calling an un-managed piece of code, we need to add the System.Runtime.InteropServices namespace to the using directive.
using System.Runtime.InteropServices;
Now we are ready to import the windows API library and define the function that we intend to use. The function to lock the workstation resides in the user32.dll library. And the function for locking the desktop is LockWorkStation. The following statements should be added to the class to import the library.
[DllImport("user32.dll")]
public static extern void LockWorkStation();
Next step is to double click the btnLockComp button to create a click event handler and call the LockWorkStation API to lock the workstation.
LockWorkStation();
Log Off
For logging off we are going to use an unmanaged API function called ExitWindowsEx(). This function accepts two arguments, one for flag(logoff, shutdown, reboot, etc.,) and the other for reason for this action(maintenance, software update, etc.,). Now import the user32.dll once again, this time so we can use the ExitWindowsEx() function, as shown below:
[DllImport("user32.dll")]
public static extern int ExitWindowsEx(int uFlags, int dwReason);
Double click the log off button and add the following function call to the event. Flag 0 indicates logoff,
ExitWindowsEx(0, 0);
To force processes to terminate while logging off, change the flag to 4 in the function as below
ExitWindowsEx(4, 0);
Reboot
To reboot we are going to use the same function ExitWindowsEx but with a different flag. Add the following code to the click event handler of the reboot button.
ExitWindowsEx(2, 0);
Shutdown
Now add the following code to the button Shutdown's click event handler.
ExitWindowsEx(1, 0);
Hibernate and Standby
To put the system in hibernate and standby modes, we are going to use Application class's SetSuspendState method. There are three arguments for this function, power state, force and disable wake event. The first argument, power state is where we mention the state of the system (hibernate/suspend)
// Hibernate
Application.SetSuspendState(PowerState.Hibernate, true, true);
// Standby
Application.SetSuspendState(PowerState.Suspend true, true);
Subscribe to:
Posts (Atom)
About Me
- Senthilkumar
- Bangalore, Karnataka, India