Translate

Sunday, December 18, 2011

Predicate C#

What is a Predicate?

The predicate is just a generic delegate that is defined in the .net framework class library. In the framework library, it is defined as


public delegate bool Predicate<T>(T obj);

This delegate is used for searching purposes.


Predicate Example

The FindAll() method in List<T> expects an instance of the predicate as a parameter. In the example below I show you how to do that.

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

namespace PlayLambda
{
    public class Person
    {
        public string name;
        public int Age;

    }

    class Program
    {

        static void Main(string[] args)
        {
            Person P1 = new Person();
            P1.name = "Mike";
            P1.Age = 37;

            Person P2 = new Person();
            P2.name = "Tommy";
            P2.Age = 13;

            Person P3 = new Person();
            P3.name = "Kim";
            P3.Age = 27;



            List<Person> People = new List<Person>();

            People.Add(P1);
            People.Add(P2);
            People.Add(P3);

            Predicate<Person> myPredicate = IsDrinkingAge;

                     //FindAll() expects an instance of the Predicate as a parameter
            foreach (Person p in People.FindAll(myPredicate))
            {
                Console.WriteLine("This person can legally drink: " + p.name);
            }


        }

        static bool IsDrinkingAge(Person p)
        {
            //The signature of this method should match the signature of the predicate
            if (p.Age > 21)
            {
                return true;
            }
            else
            {
                return false;
            }

        }
    }

}
  

Shown below is the output of this program



Wednesday, December 14, 2011

What is LINQ?


Traditionally C# (like C++, java etc) has been an imperative programming language. That means if you want to fetch data from a source or dataset, we have to give the compiler a detailed set of precise instructions. For instance, suppose I have a datatable that has information on all my employees. If I want to find the salary of an employee named John, I would have to write code to loop thru every row in the datatable.
 Now suppose the same table is there in a SQL database. If I need to find the salary of John, all I would do is write something like

Select salary from tblEmployees where firstName='John'

As you can notice, in SQL I don't have to write code to loop through all the rows in the table.  DBMS does the job of looping through for me. This way of coding where you just declare what you want and the job gets done behind the scene by some engine for you, is called declarative programming.

 So what we have learned above can be summed up as

Imperative programming:  :  Give detailed steps to get required data. eg C#,C++ etc
Declarative programming (functional programming)  :  Tell the computer what you need and it will be fetched for you. eg SQL

Clearly, compared to imperative programming,  declarative programming requires a lot lesser code to retrieve data. LINQ is the way to write declarative code in C#.

Type Inference

In C# you can write

var x = "hello";

Since "hello" is a string, x becomes a string at compile time. This is called type inference. (As in, the type of variable x got inferred.)

If you try something like
var x = "hello";
int b = a;

The compiler will throw an error: Cannot implicitly convert type 'int' to 'string'.


Saturday, November 26, 2011

ienumerable tutorial c#


Definitions of IEnumerator and IEnumerable 

If a class implements Ienumerable, then you can run a foreach loop on an instance of that class.

In the .net framework

IEnumerator is defined as 


namespace System.Collections
{   

    public interface IEnumerator
    {        
        object Current { get; }
        bool MoveNext();
        void Reset();
    }
}


IEnumerable is defined as 

namespace System.Collections
{

    public interface IEnumerable
    {        
        IEnumerator GetEnumerator();
    }
}


If you are familiar with SQL, think of IEnumerator as a cursor and IEnumerable as a table.


 Implementation of  IEnumerator and IEnumerable 

using System;
using System.Text;
using System.Collections;
 
namespace ConsoleApplication4
{
 
    class Program
    {
        static void Main(string[] args)
        {
            BookEnumerable books = new BookEnumerable();
            foreach (Book b in books)
            {
                Console.WriteLine(b.title);
            }
 
 
        }
    }
 
    public class Book
    {
        public string title;
        public int cost;
    }
 
    class BookEnumerable : IEnumerable
    {
        IEnumerator er = new BookEnumerator();
 
        public IEnumerator GetEnumerator()
        {
            return er;
        }
    }
 
 
    class BookEnumerator : IEnumerator
    {
 
 
        Book[] books = Utilities.GetBookArray();
 
 
 
        int position = -1;
 
        public object Current
        {
            get
            {
                return books[position];
            }
        }
 
        public bool MoveNext()
        {
 
            position++;
            if (position < books.Length)
            {
                return true;//this means a next item exists
            }
            else
            {
                return false;//this means there are no more items to move further to
            }
        }
 
        public void Reset()
        {
            position = -1;
        }
 
 
    }
 
    public class Utilities
    {
        public static Book[] GetBookArray()
        {
            Book b1 = new Book();
            b1.title = "Code Complete";
            b1.cost = 28;
 
            Book b2 = new Book();
            b2.title = "The Pragmatic Programmer";
            b2.cost = 33;
 
            return new Book[] { b1, b2 };
 
        }
    }
}

Tuesday, November 8, 2011

C# Dependency Injection tutorial (Inversion of Control Tutorial)


Aim of Dependency Injection:

Referring to the image below. Suppose when the console application was initially built, there was no XML or Text File. But later on an XML datasource is added (and a corresponding GetMessageFromXML class). And a few more months down the line a text file datasource. Our aim is write the code in a way that, when a new datasource is added, only the calling datasource from Main method needs to be updated. The code in DisplayMessage Class shouldn't need to change to accommodate a new datasource.






















Bad code without Dependency Injection:

 What I will try to show you here is how in a bad code, changing one part of the code requires changes in other parts of the code. And how after applying dependency injection,  I could make different parts of code, independent of each other.

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

namespace ConsoleApplication1
{


    class Program
    {
        static void Main(string[] args)
        {
            DisplayMessage dm = new DisplayMessage();
            dm.ShowMessage();
        }
    }

    public class DisplayMessage
    {
        GetMessageFromDatabase Gmd;

        public DisplayMessage()
        {
            Gmd = new GetMessageFromDatabase();
        }
        public void ShowMessage()
        {
            Console.WriteLine(Gmd.GetMessage());
            Console.ReadLine();
        }
    }

    public class GetMessageFromDatabase
    {
        public string GetMessage()
        {
            //Pretend this comes from the database
            return "Hi from database";
        }
    }


}



Everything works fine. Suppose 3 months down the line based on the argument passed into the Main method, I have to pull data either from a database or an xml file. To make that happen I add a class GetMessageFromXML to my code. Also I make a slight modification to my Main  method. The code now looks like below.


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

namespace ConsoleApplication1
{


    class Program
    {
        static void Main(string[] args)
        {
            DisplayMessage dm = new DisplayMessage(args[0].ToString());

            dm.ShowMessage();
        }
    }


    public class DisplayMessage
    {
        string source;

        public DisplayMessage(string s)
        {
            source = s;

        }
        public void ShowMessage()
        {
            if (source.ToUpper() == "DATABASE")
            {
                GetMessageFromDatabase Gmd = new GetMessageFromDatabase();
                Console.WriteLine(Gmd.GetMessage());
                Console.ReadLine();
            }
            else if (source.ToUpper() == "XML")
            {
                GetMessageFromXML Gmx = new GetMessageFromXML();
                Console.WriteLine(Gmx.GetMessage());
                Console.ReadLine();
            }
          
        }
    }



    public class GetMessageFromDatabase
    {
        public string GetMessage()
        {
            //Pretend this comes from the database
            return "Hi from database";
        }
    }


    public class GetMessageFromXML
    {
        public string GetMessage()
        {
            //Pretend this comes from an XML file
            return "Hi from XML";
        }
    }


}

Now another 2 months later suppose I also need to read data from a text file based on the input parameter to the main method. What would I do? I would add another class GetMessageFromTextFile . Also I would have to modify the class DisplayMessage

Do you see how dependent the class DisplayMessage is on the implementation (that is depending on where the data is being fetched from) ?  

Inversion of Control attempts to make the class DisplayMessage  and the data fetching classes totally independent of each other. 

Inversion of control is usually achieved by applying dependency injection. There are three popular ways of applying dependency injection  namely
  • Constructor Injection
  • Method Injection
  • Property Injection

Code with Dependency Injection:


In the code below, I have demonstrated inversion of control using constructor injection

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

namespace ConsoleApplication1
{
    public interface IGetData
    {
        string GetMessage();
    }


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

            string source = args[0].ToString();

            if (source.ToUpper() == "DATABASE")
            {
                IG = new GetMessageFromDatabase();
            }
            else if (source.ToUpper() == "XML")
            {
                IG = new GetMessageFromXML();
            }
            else if (source.ToUpper() == "TEXT")
            {
                IG = new GetMessageFromTextFile();
            }
            else
            {
                IG = new GetMessageFromDatabase();//default set to database
            }

            DisplayMessage dm = new DisplayMessage(IG);
            dm.ShowMessage();


        }
    }


    public class DisplayMessage
    {
        IGetData IGLocal;

        public DisplayMessage(IGetData IG)
        {
            IGLocal = IG;

        }
        public void ShowMessage()
        {
            Console.WriteLine(IGLocal.GetMessage());

        }
    }



    public class GetMessageFromDatabase : IGetData
    {
        public string GetMessage()
        {
            //Pretend this comes from the database
            return "Hi from database";
        }
    }


    public class GetMessageFromXML : IGetData
    {
        public string GetMessage()
        {
            //Pretend this comes from an XML file
            return "Hi from XML";
        }
    }

    public class GetMessageFromTextFile : IGetData
    {
        public string GetMessage()
        {
            //Pretend this comes from an Text file
            return "Hi from Text file";
        }
    }
}


Now like you see above, injecting the dependencies through the constructor, I am decoupling DisplayMessage class from the class GetMessageFromDatabase or any other class that the DisplayMessage class might end up utilizing. I can add as many new classes as I want, to fetch data, without modifying the DisplayMessage class, as long as they inherit from the IGetData interface.
So what happened here is that, everything depends on the interface. Which is ideal.


Now you might argue that I actually ended up shifting the dependency to the Main method.  You are absolutely correct. For a console application the main method (or a piece of code called from the main method) is an acceptable composition root (the place where we decide which implementation to use for an interface). The composition root is always located at the startup code of an application. (For web applications that would be global.asax.cs).

In most practical applications you would end up using an Ioc container such as Ninject or Autofac.  These softwares make it possible to inject dependencies (at compile time as well as run time) with much lesser code. Check this for a super simple example of autofac.




Monday, October 31, 2011

Principles of software design


Every software application, whether you apply design patterns or not, you should adhere to the design principles. Applying design principles makes your application robust and easy to maintain. Also design principles must be learned before you can embark on a journey to learn design patterns.  Allow me to introduce you to design principles with the so called SOLID design principles.

S:   Single Responsibility Principle
Like the name suggests, what this means is that every object should be built for one reason only. You should avoid writing multi purpose classes. For example in the .net class library, the string functions are in its own single purpose System.String class and the math functions are in System.Math class. 

O:  Open-Closed Principle
A class should be open for extension and closed for modification. This means once a class has had a stable release, the existing functionality should never be modified. It it however okay to add new functionality.

L:   Liskov Substitution Principle
This principle states that you should be able to use a derived class in place on the parent class and  the derived class should behave the same as its parent class.

I:    Interface Segregation Principle
This principle is tells you to separate interfaces based on their responsibility. Do not have one huge interface for everything. For example imagine the IEnumerable interface also made you implement a lot of methods that you don't need for a foreach loop. Thats obviously an unwanted inconvenience, if all you want is to apply a foreach loop. This is avoided by having only the methods required for a foreach loop as a part of the IEnumerable interface.

D:   Dependency Inversion Principle (or the Inversion of Control Principle )
The Dependency Inversion Principle states when one class uses another class, both the code in both classes can be totally independent of each other and should only depend on interfaces (or abstract classes).
There are three ways to achieve this, namely
  • Constructor Injection
  • Method Injection
  • Property Injection



The  Dependency Inversion Principle is a concept that will take a little more reading to understand. I would strongly recommend checking out these two articles, which explains this concept in a lot more detail.
http://dotnetanalysis.blogspot.com/2012/05/programming-to-interface-in-c.html
http://dotnetanalysis.blogspot.com/2011/11/dependency-inversion-or-inversion-of.html




Sunday, October 30, 2011

C# ?? operator (null coalescing operator)

int? a=null; //int? means a nullabe int. In other words an int variable that can be set to null
int? b;

b = 5;
int? c = a ?? b;//This means pick a if it is not null, else pick b

Console.WriteLine(c);//Displays 5

Saturday, October 22, 2011

Asp.net mvc releases


Release Name
Release Date
Download available at



Asp.net MVC 1
March 2009
Asp.net MVC 2
March 2010
Asp.net MVC 3
Jan 2011