Singleton Design Pattern

Introduction:
There is some cases when you want to have one and only one instance of a specific class and prevent anybody from having the ability to create more than one instance of that class. Singleton Design pattern came to solve this issue by defining a well known structure for your class

 

Singleton1

Example:
Singleton Design pattern can be used in Data repository or data collection where creation of more than one instance of this class can be resource wastage… Hence each client to singleton class is referencing to the same single shared object. Which will solve the issue.

Singleton2

public class Singleton
{
private static Singleton instance;
private static int numOfReference;
private static int numOfInstances = 0;
private string code;
private Singleton()
{
numOfReference = 0;
numOfInstances++;
code = “Code ” + numOfInstances.ToString();
}
//Return instance of the Singleton class
public static Singleton GetInstance()
{
if(instance == null)
{
instance = new Singleton();
}
numOfReference++;
return instance;
}
public static int ReferenceCounter
{
get { return numOfReference; }
}
public static int InstanceCounter
{
get { return numOfInstances; }
}
public string Code
{
get { return code; }
set { code = value;}
}
}
static void Main(string[] args)
{
Singleton instance1 = Singleton.GetInstance();
Console.WriteLine(“No. of references : ” + Singleton.ReferenceCounter);  // should be 1
Console.WriteLine(“First Objects code: ” + instance1.Code);
Console.WriteLine(“Instances Counter: ” + Singleton.InstanceCounter);   // should be 1
Singleton instance2 = Singleton.GetInstance();
Console.WriteLine(“No. of references : ” + Singleton.ReferenceCounter);  // should be 2
Console.WriteLine(“Second Objects code: ” + instance2.Code);
Console.WriteLine(“Instances Counter: ” + Singleton.InstanceCounter);   // should be 1
}

How to know SQL Server version and Service Pack(SP)

Many time I stuck with a question… what is this DB Server version and what Service pack is installed on it? What is the easiest way to know DB edition? I asked this question to a friend of mine and he gave me the following simple Select statement that answered my questions.

SELECT SERVERPROPERTY(‘productversion’) AS version

, SERVERPROPERTY (‘productlevel’) AS SP

, SERVERPROPERTY (‘edition’) AS DbEdition

 

I hope you will find it useful 🙂

Adapter Design Pattern

Introduction:
Sometimes you have set of classes with different interfaces and you want to call logic on those classes in a consistent way. Adapter design pattern solve this issue, by providing a technique (best practice)  to wrap those classes somehow to make it easy to deal with this set of classes. Also Adapter is responsible of data transformation between heterogeneous interfaces .
The main benefits from Adapter Design pattern is letting classes work together that could not otherwise because of incompatible interfaces.

Example:
AdapterDesignPattern

class Program
{
static void Main(string[] args)
{
PersonBase p1 = new GoodPerson(“111111”);
PersonBase p2 = new GoodPerson(“222222”);
PersonBase p3 = new GoodPerson(“333333”);
p1.Display();
p2.Display();
p3.Display();
Console.ReadKey();
}
}
class PersonDataBank
{
//Lagecy APIs
public float GetTall(string  uniqueId)
{
switch (uniqueId)
{
case “111111”:
return 100f;
case “222222”:
return 102f;
case “333333”:
return 103f;
default:
return 150f;
}
}
public DateTime GetDateOfBith(string uniqueId)
{
switch (uniqueId)
{
case “111111”:
return DateTime.Parse(“1/1/2000”); ;
case “222222”:
return DateTime.Parse(“1/1/2001”); ;
case “333333”:
return DateTime.Parse(“1/1/2002”); ;
default:
return DateTime.Parse(“1/1/2003”); ;
}
}
public string GetBirthPlace(string uniqueId)
{
switch (uniqueId)
{
case “111111”:
return “USA,Los Angeles”;
case “222222”:
return “USA,SD”;
case “333333”:
return “USA,LV”;
default:
return “USA,WA”;
}
}
}
class PersonBase
{
public float Tall {get;set;}
public DateTime DateOfBirth {get;set;}
public string BithPlace {get;set;}
protected string uniqueId { get; set; }
public PersonBase(string uniqueId)
{
this.uniqueId = uniqueId;
}
public virtual void Display()
{
Console.WriteLine(“\nPerson: {0} “, this.uniqueId);
}
}
class GoodPerson: PersonBase
{
public GoodPerson(string uniqueId) :base(uniqueId)
{
}
public override void Display()
{
PersonDataBank bank = new PersonDataBank();
base.DateOfBirth = bank.GetDateOfBith(base.uniqueId);
base.BithPlace = bank.GetBirthPlace(base.uniqueId);
base.Tall = bank.GetTall(base.uniqueId);
base.Display();
Console.WriteLine(” DOB: {0}”, DateOfBirth);
Console.WriteLine(” Birth Place : {0}”, BithPlace);
Console.WriteLine(” Tall: {0}”, Tall);
Console.WriteLine(“=====================”);
}
}

Download Code

Contenet Management System (CMS)

What is CMS?

    Computer management system (CMS) is computer software that is used to create, edit and publish contents of websites. Typically, CMS is used to store, control, versioning and publish industry-specific documentations such as manuals, guides, articles…etc. CMS’s users are supposed to edit and publish content of his own site without involving any technical resources. CMS system mainly contains 2 subsystems, which are: Content Management application (CMA) and the content delivery application (CDA).

What is Content Management Application (CMA)?

      This subsystem allow content manager or content author, who have no technical background on HTML editing , to create, edit, delete content from website with no need for any technical resources.

What is Content Delivery Application (CDA)?

      This subsystem is responsible about rendering the content that already managed by CMA on user’s browser.

CMS Features:

  1. Store documents, videos and other type of electronic files.

  2. Publishing feature of CMS allows users to choose a template from a pre-defined set of templates adopted by organization, as well as using wizards and other tools to manage web site contents. Format management feature of CMS is responsible about how to render documents into HTML or PDF formats.

  3. Versioning feature of CMS allows users to update contents without losing the old contents. This feature enable users to get back to old contents any time and even restore it back to website as well as keep tracking of changes had been done on website contents.

  4. Searching feature of CMS allows users to search for website contents by using keywords. This means that CMS system should indexes all data and website contents.

  5. Identify the main users and their roles within CMS system.

  6. The ability to assign specific security permission for a specific document.

  7. Define workflows, tasks and even events messaging so that author of the content got notified of any change.

Why do you need CMS?

     When your organization has a public website or an intranet site and this site has grown over the time. And much of the content of this site start being out-dated or inaccurate and you can’t find things. As well as you have to update the content of this site periodically with no need for technical resource. You start lost tracking of pages on your website.

Actually these problems are natural when you are using manual tools to edit your site… manual tools like Dreamweaver, Frontpage..etc.

CMS system is specifically designed to solve all of the above issues.

Benefits from using CMS:

  1. Make editing your site easier and straightforward.
  2. Your site will have a consistent look and feel.
  3. Improved site navigation.
  4. Increased security.
  5. Reduced duplication of information.
  6. Greater capacity for growth.
  7. Reduced site maintenance costs.
  8. Keep track of site changes.
  9. Support your business goals and strategies, by improve Sales and user satisfaction as well as make communication with public more efficient.

Builder Design Pattern

Introduction:
Sometimes you need to build your Classes in such away where its representation is different according to some attributes and this representation of this class needs to be separated from its construction. Builder Design pattern solve this issue by abstract complex object construction from its representation.

Example:
An example of Builder Design pattern is how to assemble vehicles in a step by step way. we can use Vehicle builder to construct the representation of vehicles in a step by step way. this vehicle might be car, truck or even a bicycle. the below code snap shows how to utilize Builder design pattern to construct the different type of vehicles.BuilderDesignPattern

 

static void Main(string[] args)
{
VehicleBuilder builder;

// Create BuildingLine with vehicle builders
BuildingLine buildingLine = new BuildingLine();

// Construct and display vehicles
builder = new ScooterVehicleBuilder();
buildingLine.Construct(builder);
builder.Vehicle.Show();

builder = new CarVehicleBuilder();
buildingLine.Construct(builder);
builder.Vehicle.Show();

builder = new MotorCycleVehicleBuilder();
buildingLine.Construct(builder);
builder.Vehicle.Show();

// Wait for user
Console.ReadKey();
}

class BuildingLine
{
// Builder uses a complex series of steps
public void Construct(VehicleBuilder vehicleBuilder)
{
vehicleBuilder.BuildFrame();
vehicleBuilder.BuildEngine();
vehicleBuilder.BuildWheels();
vehicleBuilder.BuildDoors();
}
}

class CarVehicleBuilder : VehicleBuilder
{
public CarVehicleBuilder()
{
vehicle = new Vehicle(“Car Vehicle”);
}

public override void BuildFrame()
{
vehicle.Frame = “Car Vehicle Frame”;
}

public override void BuildEngine()
{
vehicle.Engine = “3000 CC capicity”;
}

public override void BuildWheels()
{
vehicle.Wheels  = 4;
}

public override void BuildDoors()
{
vehicle.Doors = “4”;
}
}

class MotorCycleVehicleBuilder : VehicleBuilder
{
public MotorCycleVehicleBuilder()
{
vehicle = new Vehicle(“MotorCycle Vehicle”);
}

public override void BuildFrame()
{
vehicle.Frame =  “MotorCycle Vehicle Frame”;
}

public override void BuildEngine()
{
vehicle.Engine =  “300 CC Capacity”;
}

public override void BuildWheels()
{
vehicle.Wheels =  2;
}

public override void BuildDoors()
{
vehicle.Doors =  “0”;
}
}

class ScooterVehicleBuilder : VehicleBuilder
{
public ScooterVehicleBuilder()
{
vehicle = new Vehicle(“Scooter Vehicle”);
}

public override void BuildFrame()
{
vehicle.Frame = “Scooter Vehicle Frame”;
}

public override void BuildEngine()
{
vehicle.Engine = “50 CC Capacity”;
}

public override void BuildWheels()
{
vehicle.Wheels  = 2;
}

public override void BuildDoors()
{
vehicle.Doors = “0”;
}
}

class Vehicle
{

private string _vehicleType;

// Constructor
public Vehicle(string vehicleType)
{
this._vehicleType = vehicleType;
}

public string Frame { get; set; }
public string Engine { get; set; }
public int Wheels { get; set; }
public string Doors { get; set; }

public void Show()
{
Console.WriteLine(“\n—————————“);
Console.WriteLine(“Vehicle Type: {0}”, _vehicleType);
Console.WriteLine(” Frame : {0}”, this.Frame);
Console.WriteLine(” Engine : {0}”, this.Engine);
Console.WriteLine(” #Wheels: {0}”, this.Wheels);
Console.WriteLine(” #Doors : {0}”, this.Doors);
}

}

abstract class VehicleBuilder
{
protected Vehicle vehicle;

// Gets vehicle instance
public Vehicle Vehicle
{
get { return vehicle; }
}

// Abstract build methods
public abstract void BuildFrame();
public abstract void BuildEngine();
public abstract void BuildWheels();
public abstract void BuildDoors();
}

How to Solve “Error Creating Control” Error Message (ASP.Net Site)

If you face this error while trying to open a web application project

Error Creating Control – control_Name
‘/LM/W3SVC/1/Root/Project_Name’ is not a valid IIS application.

ErrorCreatingControlSnapshot

 

You can resolve this error by following the below steps , the root cause of this error is the incorrect mapping between web application project and the virtual directory in your IIS.
To Resolve this error , follow the following steps:

1-Right click – you web application project and select Properties -> Web
2- in the server section choose Use IIS Web Server -> then click Create Virtual.
3- Clean your project from any DDLs that was previously complied and compile your project again.

By doing the above steps this issue should got resolved.

Http Handler vs Http Module

What is ASP .Net  HTTP Handler:

      An ASP.NET HTTP handler is the process (frequently referred to as the "endpoint") that runs in response to a request made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler. You can create your own HTTP handlers that render custom output to the browser

Reference: http://msdn.microsoft.com/en-us/library/bb398986.aspx

What is ASP.Net HTTP Module:

      An HTTP module is an assembly that is called on every request that is made to your application. HTTP modules are called as part of the ASP.NET request pipeline and have access to life-cycle events throughout the request. HTTP modules let you examine incoming and outgoing requests and take action based on the request.

Reference: http://msdn.microsoft.com/en-us/library/bb398986.aspx

Note:The basic different between HTTP Handler and HTTP Module, is that HTTP Module is event based processor.

Example of How to implement HTTP Handler:

using System;
using System.Web;
using System.IO;
namespace MyNamespace
{
public class MyHttpHandler  : IHttpHandler
{
    public void ProcessRequest(System.Web.HttpContext context)
    {
           context.Response.Write("The page request is " + context.Request.RawUrl.ToString());
           StreamWriter sw = new StreamWriter(@"C:\requestLog.txt",true);
           try
           {
                sw.WriteLine("Page requested at " + DateTime.Now.ToString() +
                              context.Request.RawUrl); sw.Close();
           }
           finally {  sw.Close();    }
    }
    public bool IsReusable
     {
            get
            {
                    return true;
                }
        }
}

 

Before you will be able to do Call for this HTTP Handler, you need to do the followings:
      1.  Add the following tags into your Web.Config file

<system.web>
    <httpHandlers>
          <add verb="*" path="*.WhatEverExtension" type="MyNamespace.MyHttpHandler  , MyAssemblyName"/>
      </httpHandlers>
</system.web>

2.  You need to add the extension you added on step 1 to your IIS so that IIS will recognize the new extensions… on our example you need to add "WhatEverExtension" to IIS
Example of how to implement HTTP Module:

namespace MyNamespace
{
public class MyHttpModule : IHttpModule
{
public MyHttpModule()
{}
public void Init(HttpApplication objApplication)
{
objApplication.BeginRequest += new EventHandler(context_BeginRequest);
objApplication.EndRequest += new EventHandler(context_EndRequest);
}
public void Dispose()
{
}
public void context_EndRequest(object sender, EventArgs e)
{
try
{
StreamWriter sw = new StreamWriter(@"C:\requestLog.txt",true);
sw.WriteLine("End Request called at " + DateTime.Now.ToString());
}
finally {sw.Close(); }
}
public void context_BeginRequest(object sender, EventArgs e)
{
try
{
StreamWriter sw = new StreamWriter(@"C:\requestLog.txt",true);
sw.WriteLine("Begin request called at " + DateTime.Now.ToString());
}
finally { sw.Close(); }
}
}
}

For HTTP Module you need also to register this HTTP Module on your Web.config file… to do so , add the following tags to your Web.config file :

<httpModules>
        <add name="clsMyModule" type="MyNamespace.MyHttpModule, MyAssemblyName"/>
</httpModules>

List of HTTP Module Supported Events by :

 

Event Name Description
AcquireRequestState This event is raised when ASP.NET runtime is ready to acquire the Session state of the current HTTP request.
AuthenticateRequest This event is raised when ASP.NET runtime is ready to authenticate the identity of the user.
AuthorizeRequest This event is raised when ASP.NET runtime is ready to authorize the user for the resources user is trying to access.
BeginRequest This event is raised when ASP.NET runtime receives a new HTTP request.
Disposed This event is raised when ASP.NET completes the processing of HTTP request.
EndRequest This event is raised just before sending the response content to the client.
Error This event is raised when an unhandled exception occurs during the processing of HTTP request.
PostRequestHandlerExecute This event is raised just after HTTP handler finishes execution.
PreRequestHandlerExecute This event is raised just before ASP.NET begins executing a handler for the HTTP request. After this event, ASP.NET will forward the request to the appropriate HTTP handler.
PreSendRequestContent This event is raised just before ASP.NET sends the response contents to the client. This event allows us to change the contents before it gets delivered to the client. We can use this event to add the contents, which are common in all pages, to the page output. For example, a common menu, header or footer.
PreSendRequestHeaders This event is raised just before ASP.NET sends the HTTP response headers to the client. This event allows us to change the headers before they get delivered to the client. We can use this event to add cookies and custom data into headers.
ReleaseRequestState This event is raised after ASP.NET finishes executing all request handlers.
ResolveRequestCache This event is raised to determine whether the request can be fulfilled by returning the contents from the Output Cache. This depends on how the Output Caching has been setup for your web application.
UpdateRequestCache This event is raised when ASP.NET has completed processing the current HTTP request and the output contents are ready to be added to the Output Cache. This depends on how the Output Caching has been setup for your Web application.

Search Issue when using Visual Studio 2003 on Windows Vista Operating system

A couple of days ago, I faced a small issue when I tried to search specific value inside VS 2003 solutions while I have MS Windows Vista OS installed on my PC…. Doing searching will cause VS 2003 to be hanged and stop responding.. I overcome this issue by Disable Visual Themes for VS 2003.. To do so please follow the following steps:

  1. Right click on VS 2003 shortcut

  2. On compatibility tab , make sure to check "Disable Visual Themes" check box

  3. Click on OK button..

Now , You can enjoy Searching your VS 2003 solution.

How to solve XML configuration problem when you use unit testing

One of the first challenges I faced when I decided to use Unit Testing projects to test my Methods/Classes, is how to use XML configuration files with unit testing projects…

Basically the issue appear because my project using XML file as configuration file. And when I compile my Unite testing project, the compiler will copy only DLLs related to project being tested with no other resources including the configuration file(s) … this will cause all of my unit test methods to be failed because there is no configuration file available for Unit Test Project.

The solution is pretty easy… all what you have to do is to add the following attribute to Test Method header. This attribute will tell compiler to copy the file into Bin folder and things will go smooth.

[TestMethod(),DeploymentItem("XmlConfigurationFileName.XML")]

public void TestMethodName()

{

         //Method body goes here….

}

Design Patterns

What is Design Pattern:

Design Pattern: Is a general reusable solution to a commonly occurring problem in software.

Design Patten is a description or template of how to solve the problem we usually face during software development life cycle. It is showing relationship between classes without specifying how the final application will looks like. It is usually show the overall pattern that followed by the entire application/system.

Benefits of using Design Patterns:

  • It is proven solution to solve issues related to Software Development, and it facilitates thedevelopment of higly cohesive modules with minimal coupling .
  • Making the overall system easier to understand and maintain.
  • Making the communication between designers more efficient. Software professionals immediately understand the design when referring to the name of the design pattern used to solve the issue during discussing  system design

Design Patterns Categories:

Creational Design Patterns:

Structural Design Patterns:

Behavioral Design Patterns: