Friday, December 5, 2014

Dynamic query using LINQ

In this article, we will try to understand how we can create a dynamic query in LINQ. In order to do this, we first need to understand the concept of expression trees.
What is Expression tree?

As per MSDN : Expression trees represent code in a tree-like data structure, where each node is an expression, for example, a method call or a binary operation such as x < y
In simple language, an expression tree is a tree data structure, which can be used to represent some executable piece of code, in the form of nodes of this tree. This code is then converted into actual executable code. This kind of property allows you to generate the dynamic linq query. So let's start with the code :
We have the following linq query which returns data of a Customer, based on the CustomerId.
_dbEntities.Customers.Where(cust => cust.CustomerId == 10).FirstOrDefault();
We will now convert this query into dynamic query, by creating an expression tree for it. First, we need to add the namespace System.Linq.Expressions. This class contains various static methods, which we will use to generate the query. These methods include Parameter, Constant, Property etc. We will be using these methods to generate the query, in multiple steps. So let's start
Step 1 : We need to first generate the input parameter which is represented by code on the left of the lamda operator i.e. cust =>. For this, we use the Expression.Parameter method, which will be passed 2 parameters Type and String name. Here
§  Type is the type of entity we are using i.e. Customer entity.
§  String is the any name we use to represent an input to the parameter, which in our case is cust. So our code will be :
ParameterExpression pe = Expression.Parameter(Customer, "cust");
Step 2: Next, we need to use the CustomerId property to make the comparison with a value which is represented by cust.CustomerId in our initial query. So we need to get that property first and we use the Expression.Property method for it. So our code will be:
var _prpToUse = Expression.Property(pe, "CustomerId");
Step 3: Now we need to compare our CustomerId with some value say 10 in our case. So we generate our expression for this using the Expression.Constant method as :
var _cnstToUse = Expression.Constant(10);
Step 4: Next we need to combine the above two expressions, to generate expression cust.CustomerId == 10. For this purpose, we will use the Expression.Equal method. So our code becomes:
var qry = Expression.Equal(_prpToUse, _cnstToUse);
Step 5: Now, we have the expression of the form cust => cust.CustomerId == 10 and need to combine it with the Where extension method, to complete the query. So our following code will pass the above expression to tit, using the MethodCallExpression method.
MethodCallExpression whereExpression = Expression.Call(
typeof(Queryable),
"Where",
new Type[] { lst.ElementType },
lst.Expression,
Expression.Lambda<Func<Customer,bool>>(qry, new ParameterExpression[] { pe }));
Step 6: Finally, we need to execute the query it using CreateQuery method in the provider on which we need to execute the query.
lstData.Provider.CreateQuery<Customer>(whereExpression).FirstOrDefault();
Here, lstData is the list of customers which we have from the database. Execute the code and see the results. It will be the same that we had at the start of the article.
In all the above steps, except step 6, we have created expressions of code that are combined to create an Expression tree, as a whole, which is nothing but the query that we executed at the start of the article.
Below is the generic implementation of the code that we created

So this was about the use of Expression trees to generate the dynamic linq query. Hope you enjoyed reading it.

Monday, December 1, 2014

async and await in C#

Async and Await in C#
In this article we will discuss about the two new keywords that were introduced in C# 5.0, for implementing asynchronous programming. So let's start with some basic their definitions, rules we have to follow to implement it.
await: As per MSDN, await is
The await operator is applied to a task in an asynchronous method to suspend the execution of the method until the awaited task completes. The task represents ongoing work.
This means, if we apply this keyword to a method, and when the control reaches that method, that method will start running in asynchronous mode and the control will move on to the next statement in the program. This is simply done by using the syntax
await Method_Name()
async: Simply adding this keyword will not work. The method in which await is used, must be marked with the async keyword. So if we need to make a method (say Method1Async()) asynchronous ,using await, inside a method named Method2(), we call it using the code as:
function void Method2()
{ 
  await Method1Async();
}
Task: The task or function which is to be made asynchronous, has a return type of the type Task which represents void return type or Task<TResult>, where TResult is the type of data returned by the function. So, for our method above, i.e. Method2, assuming that it returns an integer value, the signature will be of the following type:
function Task<Int32> Method2()
{
    return 1;
}
So this was the basic discussion. Now let's convert the above code into an example. For this, our asynchronous method or Method2, will be something which takes time to complete and returns us an integer value. In our case, we will simply make it sleep using Thread.Sleep and then return an integer value. So it's signature will become like the following:

Next, we create another function inside which we will call this function using await keyword. The reason we are not calling this function in the Main function is that we need to make the parent function as async and Main function cannot be made async. So we have to introduce an intermediate function named Method2(). Next, we simply need to call this function in the Main function. We are also printing different values, which will help us to evaluate and understand the flow of the program in better way.  So our complete code becomes like the following:

Run this code and see the results:

Let's try to understand the flow of the program with the above output.
1. The program execution starts with the execution of the Main function and prints the very first line "Starting the ASYNCHRONOUS process".
2. Next, it moves on to call 
Method1, which in turns Method2. As the Method2 is marked with the await keyword, it starts its execution in an asyncrhonous mode, suspend the further execution of the Method1 and immediately returns to the calling statement in the Main function, without printing the message in the very next line.
3. Then it continues the 
Main function and starts processing the for loop and print the message.
4. Finally when execution of the asynchronous method is completed, it again resumes the execution of the 
Method2 and prints the results, with the return value received from Method2.
So this was about the use of the async and await keywords. Hope you enjoyed reading it...!!!

Friday, November 28, 2014

Tell, don't ask design principle

In this article, we will be discus about a design principle called Tell, Don't Ask. This principle is aimed at designing the classes in such a way that, when they are used, instead of querying their object/instance and performing the operation based on the output it provides, the instance should handle the logic itself.
In other words, it means, the instance of the class should take the decision itself, rather then calling code telling it what to do. So let's discuss with a code sample which violates the principle and than will implement the same using this principle.
Consider the following piece of code. Here, we have the following business logic implemented.

We check for the discount applicable on the vehicle. If it is greater than 5%, we subtract 5000 from the actual price else 3000, as a discount. We also have a net price price defined for the vehicle. After applying the discount, if net price is more than this base price, we can further provide free accessories else we do not.
This type of code will have following issues:
1. If we have same type of logic in other areas of application, changes in the logic will require changes in all the locations.
2. Client code is now aware of the business logic to calculate the cost of the vehicle.
3. Some of the member functions/properties are unnecessarily exposed as public members, to the client code.
This is where we can use the Tell, Don't Ask principle. So we change our code to shift the entire logic into the CostCalculator class and pass the required data to it. It calculates the net price and based on results, it decides whether it further needs to make a call to the ApplyAccessories() method or not. Our code now changes to:

So in this case, the entire calculation logic, along with logic to add accessories, inside the CostCalculator class. We simply provide the required data as input to this class. Further, the ApplyAccessories method is now converted into a private method and client code has no idea of the cost calculation business logic. Client code will simply pass the data to the CostCalculator and rest will be done by its NetCalculation method. In other words, we are telling the CostCalculator instance to perform the calculations, rather than asking anything from it.

Generic classes using generic type parameter in C#

In this article, we will discuss the concept of the generic classes in C#. Before we start, let us try to figure out what exactly does this concept of generics means.
As a .net developer, you will be aware of the data type object, which is the base type of all the data types in the .net framework. We can declare a variable of type object and store any kind of value in it, whether it is a string or integer or any other type. So object data type here acts as a generic type. Similarly, we can specify classes and methods with a generic definition and any type can be specified in place of it when it is being used. In simple language, we can declare a container and use this container for any data type
To start with we will be creating a class type which specifies it to be generic using the following syntax :

Here, we have created a blue print of class, which can be used for any of our data type like integer, string or any custom class. We specify it to be a generic by using the <T> as  type parameter. This is the most important part of the syntax, without which, it would have been a simple class. This i.e. the <T> is also known as generic type parameter.
Now we will be adding a method, which will be again using a parameter of type <T>,  and then we will be using this to illustrate the functionality of generic type.

Here, we have created a method which takes an input parameter of type T, which can be any type that can be specified when we use this class, and adds it to a list which is also of type T. Finally this list is returned by the function created.
So to use this, we will be using the code as :

So here, we have used the generic class to create the integer type of listing. If you try to add any string or any other type of value, it will result in compile time error as we have declared the type of the list to be integer when we first instantiated the class as integer type. Similarly you can use this for the string type or any other type of your choice. Thus, it provides the type safety and checks the type for which it is to be used at the compile time itself.
Some of the built in generic classes that we have in C# include, Stack, LinkedList, Queue etc in the System.Collections.Generic namespace.


Func - generic delegate in C#

In this article, we will discuss about the concept of Func generic delegate. In C# 3.5, a generic delegate was provided with the keyword Func, which acts like a template for the user, to create and delegates. The general signatures of this delegate are  Func<T, TResult>.
Here, T is the input parameter for the method and TResult is the return parameter of the method that will be called using this delegate. This is just a single declaration. You can have the signatures like Func<Int32, Int32, Boolean> or Func<String, Int32, Int32, Boolean>. Here, the last parameter is always the result type and rest of them are the input parameter types of the methods, that can be encapsulated by these delegates.
So let's discuss this with a simple example. We will be creating a delegate which will take two input parameters of type integer, and result a boolean value, which specifies whether the first number is greater then second or not. So our generic delegate signatures will be Func<Int32, Int32, Boolean>. Then we will be creating a function which will be encapsulated by this delegate.
See the code below :

Next, to use this delegate, we will be assigning the method with the same signatures, to this delegate and call the delegate object and pass the required parameters to it. Check out the code below :

So this will return the true or false, based on your input parameters. Similarly, you can declare the delegate with more parameters, of the required type. If you try to go to the definition of this declared delegate, it will display the generic signatures of it, like below. By generic signature, here we mean that depending on the signature of the delegate we declared, its definition is displayed dynamically.

One more interesting point is the use of the anonymous methods or the lambda expression with this delegate. You could have avoided writing the method CheckNumbers, by using the following anonymous or lambda expression declarations.

So next time you need a delegate, go for this one. So this was all about the concept of Func delegate. Happy Coding...!!!