Monday, June 8, 2015

Covariance and Contravariance

Covariance and Contravariance are one of the commonly used concepts OOPS. And it is implemented well by Dot Net framework. Here we will discuss it with the help of C#.

Covariance

An object that is instanciated with more derfive type argument is assigned to an object instanciated with less derived type arguments.


      IEnumerable<string> str = new List<string>();

In the above code snippet an object of a list type is assigned to an more derived type i.e. IEmumerable. This an example of Covariance. 

Contravariance

An object is instenciated with less derived type arguments is assign to object with more derive type argument.


        
      static void SetObject(Object o)
      {
            //some code
      }

      Action<object> obj = SetObject;
      Action<string> obj1 = obj; 


Here in this example a static method is assigned to an Action<object> type delegate. Then again the Action<object> type delegate is assign to an Action<string> type delegate which is quite possible. By this we instenciated an object with less derived type arguments is assign to object with more derive type arguments. This is what Contravariance is.

Happy Coding ... :)

Tuesday, April 21, 2015

Abstract class in C#

Abstract class is one of the most discussed things in C#. But for beginner they always found difficulties to understand it. They quite have a good reasons for that. The main question which every one tries to crumbling is why do we need an abstract class. We have interface to specifies signature. Well' if you are thinking in this direction you are right. Before going deep down to abstract class lets do some basic.

As per MSDN "The abstract keyword enables us to create classes and class members that are incomplete and must be implemented in a derived class". The golden rules of abstract class are 


1. The keyword abstract is used to specify class, method, property, indexer, and event as abstract.

2. If a class is specify as abstract it must be public or internal.

3. If a method, property, indexer, and event is declared as abstract then the class should also be declared as abstract.

4. We cannot create an object of a abstract class. Abstract class can only be inherited.


Example


    public abstract class BasicPay
    {
        public int FixConponent=10000;
        public abstract double GetBasic(int Basic);

        public double GetSalary(int Basic)
        {
            return GetBasic(Basic) + FixConponent;
        }
    }


In this example the class BasicPay is declared as abstract. It has two methods. GetBasic and get GetSalary. Here GetSalary has its body and declaration, because the business logic of behind this method will be same across all sub classes. But GetBasic method is declared as abstract because it will be different on different sub classes. Abstract method can be override in sub classes using override keyword. The below code snippet show how inherit and abstract class.



    public class SalesSalary : BasicPay
    {
        public override double GetBasic(int Basic)
        {
            //do some logic.
            return Basic * 5;
        }
    }
    public class ITSalary : BasicPay
    {
        public override double GetBasic(int Basic)
        {
            //do some logic.
            return Basic * 7;
        }
    }


This example clarify the objective of an abstract class. This is the one and only reason that we need and abstract class over interface. In short we need an abstract class where signatures are different for business logic and also some implementations required for consistency through out the sub classes. Here GetBasic is a signature and has different meaning for different sub classes and GetSalary is consistent across all sub classes.


Complete program


using System;

namespace Tutorials_AbstractClass
{
    //abstract class
    public abstract class BasicPay
    {
        public int FixConponent=10000;
        public abstract double GetBasic(int Basic);

        public double GetSalary(int Basic)
        {
            return GetBasic(Basic) + FixConponent;
        }
    }

    public class SalesSalary : BasicPay
    {
        public override double GetBasic(int Basic)
        {
            //do some logic.
            return Basic * 5;
        }
    }
    public class ITSalary : BasicPay
    {
        public override double GetBasic(int Basic)
        {
            //do some logic.
            return Basic * 7;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // creating object of derived class
            SalesSalary ss= new SalesSalary();
            ITSalary it = new ITSalary();

            Console.Clear();
            Console.WriteLine("Enter basic salary :");
            int BasicSalary = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Salary for IT : {0}",it.GetSalary(BasicSalary));
            Console.WriteLine("Salary for Sales : {0}", ss.GetSalary(BasicSalary));
            Console.ReadLine();
        }
    }
}

Output

Enter basic salary :       
3000                           
Salary for IT : 31000    
Salary for Sales : 25000


Happy Coding...)

Monday, April 20, 2015

Interface in C#

An interface looks like a class, but has no implementation. It can be a member of a namespace or a class and can contain signatures of methods, properties, events or indexers.That's why it is said to be less concrete, more abstract.At the time of execution, the runtime selects an implementation of the interface.

An interface can be created using the keyword interface.

Syntax

<access modifier> interface <interface name> 
{                                                                   
 //declare member                                          
}                                                                   

Access modifier of an interface is public or internal. By default it is internal. Hence if you don't mentioned any access modifier then it is considered as internal. But members of an interface are always public. You need not to prefix any access modifier for them.


    
    public interface IExample
    {
        //member property
        int BasicPay { get; set; }
        //.....

        //member function
        double GrossSalary();
    }

Implementing an interface is itself an art. By choosing the efficient way we can avoid the classic diamond problem. Or we can say C# remove this problem by design different way of interface implementation. There are two ways of implement an interface. Implicit and explicit.

Implicit implementation


    
    public class Example : IExample
    {
        private int _BasicPay;

        public int BasicPay
        {
            get
            {
                return _BasicPay;
            }
            set
            {
                _BasicPay = value;
            }
        }

        public double GrossSalary()
        {
            //some bussiness logic
            return _BasicPay * 4.5;
        }
    }

Explicit implementation

A class that implements an interface can explicitly implement members of that interface. An explicitly implemented member cannot be accessed through a class instance, but only through an instance of the interface.


    public class Example : IExample
    {
        private int _BasicPay;

        int IExample.BasicPay
        {
            get
            {
                return _BasicPay;
            }
            set
            {
                _BasicPay = value;
            }
        }

        double IExample.GrossSalary()
        {
            //some bussiness logic
            return _BasicPay * 4.5;
        }
    }

Complete program

using System;

namespace InterfaceExample
{
    public interface IExample
    {
        //member property
        int BasicPay { get; set; }
        //.....

        //member function
        double GrossSalary();
    }


    public class Example : IExample
    {
        private int _BasicPay;

        int IExample.BasicPay
        {
            get
            {
                return _BasicPay;
            }
            set
            {
                _BasicPay = value;
            }
        }

        double IExample.GrossSalary()
        {
            //some bussiness logic
            return _BasicPay * 4.5;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Console.Clear();
            IExample example = new Example();
            Console.WriteLine("Enter basic salary : ");
            example.BasicPay = Convert.ToInt32(Console.ReadLine());
            Console.WriteLine("Gross salary is : {0}", example.GrossSalary().ToString());
            Console.ReadLine();
        }
    }

}

Output

Enter basic salary :       
112000                        
Gross salary is : 504000


Happy Coding ..:)

Tuesday, April 7, 2015

Install ASP.NET 4.5 into Windows Server 2012

Last week I was working on hosting an ASP.NET site in Windows Server 2012. As this was my first time to work with Windows Server 2012 I faced several hurdles. Somehow I managed to install IIS on it. There are tons of articles online to help me out. I found "http://www.iis.net/learn/get-started/whats-new-in-iis-8/installing-iis-8-on-windows-server-2012" this one was very helpful. Here I am not going to discuss how to install IIS. Hope the above article helps you too.

After installing IIS I configured my site. But it is not running, throwing some handlers error. Oh crap. I need to register ASP.NET into IIS. But irony was that “aspnet_regiis –i” not working. It throws an error.

"'aspnet_regiis' is not recognized as an internal or external command, operable program or batch file."


After couple of hours of searching I found aspnet_regiis is no more supported on Windows Server 2012. Microsoft introduced and new tool called DISM. Deployment Image Servicing and Management.

DISM can deploy services into your operating system from a Windows Image or from internet.

Syntax for DISM (for my purpose)

DISM.exe {/image:<path_to_image> | /online} [dism_options] {servicing_command} [<servicing_argument>]

{/image:<path_to_image> | /online}
This is the first parameter. It gives us an option from where to install the service from and Windows image or from online.


[dism_options]
Second parameter specifies what to do. Ex. enable-feature


{servicing_command}
Tell DISM what to install


My asp.net registration into IIS turned out as

dism /online /enable-feature /featurename:IIS-ASPNET45 /all

Here /all tell DISM to install all dependency of ASPNET45.


 Finally my ASP.NET get installed on Windows Server 2012.

Happy Coding.. :)

Thursday, February 19, 2015

Ranking functions in SQL

Ranking functions are one of the most discussed functions in SQL. It returns ranking value for each row in partition. We have four ranking functions in SQL Server.
  • Row_Number
  • Rank
  • Dense_Rank
  • NTILE

Let us create a table and populate it with some dummy data. It will help to us to understand these ranking function better.


--Create table statement
CREATE TABLE [dbo].[Employee](
 [Id] [int] IDENTITY(1,1) NOT NULL,
 [Name] [varchar](50) NULL,
 [EmpCode] [varchar](10) NULL,
 [Address] [varchar](100) NULL,
 [Salary] [numeric](18, 2) NULL,
 [Dob] [datetime] NULL
) 

--Insert some sample data into employee table
INSERT INTO Employee (Name,EmpCode,Address,Salary,Dob) VALUES
('Mr. A','EC001','New Delhi',60000,'01-01-1983'),
('Mr. B','EC002','Banglore',70000,'01-02-1983'),
('Mr. C','EC003','Pune',70000,'01-03-1983'),
('Mr. D','EC004','Norway',8000000,'01-04-1983'),
('Ms. X','EC005','DC',7000000,'01-05-1983'),
('Ms. Y','EC006','Norwood',6500000,'01-06-1983')



Row_Number

Row_Number returns sequence of numbers over the partition and order them with the column specified in order by block. If there is no partition column specified then it will give a sequence of numbers with respect to order by column specified.


select Row_Number() over(order by Salary) as 'Row Number',
Name,EmpCode,Address,Salary,Dob from Employee

Here we don't have any partition logic. So SQL returns a sequence number from 1 to 6 order by salary.



select Row_Number() over(partition by Address order by Salary) as 'Row Number',
Name,EmpCode,Address,Salary,Dob from Employee



Here for the employee from Norway has sequence number 1 and 2(Highlighted in image). Rest of the employee has only sequence number 1 because they are from different different city.

Rank

Rank gives same rank for each group. The rank of a row is one plus the number of ranks that come before the row.


select Rank() over(order by Address) as 'Row Number',
Name,EmpCode,Address,Salary,Dob from Employee



Dense_Rank

Rank gives same rank for each group, without any gaps in the ranking.


select Dense_Rank() over(order by Address) as 'Row Number',
Name,EmpCode,Address,Salary,Dob from Employee



NTILE

Returns rows in an ordered partition into a specified number of groups.


select NTILE(2) over(partition by Address order by Name) as 'Row Number',
Name,EmpCode,Address,Salary,Dob from Employee


This is all about ranking functions in SQL. I hope this article will help you.
Happy Coding .. :)






 

Monday, February 16, 2015

Singleton Pattern

Singleton is one of the simplest patterns which involved one class and it is responsible for instance itself to make sure it creates only one instance. And Singleton provides a global access point to access that instance. Singleton pattern is very useful when we want create only one instance of a class and used same instance of each call. Best example of Singleton is printer driver class.


There are three main things to implement a Singleton pattern.  
  1. A private constructor. Main objective to have a private constructor is to prevent the class initialization from outside.
  2. A static variable which holds the instance of the class.
  3. A static method which create an instance of the class if the static variable is empty. And return the instance of the class.
 
Below example will explain all about.

using System;

namespace TestSoln
{
    //Singleton implementation
    public class Singleton
    {
        //static variable which holds the instance of the class.
        private static Singleton _instance;

        //private constructor which prevent the class initialization from outside.
        private Singleton() { }

        //creates an instance of the class if the static variable is empty. And return the instance of the class.
        public static Singleton GetInstance()
        {
            if (_instance == null)
                _instance = new Singleton();
            return _instance;
        }

        public void DoSomething()
        {
            Console.WriteLine("I am a Singleton class method");
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("--Start--");

            // calling Singleton class
            Singleton.GetInstance().DoSomething();
            Console.ReadLine();
        }
    }
}




Output:
--Start--                               
I am a Singleton class method