C# 3.0 Language Enhancements for LINQ – Part 3 – Expression Trees

14 04 2008

We saw more about Lambda Expression in our Part 1 of this series .Wonder how those were compiled or how those expressions parsed?

To do so, we need to get into Expression Trees!

So what is an Expression Tree?

Expression trees are nothing but those which represent the query itself.

Let us take a simple example.

   1: Func<string, string> function = 
   2:              x => x.Contains("c");

· The compiler constructs a delegate which takes an input parameter of type string and returns a value of type string

But, how about this

   1: Expression<Func<string, string>> expression = 
   2:                             x => x.Contains("c");

· The compiler generates an Expression Tree which we can parse and do something with the data

(This post gives a small introduction to Expression Trees. Expression Trees itself is a big topic but this post will help us go through some of the basics with a simple example)

Say we have a class called Student which has only one property – Name

   1: public class Student
   2: {
   3:     private string name;
   4:  
   5:     public string Name
   6:     {
   7:         get { return name; }
   8:         set { name = value; }
   9:     }
  10: }

And now we have a small function which is going to take an expression as its parameter and return the value for which the expression is queried for.

   1: public static string 
   2:          GetName(Expression<Func<Customer, bool>> predicate)

So, if we pass an expression,

n=>n.Name==”Chakkaradeep”

We need to get back Chakkaradeep , as that’s what we queried. This isn’t a good example, but I would say its good to understand how Expressions are parsed J

Let me show you the function directly now,

   1: public static string GetName(Expression<Func<Student, bool>> predicate)
   2: {
   3:     BinaryExpression binaryExpr = (BinaryExpression)predicate.Body;
   4:  
   5:     MemberExpression leftExpr = (MemberExpression)binaryExpr.Left;
   6:  
   7:     string url = leftExpr.Member.Name;
   8:  
   9:     if (binaryExpr.NodeType == ExpressionType.Equal)
  10:     {
  11:         url += "==";
  12:     }
  13:     else
  14:         throw new NotSupportedException("only = is supported");
  15:  
  16:     ConstantExpression rightValue = (ConstantExpression)binaryExpr.Right;
  17:  
  18:     url += rightValue.Value;
  19:  
  20:     return url;
  21: }

That’s a bit confusing! Whats happening ?

Expression is being parsed :)

Yes, take our expression again,

n=>n.Name==”Chakkaradeep”

Expressions always a Body property. In the above expression, we have a BinaryExpression

n.Name==”Chakkaradeep”

As you might have guessed by now, a BinaryExpression is something that has a binary operator

So lets take the Body and break it into two pieces

image

   1: BinaryExpression binaryExpr = 
   2:       (BinaryExpression)predicate.Body;

Now we have extracted our BinaryExpression body which has a Left property and Right property, as shown above in the diagram.

The Left property will hold n.Name

The Right Property will hold Chakkaradeep

And our Node Type or the Binary operator is == (Equality)

And that’s what we have done,

   1: string url = leftExpr.Member.Name;
   2:  
   3: if (binaryExpr.NodeType == ExpressionType.Equal)
   4: {
   5:     url += "==";
   6: }
   7: else
   8:     throw new NotSupportedException("only = is supported");
   9:  
  10: ConstantExpression rightValue = (ConstantExpression)binaryExpr.Left;
  11:  
  12: url += rightValue.Value;

As now you have the values, you could do anything with them and parse them :)

But yes, it would be more complicated if we have multiple queries coming up, like,

n=>n.Name==”Chakkaradeep” && n.Name==”Chaks”

And our sample will not work for the above query as we havent dealt with it. I leave to the reader to explore more on how to recursively parse Expressions :)

What if we need to manually build Expressions?

You can :)

We just use the technique of how we parsed to build the expression manually.

First, we need to create a ParameterExpression of type Student and also tell that our paramter variable is x

   1: //construct the parameter which is x and it is of type Student
   2: ParameterExpression xParam = 
   3:   Expression.Parameter(typeof(Student), "x");

And now we need to build our BinaryExpression whose Left Property is a MemberExpression which has the Property Name and the Right Property a value

   1: //construct our MemberExpression whose
   2: //left property is x.Name, and
   3: //right property’s value "Chakkaradeep"
   4: Student student = new Student();
   5: student.Name = "Chakkaradeep";
   6: MemberExpression leftExpr = MemberExpression.Property(xParam, "Name");
   7: Expression rightExpr = Expression.Constant(student.Name);
   8: //construct our BinaryExpression which is x.Name=="Chakkaradeep"
   9: BinaryExpression myExpr = MemberExpression.Equal(leftExpr, rightExpr);

All good now to build our Expression. Remember, we haven’t yet built our Expression, but we do have the bits and pieces that we need to build our expression 

image

And now we build our Expression,

   1: //now build our Expression using the parameter and BinaryExpression
   2: //x=>x.Name=="Chakkaradeep"
   3: Expression<Func<Student, bool>> lambdaExpr =
   4:     Expression.Lambda<Func<Student, bool>>
   5:         (
   6:             myExpr,
   7:             new ParameterExpression[] { xParam }
   8:         );

There you go! We build it telling that we have a ParameterExpression of type Student and the parameter is x which is associated with the BinaryExpression

And now you can directly pass this lambdaExpr to our function

GetName(lambdaExpr);

You can download the sample here

Useful Resources

1) Expression Trees

2) Expression Tree Visitor

3) System.Linq.Expressions Namespace





C# 3.0 Language Enhancements for LINQ – Part 2 – var Keyword, Extension Methods and Partial Methods

13 04 2008

The var Keyword

We come across this new keyword called var when we use LINQ, what does this var keyword do?

The var keyword is used to declare and initialize anonymous types

That’s really confusing! – What are these anonymous types?

To understand the var keyword, we need to understand what really anonymous types are, and to understand anonymous types we need to know about var keyword, lol! Both go hand in hand.

Let’s start with an example,

   1: var Student = new { Id = 1234, Name = "Chakkaradeep" };

Now we have an anonymous type which has the properties Id and Name declared and initialized using the var keyword. To illustrate what is happening here,

image

So we can come to a conclusion that the var keyword deduces the data type of an object with the initialization of that object.

Now you can do something like this,

   1: var query =
   2:       from name in names
   3:       select new
   4:       {
   5:             firstPart = name[0],
   6:             lastPart = name.Substring(1, (name.Length - 1))
   7:       };

And then used it this way,

image

But do not consider that var variable is loosely coupled and can change its type! Take an example,

   1: var FullName = "Chakkaradeep Chandran";
   2: FullName = 12;

When you compile the above code, it fails because the object FullName is initialized as a String and we are trying to assign an Integer value to it!

This brings up an important point – var variables must be initialized when they are being declared and that helps the var keyword to deduce its type

The introduction of anonymous types has also led to another change in the way objects and collections are initialized

Say, we have a Class Person

   1: public class Person
   2: {
   3:     public string Name;
   4:     public string Address;
   5:     public int Pincode;
   6: }

If you want to initialize an object of type Person and give default values to those properties, the normal way would be,

   1: Person person = new Person();
   2: person.Name = "Chakkaradeep";
   3: person.Address = "Dunedin";
   4: person.Pincode = 9016;

But now we could directly do this,

   1: Person person = new Person
   2: {
   3:     Name = "Chakkaradeep",
   4:     Address = "Dunedin",
   5:     Pincode = 9016
   6: };

That certainly looks easier and neat!

This doesn’t stop with only Classes; it’s even possible with Collections,

   1: List<string> persons = new List<string>
   2: {
   3:     "Wellington",
   4:     "Dunedin",
   5:     "Invercargill"
   6: };

Extension Methods

The best way to understand Extension Methods is from an example

Let’s take our previous post’s example of filtering names that contains a character. We did something like this,

   1: List<string> FilteredNames =
Utility.FilterNames(names, n => n.Contains('c'));

Wouldn’t it be really nice and useful to provide something like this?

   1: List<string> FilteredNames =
   2:       names.Filter(n => n.Contains('c'));

That’s what Extension Methods allows us to do!

What are we actually doing in our above code block?

- We have “added” a method called Filter to an existing type which is string[] (array of strings)

This has one advantage. It doesn’t require you modify anything in the type string[], we just extend it and add our method

So, how are these done?

Extension Methods are nothing but static methods in a static class that can be called by using instance method syntax

We need to do some changes to our Utilty class to make it ready for Extension Methods. We need to change the class to a static class and include a static method called Filter

   1: namespace LINQEnhancements
   2: {
   3:     public static class Utility
   4:     {
   5:         public static List<string>
   6:            Filter(this string[] names,
   7:                 Func<string, bool> customFilter)
   8:         {
   9:             List<string> NamesList = new List<string>();
  10:
  11:             foreach (string name in names)
  12:             {
  13:                 if (customFilter(name))
  14:                     NamesList.Add(name);
  15:             }
  16:
  17:             return NamesList;
  18:         }
  19:     }
  20: }

And now you can use the way we want it,

   1: List<string> FilteredNames;
   2: FilteredNames = names.Filter(n => n.Contains('c'));

The reason I have shown the Utility class along with namespace is that, if your extension methods are in a different namespace, you have to import that namespace to actually make use of those extension methods

   1: public static List<string>
   2:   Filter(this string[] names,
   3:       Func<string, bool> customFilter)

The above line is where our trick lies. We explicitly tell that Filter is a static method applied on a static variable of type string[] (array of strings)

Where are these used? Remember our Standard Query Operators in LINQ?

   1: IEnumerable<string> query = names
   2:                             .Where(n => n.Equals(matchName))
   3:                             .Select();

Yes, you got it right!

And all these Standard Query Operators are available to use by importing the namespace System.Linq

using System.Linq;

Partial Methods

A partial method has its signature defined in a partial type and its implementation defined in another part of the type. This sounds very similar to Partial Class. Yes, partial methods always reside inside partial classes so that they can be used in another part of the type.

Here is an example,

   1: public partial class MyPartialClass
   2: {
   3:     partial void MyPartialMethod();
   4:
   5:     public void NotPartial()
   6:     {
   7:         Console.WriteLine("Ooops..Not Partial!");
   8:     }
   9:
  10:     public void InvokePartialMethod()
  11:     {
  12:         MyPartialMethod();
  13:     }
  14: }

We have a partial class and a partial method called MyPartialMethod

Now, what happens if we do something like this?

   1: MyPartialClass partialClass = new MyPartialClass();
   2: partialClass.NotPartial();
   3: partialClass.InvokePartialMethod();

We do see that the method NotPartial gets invoked but nothing happens when we call the InvokePartialMethod

Now let us create another declaration for MyPartialClass and implement the partial method MyPartialMethod

   1: partial class MyPartialClass
   2: {
   3:     partial void MyPartialMethod()
   4:     {
   5:         Console.WriteLine("Hey, its a Partial Method!");
   6:     }
   7: }

And now do the same thing,

   1: MyPartialClass partialClass = new MyPartialClass();
   2: partialClass.NotPartial();
   3: partialClass.InvokePartialMethod();

We now see that our partial method too gets called as we have implemented it!

Well, there is lot of arguments going on in the community that why do we need Partial Methods when this can be achieved in many other ways. Partial methods are mostly used in design tools for use with auto-generated code. If you want to make use of those methods, you could write your own implementation and it’s going to be used, else the compiler just doesn’t execute them and moves on.

Partial Methods are heavily used by LINQ-to-SQL designer tools and that’s the reason I wanted to explain about them here.

There are some golden rules that we need to follow if we are writing partial methods,

· Partial method declarations must begin with the contextual keyword partial and the method must return void.

· Partial methods can have ref but not out parameters.

· Partial methods are implicitly private, and therefore they cannot be virtual.

· Partial methods cannot be extern, because the presence of the body determines whether they are defining or implementing.

· Partial methods can have static and unsafe modifiers.

· Partial methods can be generic. Constraints are put on the defining partial method declaration, and may optionally be repeated on the implementing one. Parameter and type parameter names do not have to be the same in the implementing declaration as in the defining one.

· You cannot make a delegate to a partial method.

Useful Resources

1) Standard Query Operators

2) LINQ-to-SQL





C# 3.0 Language Enhancements for LINQ – Part 1

10 04 2008

LINQ is a new feature added to C# 3.0. For an introduction to LINQ, please visit here

So, how are we able to use LINQ seamlessly with C#? Thanks to some of the enhancements that were made to C# for LINQ. They are as follows,

1) Lambda Expressions

2) The var Keyword

3) Extension Methods

4) Partial Methods

5) Expression Trees

This is the start of 3 part series which would be,

· Part 1 – Lambda Expressions

· Part 2 – The var Keyword, Extension Methods and Partial Methods

· Part 3 – Expression Trees

As said above, this post will be explaining about Lambda Expressions

Lambda Expressions

Lambda Expression is an anonymous function that can contain an expression or statement or can also be used to create a delegate.

To understand Lambda Expressions, it is better to first look into,

1) Named Methods

2) Anonymous Methods

Named Methods

With delegates one can create Named Methods, that is, instantiate a named method to a delegate and invoke it

image

Nothing gets explained better without an example; so, let’s get into our sample application

Sample Application

We are going to create a sample application which is going to filter names that contains a character. It’s a very basic and simple example, but it’s really good to explain the things that we want to explore. We would be seeing on how we approach the same concept using Named Methods and Anonymous Methods and then come to Lambda Expressions.

We have a small class called Utility which looks like this,

clip_image004

It has got two static methods and a delegate called CustomFilter with an input parameter as string and bool as return type. So, the idea is to allow the developer or user to write their own custom filter function, but use this Utility to filter. This is done with the help of delegates.

Using Named Methods

So, if we take our Named Method approach, we would end up doing like this,

static void UsingNamedMethods()

{

List<string> FilteredNames =

Utility.FilterNames(names, MyFilter);

foreach (string name in FilteredNames)

Console.WriteLine(name);

}

static bool MyFilter(string name)

{

if (name.Contains(‘c’))

return true;

return false;

}

We have a method called MyFilter which is where we define our custom filter logic and instantiate the delegate CustomFilter with this method using the Utility.FilterNames function

And here is our Utility.FilterNames function

public delegate bool CustomFilter(string name);

public static List<string>

FilterNames(string[] names,CustomFilter customFilter)

{

List<string> NamesList = new List<string>();

foreach(string name in names)

{

if (customFilter(name))

NamesList.Add(name);

}

return NamesList;

}

It’s fairly simple and straight forward. Now we really have something useful which makes use of Named Methods. This sample will help the Customer who is going to use our Utility to write his own Filter and use the generic FilterNames function to filter it.

Look into our filter method which is Myfilter – It’s fairly simple, just checking whether the name contains a character and returns true if so. Do we really need to write a method for this? Why can’t we specify a code block instead and make use of it? Anonymous Methods comes to our rescue!

Anonymous Methods

Anonymous methods can be used to pass a code block to a delegate, using the delegate parameter, and can be used in places where creating a method is really not necessary, like in our example.

Using the Anonymous method, our code changes to,

static void UsingAnonymousMethods()

{

List<string> FilteredNames;

FilteredNames =

Utility.FilterNames(names,

delegate(string name)

{

return (name.Contains(‘c’));

} );

foreach (string name in FilteredNames)

Console.WriteLine(name);

}

So, now we have a code block which checks for a character in the name and it is passed as our CustomFilter delegate

Note that our FilterNames Utility function remains unchanged.

However, Anonymous methods do have one drawback in regard to readability. It’s more verbose and the code block sometimes becomes really hard to read!

So, do we really have anything which is easy to read and also simple to use? – Yes, and Lambda Expressions comes to our rescue!

Revisiting Lambda Expressions

As I said earlier – Lambda Expression is an anonymous function that can contain an expression or statement or can also be used to create a delegate

The structure of a lambda expression looks like this,

(param1,param2..paramN)=>expression

Basically we have some input parameters delimited with comma on the left and a corresponding expression on the right

The simplest lambda expression is,

x=>x

This is nothing but assigning x to x

Moving forward, our sample’s expression to find a character in the name would now become,

n=>n.Contains(‘c’)

How is the type of ‘n’ inferred? Remember our delegate? Here it is again,

public delegate bool CustomFilter(string name);

If you translate in pure English – Here is a delegate called CustomFilter which accepts one input parameter of type string and returns a value of type bool

So, when we actually make use of lambda expressions, this gets inferred and thus our ‘n’ in the above lambda expression gets inferred that it is of type string and has to return bool. But when inferring types is not possible, you could always do,

(string n)=>n.Contains(‘c’)

This would explicitly specify the type of ‘n’

Coming back to our sample application, now with the use of lambda expressions, we could write,

static void UsingLambdaExpressions()

{

List<string> FilteredNames;

FilteredNames = Utility.FilterNames(names, n => n.Contains(‘c’));

foreach (string name in FilteredNames)

Console.WriteLine(name);

}

Note that our FilterNames Utility function still remains unchanged.

Statement Lambdas

Again, revisiting our lambda expression definition – Lambda Expression is an anonymous function that can contain an expression or statement or can also be used to create a delegate

We did see that lambda expression that has an expression. What about a statement?

Statement lambdas look like,

(param1,param2..paramN)=>{ statement; }

The statement body can contain many statements instead of a single expression. Something like,

FilteredNames =

Utility.FilterNames(

names,

n =>{

bool blnVal;

/*… something here …*/

blnVal = n.Contains(‘c’);

return blnVal;

} );

Lambdas with Func<T,TResult> delegates

Again, revisiting our lambda expression definition – Lambda Expression is an anonymous function that can contain an expression or statement or can also be used to create a delegate

We did see that lambda expression that has an expression, a statement. What about the last one which can be used to create a delegate?

With the Func<T,TResult> family of generic delegates, we can use lambda expressions to create a delegate and invoke it.

Before getting into an example, let us explore the Func<T,TResult> family. We currently have,

image

A Simple example would be,

Func<string, bool> SampleFunction = n =>n.Contains(‘c’);

SampleFunction(“Chirstchurch”);

The above code block looks fairly simple and actually we see that we can eliminate Named Methods and Anonymous Methods now and directly make use of lambda expressions!

Coming back to our example, we can now simplify our FilterNames Utility function to something like this,

public static List<string> FilterNamesUsingFuncDelegates

(string[] names,Func<string,bool> customFilter)

{

List<string> NamesList = new List<string>();

foreach (string name in names)

{

if (customFilter(name))

NamesList.Add(name);

}

return NamesList;

}

Yes, you are right; we no need to declare any delegate now and make use of the available function delegates as Predicates!

Predicates were introduced in .NET 2.0 and are defined as (from MSDN),

Represents the method that defines a set of criteria and determines whether the specified object meets those criteria

You can read more about Predicates here

We can come across the same in LINQ when you use Standard Query Operators. If you remember our LINQ example, we have actually seen this,

IEnumerable<string> query = names

.Where(n => n.Equals(matchName))

.Select();

And Where clause syntax is,

clip_image008

You can download the sample application here

Useful Resources

1) Named Methods

2) Anonymous Methods

3) Standard Query Operators





A simple Twitter client to demonstrate BackgroundWorker

5 04 2008

We have always had problems when we want to execute some operation that might take long time in a separate thread and at the same time updating UI components.

With BackgroundWorker class, we can simplify this process and makes it very simple for us to do asynchronous operations.

We initialize the BackgroundWorker and register for their events and run it asynchronously. So, when those events like WorkCompleted, ProgressChanged occurs, you are taken to your callback which is in the thread that started the BackgroundWorker.

BackgroundWorker LoginWorker = new BackgroundWorker();

LoginWorker.DoWork += new DoWorkEventHandler(worker_DoWork);

LoginWorker.RunWorkerCompleted +=new

RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);

LoginWorker.WorkerSupportsCancellation = true;

I have developed a small (very) basic Twitter client to demonstrate the BackgroundWorker class

You can download the sample here





An update to TimePicker control in AvalonsControlLibrary

13 03 2008

I hope many use AvalonsControlLibrary in their WPF projects 8) , if not, do have a look! It has got really very useful WPF Controls – Thanks to Marlon :)

Today I did a small update to the TimePicker control. I added another Property called CurrentlySelectedTime which can be used to get the current time in the TimePicker control in String of format h:m:s and also set the time by giving the time as a String in the format h:m:s

For example,

timePicker.CurrentlySelectedTime = “12:34:56″;

and,

MessageBox.Show(timePicker.CurrentlySelectedTime);

This addition totally came out of my personal need for my Project. So, I am not sure how far it would be useful for you ;). But, the logic is there in the source code now so that you could tame it to the format you want, may be add AM and PM and change to 12 hr format 8)

Marlon will soon update the updated source code at CodePlex, but until then you can download it here





Generic Delegates and Lambda Expressions

19 01 2008

.NET 3.5 now provides Generic Delegates which can be used in place of Anonymous Methods

The Generic delegates always encapsulate a method which can accept 1 or more inputs and return a value. So, currently we have,

1) Func<TResult>

2) Func<T,TResult>

3) Func<T1,T2,TResult>

4) Func<T1,T2,T3,TResult>

5) Func<T1,T2,T3,T4,TResult>

Well enough to cater our needs ;)

Lets take an example

Problem: Given an array of words, and a desired length, return me all the words which satisfy that length

Let me give the solution straight away,

function-delegates.jpg

As you can see we have used the Func<T1,T2,TResult> generic delegate where our first parameter is an array of strings and the second parameter is an integer and third parameter which is the return type is ArrayList

If you look closely, we have also used the Lambda operator too in building the function ;)

Now, let us fire our Reflector and see what is there

reflector-function-delegates.jpg

ah..so this has been transformed into an Anonymous Method and the delegate is nothing but our Func<T1,T2,TResult>

Lets again take a look at how Func<T1,T2,TResult> is declared,

public delegate TResult Func<T1, T2, TResult>(T1 arg1, T2 arg2);

Well, I think that explains it ;)

So, what about directly using Lambda expressions..mmm…like this,

function-delegates-lambda-expressions.jpg

That does reduce our lines of code and the way we interpret things :D . I feel the above method is lot more easier than our generic function delegates. So what does our Reflector say about this,

relector-lambda-expressions.jpg

So what is that CS$<>9__CachedAnonymousMethodDelegate2

My Reflector says it is nothing but,

[CompilerGenerated]

private static
     Func<string, bool> CS$<>9__CachedAnonymousMethodDelegate2;

So, again we are back to our generic delegates 8)

Yes, so as we can see it transforms the lambda expressions into delegates :D

From MSDN,

A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types.

I think that explains our Reflector was indeed correct 8)





Arriving to LINQ

18 01 2008

As everybody know, LINQ is one of the new feature in .NET 3.5 framework

I thought let me take you a small ride on how I arrived in using LINQ :D

I will take you from the common approach and then a step ahead and finally arrive to LINQ

(I am taking very very generic example to showcase this)

Problem : Given a array which has some words, find the words that end with letter “s”

1) Normal old style approach

Normal method would be just to write a function, pass the array of strings and return back our result

ArrayList arrList;
String[] strName = { "this", "is", "at" };

//plain old method
Console.WriteLine("Using plain old method - Calling a function");
arrList=OldMethod(strName);
for(int i=0;i<arrList.Count;i++)
{
    Console.WriteLine("String = {0}",arrList[i]);
}
arrList.Clear();

And our OldMethod function is as follows,

static ArrayList OldMethod(string[] strName)
{
    ArrayList arrList = new System.Collections.ArrayList();

    for (int i = 0; i < strName.Length; i++)
    {
        string name = strName[i];

        if (name.EndsWith("s"))
        {
            arrList.Add(name);
        }
    }

    return arrList;
}

2) Using Delegates

Now, you feel like providing a delegate and we shift to Named methods now

1) We declare a delegate

internal delegate ArrayList MyDelegate(string[] strName);

2) Our function

static ArrayList UsingNamedMethods(string[] strName)
{
    ArrayList arrList = new System.Collections.ArrayList();

    for (int i = 0; i < strName.Length; i++)
    {
        string name = strName[i];

        if (name.EndsWith("s"))
        {
            arrList.Add(name);
        }
    }

    return arrList;
}

3) Assign the function to the delegate object

//using named methods
Console.WriteLine("Using Named Methods - Using Delegates");
MyDelegate MyFunction = UsingNamedMethods;

4) Invoke the delegate

arrList=MyFunction(strName);

5) Display our results

for (int i = 0; i < arrList.Count; i++)
{
    Console.WriteLine("String = {0}", arrList[i]);
}
arrList.Clear();

3) Using Anonymous Methods

Now, we can use Anonymous Methods in C# and overcome some of the complexities that we have in Named Methods. With Anonymous methods, we have access to local variables too.

Again we have a delegate and then use that delegate object to create our anonymous method

internal delegate void AnonymousDelegate();

You can see the change in previous delegate declaration and the one above.As we have access to local variables, we need not pass or return, and manipulate things locally itself. So we don’t create a new method for our delegate.

//using anonymous methods
Console.WriteLine("Using Anonymous Methods - Welcome to C# 3.0");
AnonymousDelegate AnonymousMethod = delegate()
                            {
                                foreach(string s in strName)
                                {
                                    if (s.EndsWith("s"))
                                        arrList.Add(s);
                                }
                            };
AnonymousMethod();
for (int i = 0; i < arrList.Count; i++)
{
    Console.WriteLine("String = {0}", arrList[i]);
}
arrList.Clear();

4) Using Generic Function Delegates

Still, we can eliminate delegate declaration and instantiation with the generic Function delegates that are available

//using generic function delegates
Console.WriteLine("Using Generic Function Delegates");
Func<ArrayList> FunctionGenericDeletgateCall = delegate()
                                        {
                                            foreach (string word in strName)
                                            {
                                                if (word.EndsWith("s"))
                                                    arrList.Add(word);
                                            }

                                            return arrList;
                                        };
arrList=FunctionGenericDeletgateCall();
foreach(string word in arrList)
{
    Console.WriteLine("String = {0}",word);
}
arrList.Clear();

Certainly that doesn’t look that good. So what do we have next?

5) Using Extension Methods

Yes, Extension Methods! This makes life easier for others who start using your framework or API or Program. Extension Methods enables you to add “your own” methods to the existing types. So we will add a method that returns us the words ending with “s” to the data type string[]

First, Extension methods should be always static methods inside a static class. Let us create them

public static class ExtensionMethods
{
    public static ArrayList ContainsMyCharacter(this string[] strName)
    {
        ArrayList arrList = new System.Collections.ArrayList();

        for (int i = 0; i < strName.Length; i++)
        {
            string name = strName[i];

            if (name.EndsWith("s"))
            {
                arrList.Add(name);
            }
        }

        return arrList;
    }

}

Next, we just use it as how you use inbuilt methods;)

//using Extension Methods
Console.WriteLine("Using Extension Methods");
arrList=strName.ContainsMyCharacter();
foreach (string word in arrList)
{
    Console.WriteLine("String = {0}", word);
}
arrList.Clear();

This has made our life easier than our earlier methods :D

6) Using Generic LINQ (System.Linq) with Lamda Expressions

Now we get into the usage of Lambda Expressions and the Generic LINQ. Well, we haven’t still arrived at the most easiest way of programming ;)

We can use System.Linq.Enumerable to make the above process a bit simpler

//using LINQ Generic Methods
Console.WriteLine("Using Generic Linq with Lambda Expressions");
IEnumerable<string> collection=System.Linq.Enumerable.Where(strName, s => s.EndsWith("s"));
foreach (string word in collection)
{
    Console.WriteLine("String = {0}", word);
}

7) Using LINQ with Lambda Expressions

So, how can we make the above process even more simpler? :D

With C# 3.0 and LINQ and Extension Methods, the query operators are implemented as extension methods ;)

Yes, you guessed it right, we can directly query on the variable strName

//using LINQ Lambda Expressions
Console.WriteLine("Finally - Here is LINQ with Lambada expressions without Generic Functions");
collection = strName.Where(s => s.EndsWith("s"));
foreach (string word in collection)
{
    Console.WriteLine("String = {0}", word);
}

8 ) Finally, last but not the least – Using Queries

You can also query instead of directly using the extended query operators methods like Where – the one we used above

//using LINQ Query
Console.WriteLine("Using LINQ Queries");
var query = (from s in strName
              where s.EndsWith("s")
              select s);
foreach (string word in query)
{
    Console.WriteLine("String = {0}", word);
}

If you look into Reflector, the last 3 methods will be interpreted as same. So using any of them would be fine. Only that, using the Generic LINQ as in 6 will result to 7 when compiled, so we could directly use method 7

You can download the source code of the above application here

8)





.NET Source Code (not all, but few) released!

18 01 2008

vs08_v_rgb_web.jpg

Yes, as promised earlier, here comes the .NET Source Code :)

Read here on how to enable source code debugging from the person who made this possible :D

And for a screencast, Daniel Moth has an excellent screencast. Watch it here 

One notable change is in the licensing of the source code which can be read here at Scott Gu’s blog

Here is the excerpt  from the above link,

The .NET Framework source is being released under a read-only reference license. When we announced that we were releasing the source back in October, some people had concerns about the potential impact of their viewing the source. To help clarify and address these concerns, we made a small change to the license to specifically call out that the license does not apply to users developing software for a non-Windows platform that has “the same or substantially the same features or functionality” as the .NET Framework. If the software you are developing is for Windows platforms, you can look at the code, even if that software has “the same or substantially the same features or functionality” as the .NET Framework.

:)





Unit Testing the Database Access Layer

11 01 2008

tdd.png

Its been fun after getting into Test Driven Development :)

What I do is, test each individual components, layers in my project before its being used by other components and layers. So, currently am testing the Database Access Layer (DAL). Testing DAL is more tricky and many people follow different methods.

1) Many follow a Repository Pattern to test the DAL

2) Many use a in-memory database to test the DAL

3) Many use development database to test the DAL

4) Many use live database to test the DAL

So, which is best? – That really depends on your interest. For the Repository Pattern and in-memory database you may need to write a full length code which does similar job as your DAL, and that requires some amount of your development time. Development database means that each developer will have access to a development database in his local machine or network server. This is also good because you test as what would happen in the real time. Live database is same as development database, except that you are in high risk as you are working against the live database!

What I have chosen? – Testing against a development database :D

As I learn more about TDD, I will eventually shift to Repository Pattern

I ran into more problems of implementing the Repository Pattern as my DAL is LINQ-to-SQL and though there were few posts about how to unit-test LINQ-to-SQL layer, It was ending up doing more work for testing!

So, what I did was – I maintained my table data as Lists and passed on to DAL and tested against them.

1) I made my test data ready

private static List<Admin> expectedAdminList;

private void PrepareAdminTestData()
{
    expectedAdminList.Add(new Admin{AdminId = "admin",AdminPwd = "genius"});
}

The data that resides in my list is the data that is already present or in other words, the data which I have put in my development database.

2) So, now running a simple test to get the record count,

[Test]
public void Check_Property_AdminCount()
{
    int nExpected = expectedAdminList.Count;

    AdminContractor adminContract = new AdminContractor();

    int nResult = adminContract.AdminCount;

    Assert.That(nResult, Is.EqualTo(nExpected));
}

Its nothing but, checking against the count of my List ;)

3) What about Insert?

[Test]
public void Check_Method_InsertAdmin()
{
    expectedAdminList.Add(new Admin { AdminId = "chaks", AdminPwd = "chaks123" });

    Admin inputAdmin = expectedAdminList[(expectedAdminList.Count-1)];

    AdminContractor adminContract = new AdminContractor();

    adminContract.InsertAdmin(inputAdmin);

    Admin retAdmin = adminContract.GetAdmin(inputAdmin.AdminId);

    Assert.That(retAdmin.AdminId, Is.EqualTo(inputAdmin.AdminId));

    Assert.That(retAdmin.AdminPwd, Is.EqualTo(inputAdmin.AdminPwd));
}

Add to the list and then insert that new element. And now since your List which is holding the table data temporarily is updated, even the above test to count the number of records also passes, as we test the record count against the list count :)

Update and Delete also hold the similar way – Change the list, send to DAL

You have to keep one thing in mind when Deleting – you have to delete the item from the list too after being successfully removed from the database

Here it is,

[Test]
public void Check_Method_DeleteAdmin()
{
    bool blnExpected = true;
    Admin inputAdmin = expectedAdminList[(expectedAdminList.Count-1)];
    string inputAdminId = inputAdmin.AdminId;

    AdminContractor adminContract = new AdminContractor();

    adminContract.DeleteAdmin(inputAdminId);

    bool blnResult = adminContract.CheckAdminIdAvailability(inputAdminId);

    Assert.That(blnResult, Is.EqualTo(blnExpected));

    expectedAdminList.Remove(inputAdmin);
}

You can see that if the Assert passes,we delete that item from our list.

Remember one thing that if you want to run this test individually (of course we do want it :D ), use the [Setup] attribute (NUnit)

Here are my test results,

<Educator.Tests> (32 tests), [0:03.88] Success
  Educator.Tests.BusinessLogicTests (32 tests), [0:03.88] Success
    AdminContractTest (21 tests), [0:03.71] Success
      Check_AdminContract_Default_Contructor, [0:00.01] Success
      Check_Property_AdminCount, [0:01.99] Success
      Check_Method_GetAllAdmins, [0:00.14] Success
      Check_Method_GetAdmin_By_Id_Parameter, [0:00.32] Success
      Check_Method_GetAdmin_By_Name_Parameter_Exception, [0:00.03] Success
      Check_Method_InsertAdmin, [0:00.23] Success
      Check_Method_InsertAdmin_Exception, [0:00.15] Success
      Check_Method_UpdateAdmin, [0:00.10] Success
      Check_Method_CheckAdminIdAvailability_True, [0:00.01] Success
      Check_Method_CheckAdminIdAvailability_False, [0:00.00] Success
      Check_Method_DeleteAdmin, [0:00.03] Success
      Check_Property_DepartmentCount, [0:00.01] Success
      Check_Method_GetAllDepartments, [0:00.01] Success
      Check_Method_GetDepartment_By_Id_Parameter, [0:00.04] Success
      Check_Method_GetDepartment_By_GUID, [0:00.10] Success
      Check_Method_InsertDepartment, [0:00.04] Success
      Check_Method_InsertDepartment_Exception, [0:00.01] Success
      Check_Method_UpdateDepartment, [0:00.03] Success
      Check_Method_CheckDepartmentIdAvailability_True, [0:00.01] Success
      Check_Method_CheckDepartmentIdAvailability_False, [0:00.01] Success
      Check_Method_DeleteDepartment, [0:00.01] Success
    LoginContractTest (11 tests), [0:00.17] Success
      Check_LoginContractor_Default_Constructor, [0:00.01] Success
      Check_Method_CheckIdAvailability_Return_False, [0:00.03] Success
      Check_Method_CheckIdAvailability_Return_True, [0:00.00] Success
      Check_Property_UserCount, [0:00.00] Success
      Check_Method_GetAllUsers, [0:00.01] Success
      Check_Method_GetUser, [0:00.00] Success
      Check_Mthod_Login_True, [0:00.01] Success
      Check_Mthod_Login_False, [0:00.01] Success
      Check_Method_Register, [0:00.01] Success
      Check_Method_UpdateUser, [0:00.01] Success
      Check_Method_DeleteUser, [0:00.03] Success

I am sure this is not the best way, but it works for now :)





Manually constructing Expressions

9 01 2008

[ Please read Marlon's blog post before reading my post ;) ]

My friend Marlon posted about how to parse Expression given a Lambda expression something like,

x=>x.Name==”Marlon”

But what if you want to construct the above Lambda expression manually :)

Yes, that is 100% possible! You can build your queries manually too :D

Looking again at the query,

x=>x.Name==”Marlon”

We can split into two parts

1) x

2) x.Name==”Marlon”

What do these mean?

1) x is the parameter and is of type Customer

2) The property Name is checked against the string Marlon which is nothing but the property Name’s value

To speak in “LINQ” language,

1) x is a ParameterExpression of type Customer

2) x.Name==”Marlon” is a MemberExpression whose,

a) left expression is the property Name, and

b) right expression is the ConstantExpression of value “Marlon”

There is nothing new here. if you look at how Marlon has parsed the tree, we could easily arrive to the above query construction technique

So, having understood the basics, now let us construct it :)

//construct the parameter which is x and it is of type Customer
ParameterExpression xParam = Expression.Parameter(typeof(Customer), "x");

//construct our MemberExpression whose
//left expression is x.Name, and
//right expression its value "Marlon"
MemberExpression leftExpr = MemberExpression.Property(xParam, "Name");
Expression rightExpr = Expression.Constant(customer.Name);

//construct our BinaryExpression which is x.Name=="Marlon"
BinaryExpression myExpr = MemberExpression.Equal(leftExpr, rightExpr);

//now build our Expression using the parameter and BinaryExpression
//x=>x.Name=="Marlon"
Expression<Func<Customer, bool>> lambdaExpr =
    Expression.Lambda<Func<Customer, bool>>
        (
            myExpr,
            new ParameterExpression[] { xParam }
        );

//call our function and pass our expression which we constructed
customer_url = GetCustsomerUrl(lambdaExpr);

//display the returned value
Console.WriteLine("URL = {0}", customer_url);

Its nothing but parsing the expression tree in reverse :D

You can download the sample here








Follow

Get every new post delivered to your Inbox.