Saturday, 7 September 2013

Abstraction and Encapsulation in C#

What is Encapsulation ?
      Encapsulation is a one of the principle of object oriented programming. The concept of encapsulation is hiding  the Data from the outside world, i.e Hiding the Member, Field, Property from the outside of the class is known as Encapsulation.

     In Real time Example how we can understand that. Let we take Laptop as Example. In Laptop we know how to operate , When pressing the windows key , Start up is launched, But how it is launched is not exposed to the user, here it is encapsulated. Make this process as private from user.

  In C# encapsulation is done by Access Specifier "private" keyword

Example 


    public class Car
    {
        public string Model { set; get; }

        private int EngineSpeed;

        public void Start()
        {
       
        }

        public void Off()
        {
       
        }

        private void EngineProcess()
        {
            EngineSpeed = 170;
        }
    }

    public class Driver
    {
        public void work()
        {
            /* Car class hides the EngineProcess() member and EngineSpeed field from outside the class (Encapsulation)*/
            Car Honda = new Car();
            Honda.Model = "SDF324";
            Honda.Start();
            Honda.Off();
        }
    }



   In the above example , Car class encapsulates the EngineProcess member from outside the class and also EngineSpeed Field is hides from outside the class.

What is Abstraction ?
     Abstraction is also another importance concepts of Object Oriented Programming. Abstraction is Process of Exposing a necessary information and Data to the outside of class. using the access specifiers.

In C# we have different types of access specifier,
1. private
2. public 
3. protected
4. internal
5. protected internal

What is the usage of access specifier ?

Access specifier is used to specify the what type of access can given for method,class,variable,property, event when it is try to invoke from other class , other class which is present in other project. In C# there is various Access Specifiers
1. Public
2. Private
3. Protected
4. Internal
5. Protected Internal

Here Assembly consider as Project in IDE

public

The type or member can be accessed by any other code in the same assembly or another assembly that references it.

private
The type or member can be accessed only by code in the same class or struct.

protected
The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class.

internal
The type or member can be accessed by any code in the same assembly, but not from another assembly.

protected internal
The type or member can be accessed by any code in the assembly in which it is declared, or from within a derived class in another assembly. Access from another assembly must take place within a class declaration that derives from the class in which the protected internal element is declared, and it must take place through an instance of the derived class type.


Wednesday, 4 September 2013

Generic Quick Sorting - C#

In this article we are going to see the Generic Quick Sorting implementation using C#.

Quick Sort :




Quick Sort is a Divide and conquer algorithm, It divides the collection int to two sub sets based on the pivot element selected, one subset is a collection elements which is smaller than pivot, another subset is collection of elements consists of larger than pivot.then each subsets are undergoes following steps again.Entire sort can be done in O(log n)

Steps :
1. Consider a element as Pivot from the List.
2. ReOrder the list so the elements which are lesser than pivot arrange previous in the order of the pivot and     the elements which are higher than pivot arrange next in the order of the pivot.
3. Recursively apply the above steps to each two subsets individually.


Algorithm :

function quicksort('array')
      if length('array')1
          return 'array' 
      for each 'x' in 'array'
          if 'x''pivot' then append 'x' to 'less'
          else append 'x' to 'greater'

      return concatenate(quicksort('less'), list('pivot'), quicksort('greater'))


Now Let we see this implementation in C#

        First Derive a Generic List<T> which is comparable, Then add collection to it ,Add a additional method to it as Order to order a collection based on the Quick Sort by implementing the algorithm. Following type in Generic so any data type can be sorted using this.


class Quicksort<T>:List<T> where T : IComparable
    {
        public List<T> Order()
        {           
            return SortList(this.ToList<T>());
        }

        public  List<T> SortList(List<T> values)
        {
            List<T> _left = new List<T>();
            List<T> _right = new List<T>();

            if (values.Count() > 1)
            {
                T pivot = values[values.Count - 1];
                values.RemoveAt(values.Count - 1);

                foreach (T each in values)
                {
                    if (each.CompareTo(pivot) == 1)
                    {
                        _right.Add(each);
                    }
                    else
                    {
                        _left.Add(each);
                    }
                }
                return MergeList(SortList(_left), pivot, SortList(_right));
            }
            return values;
        }

        private List<T> MergeList(List<T> left, T pivot, List<T> right)
        {
            left.Add(pivot);
            left.AddRange(right);
            return left;
        }

    }


 Now create a Two list one with int type other with string type and order the collection using Quick sort.

class Program
    {
        static void Main(string[] args)
        {
            Quicksort<int> _sorting = new Quicksort<int>();
            _sorting.AddRange(new int[] { 3,1,8,45,2,5,7});
            Console.WriteLine("Ordering the numbers using Quick Sort");
            foreach (int s in _sorting.Order())
            {
                Console.WriteLine(s);
            }

            Quicksort<string> _names = new Quicksort<string>();
            _names.AddRange(new string[]{"Rajesh","Suresh","Pavi","Anna","Ganesh","Sathish","Kani","Hanish","Babu","Dilli"});
            Console.WriteLine();
            Console.WriteLine("Ordering the names using Quick Sort");
            foreach (string s in _names.Order())
            {
                Console.WriteLine(s);
            }
            Console.Read();
        }
    }



Output :




From this article you can learn the Generic Quick Sorting algorithm in C# and the process of algorithm.

Sunday, 1 September 2013

Sql Server - Performance Tips



In this article we are going to see the performance impact of some of the queries in SQL SERVER.

SELECT instead of SET:
   Always prefer to use SELECT keyword instead of SET , to assign a value for variable.Because in select we can assign a value for multiple variable at a time at a single execution. It takes a one value from a result,if it have more than one value in the result set.

Exists instead of Count():
  Always try to use the Exists keyword to check the existence of record, instead of Count(*).Count() needs a full record set to be retrieved

UnionAll instead of Union:
  Always try to use  UnionAll because Union use to return distinct values due to this some internal operations take more time.

Joins instead of SubQuery:
 Try to use Joins instead of subQuery, Because subQuery takes more time to retrieve the records in from table.

Order by :
  Try to avoid order by in Query ,  try to select the data in db and order the data in front end . it takes few second only.If you use order by in Queries. It takes more time to order and takes the data.

Functions :
  Try to avoid the usage of functions in where condition, It takes the more time to execute the function for each and every record.

Dynamic Query:
  Try to avoid the dynamic query, Because at the run time only query framed and executed so the cache is not possible for that query. 

Cursor:
 Try to use While loop instead of using Cursor , because cursor is executed in record by record in sequence.

More Joins :
  Avoid more joins in tables,because this gives very slow performance hit,so try to kept the data in optimized table structure.

Indexes :
  Try to create a indexes for the tables to retrieve the records very fast in SELECT, and Avoid the more non-clustered indexed column in Where clause.

I Hope From this article you can see some of the performance tips in SQL SERVER.



Usage of IComparable and IComparer in c#


                        In this article we are going to see the usage of IComparable and IComparer. For this we are going to create a custom Student Class with three properties Name, Age and Percentage and implement the IComparable<Student>, Which is used to specify the custom class is comparable based on the percentage property in ascending order. 

IComparable


 class Student:IComparable<Student>
    {
        public string Name { set; get; }

        public int Age { set; get; }

        public int  Percentage { set; get; }
      
        public int CompareTo(Student other)
        {
            if (this.Percentage < other.Percentage)
            {
                return -1;
            }
            if (this.Percentage > other.Percentage)
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }

        public override string ToString()
        {
            return string.Format(" Name :"+this.Name+", Age :"+this.Age+", Percentage:"+this.Percentage);
        }
    }


So Let we see where it is uses, By this it indicates the Student class is comparable,While sorting the collection of Student class it takes the CompareTo Method to compare the objects present in collection.
then the collection of student is ordered in Ascending order of Percentage.

IComparer

     Now we see about the IComparer, What is the usage of IComparer it is also to compare the two objects and return the order based on the condition specified in Compare Method.

class StudentComparer:IComparer<Student>
    {

        public int Compare(Student x, Student y)
        {
            if (x.Age < y.Age)
            {
                return -1;
            }
            if (x.Age > y.Age)
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }
    }


Where it is uses ,By this we can specify the comparer externally by creating a new instance of that comparer and pass as parameter to the Sort Method of the collection.In this comparer we are ordering the collection in Ascending order based on the Age of the Student.

Let we see the Example 

 class Program
    {
        static void Main(string[] args)
        {           

            List<Student> studentlist = new List<Student>();
            studentlist.Add(new Student() { Name="Rajesh", Age=23,Percentage=88});
            studentlist.Add(new Student() { Name="Suresh", Age=21,Percentage=93});
            studentlist.Add(new Student() { Name="MeenakshiSundaram",Age=24,Percentage=88});
            studentlist.Add(new Student() { Name="Priyanka",Age=20,Percentage=60});
            studentlist.Add(new Student() { Name="GeorgeWas",Age=38,Percentage=76});
            studentlist.Add(new Student() { Name="Bro",Age=23,Percentage=77});
            studentlist.Add(new Student() { Name="SivaRajan",Age=32,Percentage=76});
            studentlist.Add(new Student() { Name="Amala",Age=26,Percentage=64});
            studentlist.Add(new Student() { Name="Indhumathy",Age=27,Percentage=86});
            studentlist.Add(new Student() { Name="KalaiSelvi",Age=25,Percentage=74});
            studentlist.Add(new Student() { Name="Pavi",Age=16,Percentage=70});
            studentlist.Add(new Student() { Name="Hanish",Age=14,Percentage=94});

            Console.WriteLine("Using IComparable");
            studentlist.Sort();
            foreach (Student stud in studentlist)
            {
                Console.WriteLine(stud.ToString());
            }

            Console.WriteLine("Using IComparer");
            studentlist.Sort(new StudentComparer());
            foreach (Student stud in studentlist)
            {
                Console.WriteLine(stud.ToString());
            }

            Console.Read();
        }

    }

    class StudentComparer:IComparer<Student>
    {

        public int Compare(Student x, Student y)
        {
            if (x.Age < y.Age)
            {
                return -1;
            }
            if (x.Age > y.Age)
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }
    }

    class Student:IComparable<Student>
    {
        public string Name { set; get; }

        public int Age { set; get; }

        public int  Percentage { set; get; }
      
        public int CompareTo(Student other)
        {
            if (this.Percentage < other.Percentage)
            {
                return -1;
            }
            if (this.Percentage > other.Percentage)
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }

        public override string ToString()
        {
            return string.Format(" Name :"+this.Name+", Age :"+this.Age+", Percentage:"+this.Percentage);
        }
    }


Output:

Using IComparable

 Name :Priyanka,             Age :20, Percentage:60
 Name :Amala,                Age :26, Percentage:64
 Name :Pavi,                   Age :16, Percentage:70
 Name :KalaiSelvi,          Age :25, Percentage:74
 Name :SivaRajan,          Age :32, Percentage:76
 Name :GeorgeWas,       Age :38, Percentage:76
 Name :Bro,                   Age :23, Percentage:77
 Name :Indhumathy,       Age :27, Percentage:86
 Name :MeenakshiSundaram, Age :24, Percentage:88
 Name :Rajesh,               Age :23, Percentage:88
 Name :Suresh,               Age :21, Percentage:93
 Name :Hanish,               Age :14, Percentage:94

Using IComparer 

Name :Hanish,                Age :14, Percentage:94
 Name :Pavi,                   Age :16, Percentage:70
 Name :Priyanka,            Age :20, Percentage:60
 Name :Suresh,               Age :21, Percentage:93
 Name :Rajesh,               Age :23, Percentage:88
 Name :Bro,                   Age :23, Percentage:77
 Name :MeenakshiSundaram, Age :24, Percentage:88
 Name :KalaiSelvi,          Age :25, Percentage:74
 Name :Amala,               Age :26, Percentage:64
 Name :Indhumathy,       Age :27, Percentage:86
 Name :SivaRajan,         Age :32, Percentage:76
 Name :GeorgeWas,      Age :38, Percentage:76

  From the output you can see that, Using Sort() method the collection is sorted in ascending order of Percentage. It takes the CompareTo method to compare the data.When Specifying the instance of StudentComparer explicitly it takes the comparer method to sort and sort the collection in ascending order of Age.

I Hope from this article you can learn the usage of two interfaces IComparable and IComparer.