Pages

Thursday, June 25, 2015

Behavioral Pattern - Strategy Pattern

Let’s understand the widely accepted definition of strategy pattern which you can find from various resources on net. “Strategy pattern defines a family of algorithms, encapsulates each one of them and makes them interchangeable.” Confused with the definition? let’s try to break it in three parts:-
1) Family of Algorithms- The definition says that the pattern defines the family of algorithms- it means we have functionality (in these algorithms) which will do the same common thing for our object, but in different ways.
2) Encapsulate each one of them- The pattern would force you to place your algorithms in different classes (encapsulate them). Doing so would help us in selecting the appropriate algorithm for our object.
3) Make them interchangeable- The beauty with strategy pattern is we can select at run time which algorithm we should apply to our object and can replace them with one another
For Example
public interface IWeaponBehavior
    {
        string UseWeapon();
    }

    public class KnifeBehavior : IWeaponBehavior
    {
        public string UseWeapon()
        {
            return "Knife Used";
        }
    }

    public class AxeBehavior : IWeaponBehavior
    {
        public string UseWeapon()
        {
            return "Axe Used";
        }
    }

    public class SwordBehavior : IWeaponBehavior
    {
        public string UseWeapon()
        {
            return "Sword Used";
        }
    }

    public class BowAndArrowBehavior : IWeaponBehavior
    {
        public string UseWeapon()
        {
            return "Bow And Arrow Used";
        }
    }


    public abstract class Character
    {
        protected IWeaponBehavior weapon;

        public void SetWeapon(IWeaponBehavior w)
        {
            this.weapon = w;
        }

        public abstract string fight();

        public string performfight()
        {
            return weapon.UseWeapon();
        }
    }


    public class Queen : Character
    {
        public Queen()
        {
            weapon = new BowAndArrowBehavior();
        }

        public override string fight()
        {
            return "I am Queen";
        }
    }



    public class King : Character
    {
        public King()
        {
            weapon = new SwordBehavior();
        }

        public override string fight()
        {
            return "I am King";
        }
    }

//Client End Calling

   Character queen = new Queen();
   Console.Write("\n" + queen.fight()); 
   Console.Write("\n" + queen.performfight()); 
   queen.SetWeapon(new SwordBehavior()); // Run time behavior change
   Console.Write("\n" + queen.performfight());
         
   Character king = new King();
   Console.Write("\n\n" + king.fight()); 
   Console.Write("\n" + king.performfight());
   king.SetWeapon(new KnifeBehavior());// Run time behavior change
   Console.Write("\n" + king.performfight());
   king.SetWeapon(new AxeBehavior());// Run time behavior change
   Console.Write("\n" + king.performfight());
   Console.Read();

   //******************************
   // BELOW IS ANOTHER EXAMPLE 
   // THANKS to head first DP 
   //****************************** 

    //******Set of behaviors as a family of alogrithms 
    public interface IFlyBehavior
    {
        string fly();
    }

    public class FlyWithWings : IFlyBehavior
    {
        public string fly()
        {
            return "fly with wings";
        }
    }

    public class FlyNoWay : IFlyBehavior
    {
        public string fly()
        {
            return "Can't fly";
        }
    }
    //************************************************

    //******Set of behaviors as a family of alogrithms 

    public interface IQuackBehavior
    {
        string quack();
    }

    public class Quack : IQuackBehavior
    {
        public string quack()
        {
            return "Duck Quack";
        }
    }

    public class Squeak : IQuackBehavior
    {
        public string quack()
        {
            return "Rubber Duckie Squeak";
        }
    }

    public class MuteQuack : IQuackBehavior
    {
        public string quack()
        {
            return "do nothing can't quack";
        }
    }
    
    //*************************************************

    //***********CLIENT END*******************************

    public abstract class Duck
    {
        protected IFlyBehavior FlyBehavior;
        protected IQuackBehavior QuackBehavior;

        public void setFlyBehavior(IFlyBehavior flybehav)
        {
            this.FlyBehavior = flybehav;
        }

        public void setQuackBehavior(IQuackBehavior quackbehav)
        {
            this.QuackBehavior = quackbehav;
        }

        public string performQuack()
        {
            return this.QuackBehavior.quack();
        }

        public string performFly()
        {
            return this.FlyBehavior.fly();
        }

        public abstract void display();

    }

    public class MallardDuck : Duck
    {
        public MallardDuck()
        {
            FlyBehavior = new FlyWithWings();
            QuackBehavior = new Quack();
        }

        public override void display()
        {
            throw new NotImplementedException();
        }
    }

    //***************************************************


    Duck Duck = new MallardDuck();
    Console.Write("\n" + Duck.performFly());
    Console.Write("\n" + Duck.performQuack());
    Duck.setFlyBehavior(new FlyNoWay()); // Run time behaviour change
    Duck.setQuackBehavior(new Squeak()); // Run time behaviour change
    Console.Write("\n" + Duck.performFly());
    Console.Write("\n" + Duck.performQuack());
    Console.Read();

Monday, June 22, 2015

"Volatile” keyword

Consider this example:
int i = 5;
System.out.println(i);
The compiler may optimize this to just print 5, like this:
System.out.println(5);
However, if there is another thread which can change i, this is the wrong behaviour. If another thread changes i to be 6, the optimized version will still print 5. The volatile keyword prevents such optimization and caching, and thus is useful when a variable can be changed by another thread.

Sunday, June 21, 2015

Creational Pattern - Abstract Factory Design Pattern

Abstract Factory Pattern


The Abstract Factory provides an interface for creating families of related or dependent objects without specifying their concrete classes. Abstract Factory provides an interface for creating families of related objects without specifying their concrete classes. It… encapsulates object creation. relies on object composition—object creation is implemented in methods exposed in the factory interface. promotes loose coupling by reducing the dependency of the application on concrete classes.
 
  class Program
    {
        static void Main(string[] args)
        {
            IAnimal IAnimal = null;
            AnimalFactory objAnimalFactory = null;
            
            objAnimalFactory = AnimalFactory.GetAnimalFactory("sea");
            Console.Write("\n\n Animal factory type is " + objAnimalFactory.GetType());
            Console.ReadKey();

            IAnimal = objAnimalFactory.GetAnimal("Shark");
            Console.Write("\n Animal type is " + IAnimal.GetType());
            Console.Write("\n Animal Speak " + IAnimal.Speak());
            Console.ReadKey();

            IAnimal = objAnimalFactory.GetAnimal("Octopus");
            Console.Write("\n Animal type is " + IAnimal.GetType());
            Console.Write("\n Animal Speak " + IAnimal.Speak());
            Console.ReadKey();

            objAnimalFactory = AnimalFactory.GetAnimalFactory("land");
            Console.Write("\n\n Animal factory type is " + objAnimalFactory.GetType());
            Console.ReadKey();

            IAnimal = objAnimalFactory.GetAnimal("Cat");
            Console.Write("\n Animal type is " + IAnimal.GetType());
            Console.Write("\n Animal Speak " + IAnimal.Speak());
            Console.ReadKey();

            IAnimal = objAnimalFactory.GetAnimal("Dog");
            Console.Write("\n Animal type is " + IAnimal.GetType());
            Console.Write("\n Animal Speak " + IAnimal.Speak());
            Console.ReadKey();

            IAnimal = objAnimalFactory.GetAnimal("Lion");
            Console.Write("\n Animal type is " + IAnimal.GetType());
            Console.Write("\n Animal Speak " + IAnimal.Speak());
            Console.ReadKey();

        }
    }
        
    //****************Abstract Factory Pattern**********************//

    public interface IAnimal
    {
        string Speak();
    }

    public class Cat : IAnimal
    {
        public string Speak()
        {
            return "MIAOO";
        }
    }

    public class Dog : IAnimal
    {
        public string Speak()
        {
            return "Bark";
        }
    }

    public class Lion : IAnimal
    {
        public string Speak()
        {
            return "Roar";
        }
    }

    public class Shark : IAnimal
    {
        public string Speak()
        {
            return "Can't Speak";
        }
    }

    public class Octopus : IAnimal
    {
        public string Speak()
        {
            return "Can't Speak";
        }
    }

    public abstract class AnimalFactory
    {
        public abstract IAnimal GetAnimal(string animalType);

        public static AnimalFactory GetAnimalFactory(string factoryType)
        {
            AnimalFactory animalfactory = null;
            if ("sea".Equals(factoryType))
            {
                animalfactory = new SeaAnimalFactory();
            }
            else
            {
                animalfactory = new LandAnimalFactory();
            }
            return animalfactory;
        }
    }

    public class SeaAnimalFactory : AnimalFactory
    {
        public override IAnimal GetAnimal(string animalType)
        {
            IAnimal ianimal = null;
            switch (animalType)
            {
                case "Shark":
                    ianimal = new Shark();
                    break;
                case "Octopus":
                    ianimal = new Octopus();
                    break;
            }
            return ianimal;
        }
    }

    public class LandAnimalFactory : AnimalFactory
    {
        public override IAnimal GetAnimal(string animalType)
        {
            IAnimal ianimal = null;
            switch (animalType)
            {
                case "Cat":
                    ianimal = new Cat();
                    break;
                case "Dog":
                    ianimal = new Dog();
                    break;
                case "Lion":
                    ianimal = new Lion();
                    break;
            }
            return ianimal;
        }
    }
    //****************End:Abstract Factory Pattern******************//
Another Example as below:-
 
//The DataType enumeration.
public enum DataType
{
  File,
  DB
}

//The Abstract Item class.
public interface IData
{
 string GetData();
}


//The Abstract Factory interface.
public interface IDataFactory
{
  IData CreateData();
}


//The Concrete Factory #1 class.
public class DataFromDB : IDataFactory
{
  public IData CreateData()
 {
  //IMPLEMENT YOUR LOGIC
  return new Data("DataBase source");
 }
}


//The Concrete Factory #2 class.
public class DataFromFile : IDataFactory
{
  public IData CreateData()
  {
  //IMPLEMENT YOUR LOGIC
   return new Data("File source");
  }
}


//The Item class.
public class Data : IData
{
 private string _value;
 public Data(string value)
 {
 _value = value;
 }
 public string GetData()
 {
  return _value;
  }
}


//The Client class.
public class DataSource
{
  private IData _data;
  public DataSource(DataType dataType)
  {
   IDataFactory factory;
   switch (dataType)
   {
    case DataType.File:
     factory = new DataFromFile();
     _data = factory.CreateData();
     break;

    case DataType.DB:
     factory = new DataFromDB();
     _data = factory.CreateData();
     break;
   }
}


public string GetDataFromSource()
 {
  return _data.GetData();
 }

}

//The following code shows how to call the Abstract Factory from an application client:
DataSource ds = new DataSource(DataType.DB);
DataSource ds = new DataSource(DataType.File);
string result = ds.GetDataFromSource();

Creational Pattern - Factory Design Pattern

Factory Design Pattern 
The factory design pattern is very simple. Several other patterns, like the abstract factory pattern, build off of it though, so it is a common base pattern. You use this pattern when one or more of the following are true:

1. A class can't anticipate the class of object it must create.
2. A class wants its subclasses to specify the objects it creates.
3. Classes delegate responsibility to one of several helper subclasses, and you want to localize the knowledge of which helper subclass is the delegate.[GOF108]

The class is easy to implement and consists of an identifier, either named constants or an enum and a switch statement. For our example we will be creating dog objects. As with any good OO design we start with an interface for our related objects. The IDog interface Code:
    public interface IDog
      {
        void Bark();
        void Scratch();
      }
We just define a couple of simple methods for our dogs to do. Now for the two actual concrete dog classes. We define a bulldog and poodle class: Code:
    public class CPoodle : IDog
    {
         public CPoodle()
          {
           Console.WriteLine("Creating Poodle");
           }

         public void Bark()
          {
          Console.WriteLine("Yip Yip");
           }
    
         public void Scratch()
          {
          Console.WriteLine("Scratch Scratch");
          }
    }


    public class CBullDog : IDog
    {
      public CBullDog()
       {
        Console.WriteLine("Creating Bulldog");
       }

     public void Bark()
       {
       Console.WriteLine("Wooof Wooof");
       }

    public void Scratch()
       {
       Console.WriteLine("Scratch Slobber Scratch");
       }

    }
Now for our factory class. It’s static and contains one method to return the correct dog. Code:
    public class CDogFactory
    {
        public enum DogType
        {
            Poodle, Bulldog
        }

        static CDogFactory()
        {

        }

        public static IDog CreateDog(DogType TypeOfDog)
        {
            switch (TypeOfDog)
            {

                case DogType.Bulldog:
                    return new CBullDog();
                case DogType.Poodle:
                    return new CPoodle();
                default:
                    throw new ArgumentException("Invalid Dog Type!");
            }
        }
    }
We make the class static so we don’t need an instance of the class. To test the class, I have created a simple function. Our test function just return the dogs and uses them. In a more real world app, the type of dog would have been determined by the user or through program logic. Code:
 
IDog dog1;
IDog dog2;
dog1 = CDogFactory.CreateDog(CDogFactory.DogType.Bulldog);
dog2 = CDogFactory.CreateDog(CDogFactory.DogType.Poodle);

dog1.Bark();
dog1.Scratch();

dog2.Bark();
dog2.Scratch();
Problem
For example we have a scenario where based on user input we need to call particular class methods. I have a customer input screen. He enters his choice whether they want to buy a bike or a car. Normally we get input from the user and based on that will create an object in the client class and call those methods like below.
//
// customer enters their choice
//
If (choice == “Car”)
{
 // call car class and it’s methods
 Car c = new car();
 c.buy();
}
If (choice == “bike”)
{
 // call bike class and it’s methods
 Bike b = new Bike();
 b.buy()
}
...
In case in future if there is any other vehicle added then we need to change the client functionality. The above client code depicts that there are classes Car, Bike, and a method Buy. There is no security at the client side. Need to use the new keyword in client classes. To avoid these problems Factory pattern is used.
Solution
Problem 1 Create a new interface to depict methods, for example, in our scenario, it is Buy(). Using this interface it will solve problems 1 and 2.
//
// Interface
//
public interface IChoice
{
    string Buy();
}
A new class will be added and this class we will be called factory class. This class sits between the client class and the business class and based on user choice it will return the respective class object through the interface. It will solve problem 3.
//
// Factory Class
//
public class FactoryChoice
{
    static public IChoice getChoiceObj(string cChoice)
     {
        IChoice objChoice=null;
        if (cChoice.ToLower() == "car")
        {
            objChoice = new clsCar();
        }
        else if (cChoice.ToLower() == "bike")
        {
            objChoice = new clsBike();
        }
        else
        {
            objChoice = new InvalidChoice();
        }
        return objChoice;
    }
}
 
//Business classes
//Car
public class clsBike:IChoice
{
    #region IChoice Members
 
    public string Buy()
    {
        return ("You choose Bike");
    }
 
    #endregion
}
 
//Bike
public class clsCar:IChoice
{
 
    #region IChoice Members
 
    public string Buy()
    {
        return ("You choose Car");
    }
 
    #endregion
}
From the client class call the factory class object and it will return the interface object. Through the interface object we will call the respective method.
//Client class
IChoice objInvoice;
objInvoice = FactoryClass.FactoryChoice.getChoiceObj(txtChoice.Text.Trim());
MessageBox.Show(objInvoice.Buy());
In future if we need to add a new vehicle then there is no need to change the client class, simply return that object using the factory class. Advantages Suppose we want to add a decoupled structure and don’t want to disturb the client environment again and again, this pattern is very useful. The factory class will take all the burden of object creations.

Const, ReadOnly, Static ReadOnly and Static

Constant
Constant fields or local variables must be assigned a value at the time of declaration and after that they cannot be modified. By default constant are static, hence you cannot define a constant type as static.

public const int X = 10;

A const field is a compile-time constant. A constant field or local variable can be initialized with a constant expression which must be fully evaluated at compile time.

void Calculate(int Z)
{

 const int X = 10, X1 = 50;
 const int Y = X + X1; //no error, since its evaluated a compile time
 const int Y1 = X + Z; //gives error, since its evaluated at run time
}

You can apply const keyword to built-in value types (byte, short, int, long, char, float, double, decimal, bool), enum, a string literal, or a reference type which can be assigned with a value null.
const MyClass obj1 = null;//no error, since its evaluated a compile time
const MyClass obj2 = new MyClass();//gives error, since its evaluated at run time
Constants can be marked as public, private, protected, internal, or protected internal access modifiers.
Use the const modifier when you sure that the value a field or local variable would not be changed.

ReadOnly
A readonly field can be initialized either at the time of declaration or with in the constructor of same class. Therefore, readonly fields can be used for run-time constants.
class MyClass
{
 readonly int X = 10; // initialized at the time of declaration
 readonly int X1;
 
 public MyClass(int x1)
 {
 X1 = x1; // initialized at run time
 }
}
Explicitly, you can specify a readonly field as static since, like constant by default it is not static. Readonly keyword can be apply to value type and reference type (which initialized by using the new keyword) both. Also, delegate and event could not be readonly. Use the readonly modifier when you want to make a field constant at run time. Initialize the value in the static constructor, it gives an error.  

Static ReadOnly
A Static Readonly type variable's value can be assigned at runtime or assigned at compile time and changed at runtime. But this variable's value can only be changed in the static constructor. And cannot be changed further. It can change only once at runtime.

Static
The static keyword is used to specify a static member, which means static members are common to all the objects and they do not tied to a specific object. This keyword can be used with classes, fields, methods, properties, operators, events, and constructors, but it cannot be used with indexers, destructors, or types other than classes.
class MyClass
{
 static int X = 10;
 int Y = 20;
 public static void Show()
 {
 Console.WriteLine(X);
 Console.WriteLine(Y); //error, since you can access only static members
 }
}
Key points about Static keyword
  1. If the static keyword is applied to a class, all the members of the class must be static. 
  2. Static methods can only access static members of same class. Static properties are used to get or set the value of static fields of a class. 
  3. Static constructor can't be parametrized. Access modifiers can not be applied on Static constructor, it is always a public default constructor which is used to initialize static fields of the class.

Tuesday, June 16, 2015

How to publish website using command prompt

MS provide a command msbuild which is really helpful to published build on some specific location.
Before publishing web site, we need to create a publish profile using VS.

Note: the below contents requires to have VS 2012 (or VS2010 for that matter) and the Azure SDK on top of that. The features were not included in the RTM drop of VS2012.

After creating a publish profile in VS the following are created:
  • Start Visual Studio command prompt
  • A publish profile (.pubxml file) under App_Data/PublishProfiles
  • A website.publishproj in the root of the website

For eg:-

msbuild test.Web.csproj /p:DeployOnBuild=true /p:PublishProfile=Target

msbuild "G:\XXX\XX\XX\XX\test.Web\test.Web.csproj" /p:DeployOnBuild=true /p:PublishProfile=Target
msbuild test.Web.csproj /t:Rebuild /p:outdir="f:\target\" /p:Configuration=Release /p:Platform="Any CPU"
  1. 'test.web.csproj': Is a project solution. Before excuting command we need to navigate to solution path using cd command.
  2. '/p:DeployOnBuild=true': Set property true, in order to deploye once buid completed.
  3. '/p:PublishProfile': Is a published profile name that we may need to deployed on mentioned location
Another way is to create buid.xml file.

Create a build.xml file thats look like below
Start Visual Studio command prompt

Run msbuild build.xml
<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="4.0" DefaultTargets="Build">

  <PropertyGroup>
    <Build>$(MSBuildProjectDirectory)\Build</Build>
    <ProjectFile>MyProject.csproj</ProjectFile> 
    <ProjectName>MyProjectNameInVisualStudio</ProjectName>
    <CopyTo>$(MSBuildProjectDirectory)\CopyTo</CopyTo>
  </PropertyGroup> 

  <Target Name="Build"> 
    <RemoveDir Directories="$(Build)"/>  
    <MSBuild Projects="$(ProjectFile)" Properties="Configuration=Release;OutputPath=$(Build);OutDir=$(Build)/"></MSBuild>  
    <Exec Command="robocopy.exe  $(Build)\_PublishedWebsites\$(ProjectName) $(CopyTo) /e /is
      if %errorlevel% leq 4 exit 0 else exit %errorlevel%"/>    
  </Target>

</Project>
 
Thanks 

Core Javascript


Classes In Javascript


1. Using a function

This is probably one of the most common ways. You define a normal JavaScript function and then create an object by using the new keyword. To define properties and methods for an object created using function(), you use the this keyword, as seen in the following example.

   Process = function()
    {
        this.a = 12;
        this.Step = function(){
            this.a=13;
            alert(this.a);
        }
    }
    var obj = new Process();
    alert(obj.a)
    obj.Step();

 OR
    clsPerson = function()
    {
        this.per = "This is";
        clsPerson.prototype.employee = function(){
            this.per += " another ";
            alert(this.per + "employee method");
        }

        this.accountant = function(){
            alert(this.per + "accountant method");
        }

        clsPerson.prototype.hr = function(){
             this.per += " so ";
             alert(this.per + "hr method");
        }
    }
    var obj = new clsPerson();
    obj.employee();
    obj.accountant();
    obj.hr(); 

2. Using object

Literals are shorter way to define objects and arrays in JavaScript. To create an empty object using you can do:

var o = {};
instead of the "normal" way:
var o = new Object();
For arrays you can do:
var a = [];
instead of:
var a = new Array();
So you can skip the class-like stuff and create an instance (object) immediately. Here's the same functionality as described in the previous examples, but using object literal syntax this time:
    var step = {
        a: 12,
        process: function(){
            a = 13;
            alert(a);
        }
    }
    alert(step.a);
    step.process();


3. Singleton using a function

The third way presented in this article is a combination of the other two you already saw. You can use a function to define a singleton object.

    var step = new function(){
        this.a = 2;
        this.prcoess = function(){
            this.a=3;
            alert(this.a);
        }
    }
    alert(step.a);
    step.prcoess();

Understanding JavaScript Closures

In JavaScript, a closure is a function to which the variables of the surrounding context are bound by reference.
    
 A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain. The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function’s variables, and it has access to the global variables.

The inner function has access not only to the outer function’s variables, but also to the outer function’s parameters. Note that the inner function cannot call the outer function’s arguments object, however, even though it can call the outer function’s parameters directly.

You create a closure by adding a function inside another function.
A Basic Example of Closures in JavaScript:

   function showName (firstName, lastName) 
       {

          ​var nameIntro = "Your name is ";// this inner function has access to the outer function's variables, including the    parameter​
         ​function makeFullName () {
      
              ​return nameIntro + firstName + " " + lastName;
  
         }
        ​return makeFullName ();

        }

   showName ("Michael", "Jackson"); // Your name is Michael Jackson

Closures are used extensively in Node.js; they are workhorses in Node.js’ asynchronous, non-blocking architecture. Closures are also frequently used in jQuery and just about every piece of JavaScript code you read.
A Classic jQuery Example of Closures:


  $(function() {
    ​var selections = [];
        $(".niners").click(function() { // this closure has access to the selections variable​
           selections.push (this.prop("name")); // update the selections variable in the outer function's scope​
        });
    });

Another Example:-
function getMeAClosure() {
    var canYouSeeMe = "here I am";
    return (function theClosure() {
        return {canYouSeeIt: canYouSeeMe ? "yes!": "no"};
    });
}
var closure = getMeAClosure();
closure().canYouSeeIt; //"yes!"

Friday, June 12, 2015

SOLID Principles Of OOPS


Overview Of S.O.L.I.D 


While Designing a class the principles of S.O.L.I.D are guidelines that can be applied to remove code smells. S.O.L.I.D
  •     Single Responsibility Principle (SRP)
  •     Open/Close Principle (OCP)
  •     Liskov Substitution Principle (LSP)
  •     Interface Segregation Principle (ISP)
  •     Dependency Inversion Principle (DIP)

Single Responsibility Principle (SRP) It states that every object should have a single responsibility, and that responsibility should be entirely encapsulated by the class. There should not be more than one reason to change the class. This means class should be designed for one purpose only. This principle states that if we have 2 reasons to change for a class, we have to split the functionality in two classes. Each class will handle only one responsibility and on future if we need to make one change we are going to make it in the class which handle it. When we need to make a change in a class having more responsibilities the change might affect the other functionality of the classes. Example- Employee class: This class is using for CRUD functionality of Employee, Then it should not have any method to MAP Employee attributes with Database columns, Because later if there is any new column added in Database, the class need to be modified which is violationg the rule of Single Responsibility Principle.


Open/Close Principle (OCP) It states that Class should be open for extension not for modification. Usually, many changes are involved when a new functionality is added to an application. Those changes in the existing code should be minimized, since it's assumed that the existing code is already unit tested and changes in already written code might affect the existing functionality. This is valuable for Production environment where the source codes has already been reviewed and tested. Adding the New functionality may causes the problem on existing  code.


Liskov Substitution Principle (LSP)
Basically when we designed a class, we use maintain Class hierarchies. We must make sure that the new derived classes just extend without replacing the functionality of old classes. Otherwise the new classes can produce undesired effects when they are used in existing program modules.
LSV states that if the module using any base class, then the reference to the Base class can be replaced with a Derived class without affecting the functionality of the program module.

Example : - A typical example that violates LSP is a Square class that derives from a Rectangle class, assuming getter and setter methods exist for both width and height. The Square class always assumes that the width is equal with the height. If a Square object is used in a context where a Rectangle is expected, unexpected behavior may occur because the dimensions of a Square cannot (or rather should not) be modified independently. This problem cannot be easily fixed: if we can modify the setter methods in the Square class so that they preserve the Square invariant (i.e. keep the dimensions equal), then these methods will weaken (violate) the postconditions for the Rectangle setters, which state that dimensions can be modified independently. If Square and Rectangle had only getter methods (i.e. they were immutable objects), then no violation of LSP could occur.

Interface Segregation Principle (ISP)
It states avoid tying a client class to a big interface if only a subset of this interface is really needed. Many times you see an interface which has lots of methods. This is a bad design choice since probably a class implementing. . This can make it harder to understand the purpose of a component, but it can also cause increase coupling, where by components that make use of such a component are exposed to more of that components capabilities that are appropriate.
The Interface Segregation Principle (or ISP) aims to tackle this problem by breaking a components interface into functionally separate sub-interfaces. Although a component may still end up with the same set of public members, those members will be separated into separate interfaces such that a calling component can operate on the component by referring only to the interface that concerns the calling component.


Dependency Inversion Principle (DIP)
In an application we have low level classes which implement basic and primary operations and high level classes which encapsulate complex logic and rely on the low level classes. A natural way of implementing such structures would be to write low level classes and once we have them to write the complex high level classes. Since the high level classes are defined in terms of others this seems the logical way to do it. But this is not a flexible design.
High-level modules should not depend on low-level modules. Both should depend on abstractions.Abstractions should not depend on details. Details should depend on abstractions

Monday, June 8, 2015

SQL Agent Job and Job Step History in SQL Server


To generate a comprehensive and descriptive set from the job history the following script can be run in SSMS/QA. It uses the system database msdb and some of the system tables related to jobs and job history.

USE msdb
Go
SELECT j.name JobName,h.step_name StepName, h.step_id,
CONVERT(CHAR(10), CAST(STR(h.run_date,8, 0) AS dateTIME), 111) RunDate,
STUFF(STUFF(RIGHT('000000' + CAST ( h.run_time AS VARCHAR(6 ) ) ,6),5,0,':'),3,0,':') RunTime,
h.run_duration StepDuration,
case h.run_status when 0 then 'failed'
when 1 then 'Succeded'
when 2 then 'Retry'
when 3 then 'Cancelled'
when 4 then 'In Progress'
end as ExecutionStatus,
h.message MessageGenerated
FROM sysjobhistory h inner join sysjobs j
ON j.job_id = h.job_id
Where j.name = 'XXXXXXXXXXX'
ORDER BY h.run_date, h.run_time
Desc
GO

Column Description
[JobName] Name of job as specified
[StepName] Name of step as specified
[RunDate] Date when job run
[RunTime] Time when job run
[StepDuration] Duration in seconds that a step took to complete
[ExecutionStatus] Execution status of step
[MessageGenerated] Message generated at end of step