Saturday, April 16, 2011

Default Extension methods

Shout it kick it on DotNetKicks.com
In this post I am going to discuss about Default extension method(s) which are use full when we query the data form the collection,array or performing operation while code using linq to sql.

In .net framework there are number of extension methods which allows perform function on the the collection. But problem arise when we don't know the collection or array empty or there is no element after we apply filter.

Methods like .First<t>(),.Last<t>(),.Single<t>() always throws exception InvalidOperationException when object collection is empty or if there is no element available after applying filter condition.
List<int> lstInt = new List<int>(new int[] {15,11,20,30});
var data = lstInt.Single(i => i < 10);

Default Methods
To avoid the exception .net framework has default methods like .FirstOrDefault<t>(),.LastOrDefault<t>(),.SingleOrDefault<t>(), which return the default value if there is no element in the collection or array is empty.
List<int> lstInt = new List<int>(new int[] {15,11,20,30});
var data = lstInt.SingleOrDefualt(i => i < 10);
if (data == 0)
{
   Console.WriteLine("No element found");
}
What if I have collection which is empty and apply the default method, it will return Null value.
class Employee
{
        public string Name { get; set; }
        public int Age { get; set; }

        public static void GetEmployee()
        {
            List<Employee> lstEmp = new List<Employee>();
            var lst = lstEmp.SingleOrDefault();
            if (lst == null)
              Console.WriteLine("list is empty");
        }
}

But I want to display the default value if collection is empty. So for the solution .net Framework provided method DefualtIfEmpty() which allow to do so.
class Employee
{
        public string Name { get; set; }
        public int Age { get; set; }

        public static void GetEmployee()
        {
            List<Employee> lstEmp = new List<Employee();
            Employee defualtEmp = new Employee() { Name = "defualt", Age = 0 };
            var lst = lstEmp.DefaultIfEmpty(defualtEmp).Single();
            
            Console.WriteLine("Employee :" + lst.Name);
        }
}
The above method is also help full when I am apply filter on the collection and collection is empty.
public static void GetEmployee()
{
            List<Employee> lstEmp = new List<Employee>{
                                new Employee(){Name = "Pranay",  Age =25 },
                                new Employee(){Name = "Krunal", Age = 26},
                                new Employee(){Name = "Hanika", Age = 26} 
            };

            Employee defualtEmp = new Employee() { Name = "defualt", Age = 0 };

            var emp = lstEmp.Where(e=>e.Age<20).DefaultIfEmpty(defualtEmp);
            foreach(Employee e in emp)
            Console.WriteLine("Fond Employee: " + e.Name);
}
The above code is the example but it's very help full when I am binding collection with the list controls.

Summary 
The default methods palys important role when we do code with the collection or with the linq to sql or linq to xml and we don't know weather collection is emptry or not. You can get detail information about the methods on msdn.

Sunday, April 10, 2011

Overview of the C# version 1.0 to 4.0

Shout it kick it on DotNetKicks.com
In this article I am going to discuss about the some of the changes in C# language from the beginning to up till i.e C#1.0 to C#4.0. I am just sharing my personal experience what the evolution did by C# up till.

This post is just show the evolution in C# programming language. I am not going to show all features of the each version.

One day I and my (Girl Friend)GF went to the Cafe coffee day to drink coffee after completing office. At that day I carried the C# book in my bag, which I took office to explain the newer version to my colleague. She suddenly looked in my bag and which started below conversation.

GF: why do you always carry the C# book which marked with the different version on it?
Me: The C# developer team released around 4 major version of C# language. Every version comes up with some new feature(s) which makes development easy and simple. As well as cause me to do the change the code accordingly.
GF: How that can be possible every version release causes you to change your code?
ME: (on my laptop) ok. I will show what the revolution in language.

C#1.0
Specification of Version 1
Following is code for the Employee class for my system.
public class EmployeeCompare : IComparer
    {
        public int Compare(object x, object y)
        {
            Employee emp1 = (Employee)x;
            Employee emp2 = (Employee)y;
            return emp1.Name.CompareTo(emp2.Name);
        }
    }
Above code is for sorting employee on name property. You can see, I need to convert from general/generic object type into employee first, then i need to compare name property of employee objects

Note here I have implemented IComparer to sort employee.
public class Employee
    {
        string _name;
        public string Name
        {
            get
            {
                return _name;
            }
            set
            {
                _name = value;
            }
        }

        int _id;
        public int ID
        {
            get
            {
                return _id;
            }
        }
Above I have created two properties to store employee name and id, actually here private variable holding value of the property.
One more thing to note here is I have written get block to make ID readonly.
public Employee(int id, string name)
        {
            this._id = id;
            this._name = name;
        }
Below method create the list of the employee and storing it in the ArrayList.
public ArrayList GetEmployee()
        {
            ArrayList al = new ArrayList();
            al.Add(new Employee(1, "pranay"));
            al.Add(new Employee(2, "kruanal"));
            al.Add(new Employee(2, "hanika"));
            return al;
        }
But when I am adding employee object actually I am converting it in the object.
public void displayEmployee()
        {
            ArrayList alEmployee = GetEmployee();
            alEmployee.Sort();
            foreach (Employee emp in alEmployee)
            {
                Console.WriteLine(emp.Name);
            }
        }
    }
Above I am requesting the employee class to display all Employee in sorted order by calling displayEmployee method.
Note here I am converting each object of ArraList in employee to display data.


GF: it’s some what similar to java /c++ class like other programming language.
Me:Now we moving to second version of language which change this class.
GF: let's see.

C#2.0
Specification of Version 2

As you see here now I can created IComparer with the specific Type like employee. This is because of the C#2.0 included new feature called Generic.
public class EmployeeCompare : IComparer<Employee>
    {
        public int Compare(Employee x, Employee y)
        {
            return x.Name.CompareTo(y.Name);
        }
    }
Now to compare two employee object I no need to convert object to employee.
public class Employee
    {
        string _name;
        public string Name
        {
            get
            {
                return _name;
            }
            set
            {
                _name = value;
            }
        }
        int _id;
        public int ID
        {
            get
            {
                return _id;
            }
            private set
            {
                _id = value;
            }
        }
As you can see the properties above I can able to set the the access level to private which make the property readonly.
public Employee(int id, string name)
        {
            this._id = id;
            this._name = name;
        }
In GetEmployee now I can put the Employee objects directly as Employee because of the Generic feature.
public List<Employee> GetEmployee()
        {
            List<Employee> al = new List<Employee>();
            al.Add(new Employee(1, "pranay"));
            al.Add(new Employee(2, "kruanal"));
            al.Add(new Employee(2, "hanika"));
            return al;
        }
As Generic feature make the List typesafe and there is no need of converting object to employee. So to display employee I no need to covert List object to employee again.
public void displayEmployee()
        {
            List<Employee> alEmployee = GetEmployee();
            //alEmployee.Sort();

            alEmployee.Sort(delegate(Employee x, Employee y)
            { return x.Name.CompareTo(y.Name); });

            foreach (Employee emp in alEmployee)
            {
                Console.WriteLine(emp.Name);
            }
        }
    }
As you can there is no need of the comparer to sort the object I can do it easily with the anonymous method feature of the language.

Me: So got something new and change of things.
GF: yeah......it's look like big change and cool.

Me: so we are moving on version three of the language.
GF : go on I like it eager to know what new now in this version.

C#3.0
Specification of Version 3
Now the below code is with the next new version of the language.
public class Employee
    {
        public string Name
        {
            get;
            set;
        }

        public int ID
        {
            get;
            private set;
        }
Well as you can see here there is no need of the private variable to hold the value of the property. This is because the new feature automic property of the language. This is usefull when I don’t have any logic to manipulate with the value.
Employee() { }

        public Employee(int id, string name)
        {
            this.ID = id;
            this.Name = name;
        }
In GetEmployee now I do not need to add the employee object one by one that I can do easily with the object Inialization feature of new version.
public List<Employee> GetEmployee()
        {
            return new List<Employee>
            {
                new Employee{ Name="pranay", ID=1},
                new Employee{ Name="krunal", ID=2},
                new Employee{ Name="hanika", ID=3}
            };
        }
Now displayEmployee method here I do not need to implement IComparare or any anonymous method to sort data I can do it easily with the lamda expression or by using extension method provided by the this version of language.
public void displayEmployee()
        {
            List<Employee> alEmployee = GetEmployee();
            alEmployee.Sort((x,y) => x.Name.CompareTo(y.Name) );
            //alEmployee.OrderBy(e => e.Name);
            foreach (Employee emp in alEmployee)
            {
                Console.WriteLine(emp.Name);
            }
        }
    }

Me:so like this new feature of this version.
GF:yeah...LINQ feature is just awesome. I just liked it much.

Me: Now the latest version of this language. This version is not doing major changes as its did by the previous version because the latest version more towards the dynamic types in language.
GF: Lets see.

C#4.0
Specification of Version 4
public class Employee
    {
        public string Name
        {
            get;
            set;
        }

        public int ID
        {
            get;
            private set;
        }
Now this version allows you to set the default parameter value for the argument in the function which is not possible with the previous version (Optional parameter). So the constructor for the employee looks like as below.
public Employee(string name, int id = 0)
        {
            this.ID = id;
            this.Name = name;
        }
Note by this feature I do not have to create extra overloading methods in my class.
In GetEmployee method I can set the value of variable by specifying name of the parameter of the function.
public List<Employee> GetEmployee()
        {
            return new List<Employee>           {
                new Employee(name : "pranay", id :1 ),
                new Employee(name : "krunal", id :2 ),
                new Employee(name : "hanika", id :3 )
            };
        }

        public void displayEmployee()
        {
            List<Employee> alEmployee = GetEmployee();
            //alEmployee.Sort((x,y) => x.Name.CompareTo(y.Name) );
            alEmployee.OrderBy(e => e.Name);
            foreach (Employee emp in alEmployee)
            {
                Console.WriteLine(emp.Name);
            }
        }
    }
Me: so this version do the changes in the way I declare parameter in the method and the way I pass value to the method when call.
GF: I like this feature of the optional parameter and the way i can assign the value to parameter. This is really awesome each version of C# came up with the new feature and change the things.
GF: I just say woooo.... this means we can spend more time because each new version save your time.

Sunday, April 3, 2011

Dynamic query with Linq

Shout it kick it on DotNetKicks.com
In this post I am going to discuss about building dynamic query with the LINQ. LINQ to SQL allow user to query data from the database without writing sql queries by writing LINQ queries. LINQ represent each table as one entity and where LINQ queries allows to manipulate data in type safe.

But Static LINQ queries not able to meet all our programming needs. A Dynamic LINQ queries is needed when we need to retrieve a set of records based on different search parameters.

For example - An employee search screen or a general purpose report which needs to execute a different SELECT statement based on a different WHERE as well as Sorting column to sort data.

Dynamic query in Sql server

In SQL there is concept of dynamic queries which allow to write and execute dynamic queries easily. In SQL server we use EXECUTE or sp_executesql to execute dynamic query.
For example:
DECLARE @SQLQuery AS NVARCHAR(500)
SET @SQLQuery = 'SELECT * FROM tblEmployees WHERE EmployeeID = + convert(@EmpID as varchar(10))
EXECUTE(@SQLQuery)   
or
DECLARE @SQLQuery AS NVARCHAR(500)
DECLARE @ParameterDefinition AS NVARCHAR(100)
DECLARE @EmpID INT
SET @EmpID =100
SET @SQLQuery = 'SELECT * FROM tblEmployees WHERE EmployeeID = @EmpID'
SET @ParameterDefinition =  '@EmpID INT'
EXECUTE sp_executesql @SQLQuery, @ParameterDefinition, @EmpID
What to do when I am using LINQ ?
There are two way to achieve this thing easily
1. Use Dynamic LINQ libarary
2. Use PredicateBuilder

To understand both of the above library consider the below screen shot
I want to search data by entering in above screen. Note here I may left some field blank and some field filled with value.

Use Dynamic LINQ library
Dynamic LINQ library allows build query which are having varying where clause or orderby. To work with the dynamic LINQ library you need to download and install file in your project.
you get the file from this link : Basic Dynamic LINQ C# Sample

so once you install the file you can build query as we can do in pl-sql query.

Following code demonstrate how to build where dynamically
string strWhere = string.Empty;
        string strOrderBy = string.Empty;

        if (!string.IsNullOrEmpty(txtAddress.Text))
            strWhere = "Address.StartsWith(\"" + txtAddress.Text + "\")";  
        if (!string.IsNullOrEmpty(txtEmpId.Text))
        {
            if(!string.IsNullOrEmpty(strWhere ))
                strWhere = " And ";
            strWhere = "Id = " + txtEmpId.Text;
        }
        if (!string.IsNullOrEmpty(txtDesc.Text))
        {
            if (!string.IsNullOrEmpty(strWhere))
                strWhere = " And ";
            strWhere = "Desc.StartsWith(\"" + txtDesc.Text + "\")";
        }
        if (!string.IsNullOrEmpty(txtName.Text))
        {
            if (!string.IsNullOrEmpty(strWhere))
                strWhere = " And ";
            strWhere = "Name.StartsWith(\"" + txtName.Text + "\")";
        }

        EmployeeDataContext edb = new EmployeeDataContext();
        var emp = edb.Employees.Where(strWhere);
        grdEmployee.DataSource = emp.ToList();
        grdEmployee.DataBind();
In above code I am building strWhere dynamically because there may be some criteria no have value where some has.


Predicate Builder
Predicate builder works same as dynamic linq library but the main difference is its allow to write more type safe queries easily.
You can get the detail about predicate builder form here : Dynamically Composing Expression Predicates
Following code shows how you can use PredicateBuilder easily to create dynamic clause easily.
var predicate = PredicateBuilder.True();

        if(!string.IsNullOrEmpty(txtAddress.Text))
            predicate = predicate.And(e1 => e1.Address.Contains(txtAddress.Text));
        if (!string.IsNullOrEmpty(txtEmpId.Text))
            predicate = predicate.And(e1 => e1.Id == Convert.ToInt32(txtEmpId.Text));
        if (!string.IsNullOrEmpty(txtDesc.Text))
            predicate = predicate.And(e1 => e1.Desc.Contains(txtDesc.Text));
        if (!string.IsNullOrEmpty(txtName.Text))
            predicate = predicate.And(e1 => e1.Name.Contains(txtName.Text));

        EmployeeDataContext edb= new EmployeeDataContext();
        var emp = edb.Employees.Where(predicate);
        grdEmployee.DataSource = emp.ToList();
        grdEmployee.DataBind();
So as you see in above code I had created one PredicateBuilder for AND condition and building where clause same way you can build OR clause by using PredicateBuilder.

Difference between both library
  • Predicatebuilder allows to build TypeSafe dynamic queries.
  • Dynamic LINQ library allows to builder query with the Dynamic ORDER BY clause.
Note : Above difference is based on the experience that I have with both library. If you know more than please comment so that I can include in my list.