Open Close Principle with C#

Open Close Principle is an Object Oriented Design principle. It is first introduced by Betrand Meyer in 1988. He says “Software entities (Class, module, function etc.) should be open for extension, but closed for modification”. An entity is “Open for extension” means that its behavior can be extended to accommodate new demand. The entity is “closed for modification” means that the existing source code of the module is not changed or minimum change when making enhancement. It is clear that if a system cannot accommodate change easily, its life cycle will end fast.

Sometimes code changes introduce heavy risk. At the time of changing, you must ensure that changes will not break the system. Sometimes it takes huge regression testing. This risk can be minimized if no changes are made to existing code.

So, our intention should be writing code in such a way that new functionality should be added with minimum changes or not changes in the existing code.  It should be done in a way to allow the adding of new functionality as new classes, keeping as much as possible existing code unchanged. The major advantages of “open close principle” is that it undergo changes and its value will be tremendous. It required almost no regression testing.

Let’s introduce open close principle with an example. Suppose, in our application, we need a “Area calculator” which calculate area of rectangle. However, in this occasion we just create a class AreaCalculator then there will be a method RectangleArea in this class which just calculates area of rectangle. It works fine. In the middle of the application development, we need to calculate area of Triangle and Circle. In this occasion, what should we do? We just add another two method TriangleArea and CircleArea and can do the job. But several problems will arise here – for each new shape you have to add new unit of code. Developer must have to know the logic to calculate area of new shape. Adding a new shape might effect in existing functionalities. So, it will take huge cost of regression testing. This is actually violate, open close principle.

We implement the same problem abide by open close principle by the following way. Here Rectangle, Triangle and Circle class inherit the Shape class and implement CalculateArea Method. In this way, if you need to calculate area of x shape just add a class of x and then implement shape and calculate area of x without modifying exiting code.

Class diagram:

OCP class diagrm

Open Close Principle Implementation by C#:

Step 1: Create abstract Shape class


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OCP
{
public abstract class Shape
{
public abstract double CalculateArea();
}
}

Step 2: Create Rectangle class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OCP
{
public class Rectangle : Shape
{
public double Height { get; set; }
public double Width { get; set; }

public Rectangle(double height, double width)
{
this.Height = height;
this.Width = width;
}

public override double CalculateArea()
{
return Height * Width;
}
}
}

Step 3: Create Triangle class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OCP
{
public class Triangle : Shape
{
public double Base { get; set; }
public double Height { get; set; }

public Triangle(double vbase, double vheight)
{
this.Base = vbase;
this.Height = vheight;
}

public override double CalculateArea()
{
return 1 / 2.0 * Base * Height;
}
}
}

Step 4: Create circle class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OCP
{
public class Circle : Shape
{
public double Radius { get; set; }

public Circle(double radius)
{
this.Radius = radius;
}

public override double CalculateArea()
{
return Math.PI * Radius * Radius;
}
}
}

Step 5: Client class which uses Rectangle, Triangle and Circle class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace OCP
{
public class Program
{
public static void Main(string[] args)
{
Shape objShape = new Rectangle(20, 30);
Console.WriteLine("Area of Rectangle: " + objShape.CalculateArea());

objShape = new Triangle(20, 30);
Console.WriteLine("Area of Triangle: " + objShape.CalculateArea());

objShape = new Circle(4);
Console.WriteLine("Area of Circle: " + objShape.CalculateArea());

Console.ReadKey();
}
}
}

Abstract Class and Method with C# – A detail description

What is Abstract Class?

Abstract class is a class that has no direct instances, but its descendants may have direct instances.  An abstract class is a class that can contain abstract members, although it is not required. But any class that contains abstract member must be abstract. An abstract class can also contain non-abstract members.

An abstract method is an empty method – a method that has no implementation. Any class that implement this abstract class must implement the abstract method. We always use interface in C#, it is implicitly abstract.

Why abstract class?

The purpose of an abstract class is to act as a base class. It is not possible to instantiate an abstract class directly, nor can an abstract class be sealed. Often we need a class that contains methods that must be implemented by all derived classes but not by the base class itself. By this, actually we force the programmer to implement base class methods. Think a simple scenario. Suppose we want to develop a banking software. Here a common entity is account information. There are many type of account like savings account,  current account e.t.c in bank. In every account two things is common that is deposit and withdraw. So we can create a Account class as base class which must have this two method deposit and withdraw and it will be abstract method and the Account class will be abstract class. So, you can say – why its will be abstract class and abstract method? Answer of the first question is if there is any abstract member in the class, the class must be abstract. Answer of the second question, in every type of accounts two things is common deposit and withdraw but their way of transaction may be different. We just want to enforce the programmer to implement the methods if the create any class by inheriting the Account class

Syntax

The syntax for creating an abstract method is – use the abstract modifier with the name of the method and the parameters, followed by a semicolon by keeping it empty. It will be look like this.

[access-modifiers] abstract return-type method-name ([parameters]) ;

Example:

The following example shows how to create an abstract class Account with two abstract methods Deposit and Withdraw.

public abstract class Account
{
public abstract string Deposit(double money);
public abstract string Withdraw(double money);
}

The benefit of creating abstract methods is that it enables you to add methods to your base class that subsequently must be implemented by all derived classes, but the implementation details for these methods do not have to be defined in the base class.

Override the abstract class
When a derived class inherits an abstract method from an abstract class, it must override the abstract methods. This requirement is enforced at compile time.
The following example shows how a SavingsAccount class, which is derived from Account, uses the override keyword to implement the Deposit and Withdraw method. Here first (Account) class is base class and second (SavingsAccount) is derived class.

///
/// Base class
///
public abstract class Account
{
public abstract string Deposit(double money);
public abstract string Withdraw(double money);
}

///
/// Derived class
///
public class SavingsAccount : Account
{

//override the base class
public override string Deposit(double money)
{
return "AC type savings: Deposit transaction done sucessfully";
}

public override string Withdraw(double money)
{
return "AC type savings: Withdraw transaction done sucessfully";
}
}

After creating instance of SavingsAccount, if you call Deposit and withdraw method you will see the following output:
AC type savings: Deposit transaction done sucessfully
AC type savings: Withdraw transaction done sucessfully

Abstract class with virtual method:
You can also create an abstract class that contains virtual methods, as shown in the following example:

///
/// Base class
///

public abstract class Account
{
public virtual void BankName()
{
Console.WriteLine("Welcome to ABC Bank Limited");
}

public abstract string Deposit(double money);
public abstract string Withdraw(double money);
}

In this case, a derived class does not have to provide an implementation of the BankName method because BankName is defined as virtual. Therefore, I say the important thing again, if you have a generic method that is common to all derived classes, and you want to force each derived class to implement the method, you must define the method as abstract in the base class.

Difference between an abstract method & virtual method:

Virtual method has an implementation and provides the derived class with the option of overriding it. Abstract method does not provide an implementation and forces the derived class to override the method.

Abstract Properties:

Properties may also be declared as abstract. Same as abstract method, to declare an abstract property, specify the property name and the accessors that the derived property should implement.
Example:

///
/// Base class
///

public abstract class Account
{
//Abastract property
public abstract string AccountNo { get; set; }

//Virtual Method
public virtual void BankName()
{
Console.WriteLine("Welcome to ABC Bank Limited");
}

public abstract string Deposit(double money);
public abstract string Withdraw(double money);
}

Total Solution:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

/*
* Author : Md. Mahedee Hasan
* Create Date : 14/04/2012
* web : mahedee.blogspot.com
*/

namespace ConsoleProgram
{

///
/// Base class
///

public abstract class Account
{
//Abastract property
public abstract string AccountNo { get; set; }

//Virtual Method
public virtual void BankName()
{
Console.WriteLine("Welcome to ABC Bank Limited");
}

//Abstract Method
public abstract string Deposit(double money);
public abstract string Withdraw(double money);
}

///
/// Derived class
///

public class SavingsAccount : Account
{
private string acccNo;

//override the base class
public override string Deposit(double money)
{
return "AC type savings: Deposit transaction done sucessfully";
}

public override string Withdraw(double money)
{
return "AC type savings: Withdraw transaction done sucessfully";
}

//Override base class property
public override string AccountNo
{
get
{
return acccNo;
}
set
{
acccNo = value;
}
}
}

///
/// Main class
///

class Program
{
///
/// Main Method
///
///

static void Main(string[] args)
{
SavingsAccount objSavingsAccount = new SavingsAccount();
objSavingsAccount.BankName();
objSavingsAccount.AccountNo = "0110";
Console.WriteLine("Account Number: " + objSavingsAccount.AccountNo);
string msg = objSavingsAccount.Deposit(1000);
Console.WriteLine(msg);
msg = objSavingsAccount.Deposit(500);
Console.WriteLine(msg);

}
}
}

Output:
Welcome to ABC Bank Limited
Account Number: 0110
AC type savings: Deposit transaction done sucessfully
AC type savings: Deposit transaction done sucessfully

At a glance:
· An abstract class is a generic base class.
– Contains abstract methods that must be implemented by the derived class.
· Cannot create instance of abstract class.
· Abstract class can contain no abstract members.

Determine whether Caps Lock is ON in ASP.net Page by JavaScript

Here I used a simple Textbox in ASP.net page and used Javascript to determine whether Caps Lock is on or off.
I have used the following Javascript code in between head  tag.
function isCapslock(e) {

            e = (e) ? e : window.event;

            var charCode = false;

            if (e.which) {
                charCode = e.which;
            } else if (e.keyCode) {
                charCode = e.keyCode;
            }

            var shifton = false;
            if (e.shiftKey) {
                shifton = e.shiftKey;
            } else if (e.modifiers) {
                shifton = !!(e.modifiers & 4);
            }

            if (charCode >= 97 && charCode <= 122 && shifton) {
                document.getElementById("txtCapsMsg").value = "Caps Lock is on";
                return true;
            }

            if (charCode >= 65 && charCode <= 90 && !shifton) {
                document.getElementById("txtCapsMsg").value = "Caps Lock is on";
                return true;
            }

            document.getElementById("txtCapsMsg").value = "Caps Lock is off";
            return false;

        }

I have also used two text box in ASP.net page. One for input and another for displaying message whether Caps Lock is on or off.

Message :
Input Text :

Now input some text in input textbox. Message will be showed in txtCapsMsg, textbox whether Caps Lock is on or off.

How to enable hibernate on windows 8.1

Step 1: Press Windows + R to get “run” window and type “powercfg.cpl”

1

Press enter. Now you will be lead to “Power options” window.

2

Step 2: Click on “Choose what power buttons do”.

3

Step 3: Click on “Change settings that are currently unavailable”

4

Now some controls are enabled. Scroll down, there you can able to see “Hibernate” option which is not ticked.

5Step 4: Check “Hibernate”

6

And “Save changes”.

Now, right click on start button..

7

After this change, “Hibernate” will be visible in settings charm shutdown command also

8

Singleton Design Pattern with C#

Design Pattern

Design pattern is a solution of known problems. These are strategies of solving commonly occurring problems. A design pattern is not a finish design. It is like a template to solve a problem.

Singleton Design Pattern

Singleton is a software design pattern. It is restrict to create object more than once. This is actually needed when one object can perform its action in whole system. We frequently use a database connection object to connect with database. We don’t need multiple objects to create connection with database and close it. We can use singleton in this scenario.

Implementation of Singleton by C#

Step 1: Create EmployeeInfo class

This class is to hold employee information.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Singleton
{
public class EmployeeInfo
{
public string EmpName { get; set; }
public string EmpDesignation { get; set; }
public int MonthlySalary { get; set; }
}
}

Step 2: Create a singleton class

Here EmployeeService is a singleton class. Constructor of this class is private so that nobody can create its instance from outside.  Instance() is a static method which creates instance of the singleton class. It actually forces that only one instance of the object will be created. Lock() is used to create instance of the singleton pattern in thread safe manner in multi threaded environment. The other two methods are used to add employee information in list and get employee salary. These two are as usual method.Don’t mix up Singleton class and Static class. Keep in mind; in static class everything must be static like Method, constructor, properties. But in singleton class it is not required. Hope, you will be clear after the following example.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Singleton
{
///
/// EmployeeService is a singleton class
///

public class EmployeeService
{

//Static object of singleton class
private static EmployeeService instance;

private List lstEmployeeInfo = null;

///
/// Restrict to create object of Singleton class
///

private EmployeeService()
{
if (lstEmployeeInfo == null)
{
lstEmployeeInfo = new List();
}
}

///
/// The static method to provide global access to the singleton object.
///

/// Singleton object of EmployeeService class
public static EmployeeService Instance()
{

if (instance == null)
{
//Thread safe singleton

lock (typeof(EmployeeService))
{
instance = new EmployeeService();
}
}

return instance;
}

///
/// Add employee information to the Employee information list
///

///

public void AddEmployeeInfo(EmployeeInfo objEmployeeInfo)
{
lstEmployeeInfo.Add(objEmployeeInfo);
}

///
/// Get Salary by Name
///

////// Salary of Employee

public int GetEmployeeSalaryByName(string name)
{
int monthlySalary = 0;
foreach (EmployeeInfo objEmployeeInfo in lstEmployeeInfo)
{
if (objEmployeeInfo.EmpName.Contains(name))
monthlySalary = objEmployeeInfo.MonthlySalary;
}
return monthlySalary;
}

}
}

Step 3: Access singleton class

This class creates an instance of singleton class by EmployeeService objEmployeeService = EmployeeService.Instance(); and access singleton class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Singleton
{
class Program
{
static void Main(string[] args)
{
EmployeeInfo objEmpInfo1 = new EmployeeInfo() { EmpName = "Mahedee", EmpDesignation = "Senior Software Engineer", MonthlySalary = 00000 };
EmployeeInfo objEmpInfo2 = new EmployeeInfo() { EmpName = "Kamal", EmpDesignation = "Software Engineer", MonthlySalary = 30000 };

//Create a singleton object
EmployeeService objEmployeeService = EmployeeService.Instance();

objEmployeeService.AddEmployeeInfo(objEmpInfo1);
objEmployeeService.AddEmployeeInfo(objEmpInfo2);

Console.WriteLine(objEmpInfo2.EmpName + " : " + objEmployeeService.GetEmployeeSalaryByName("Kamal"));

Console.ReadLine();

}
}
}