Jean Paul's Blog

There are 2 types of People in the World, One who Likes SharePoint and..

  • Microsoft MVP

  • MindCracker MVP

  • CodeProject MVP

  • eBook on SharePoint 2010

  • eBook on Design Patterns

  • eBook on Windows Azure

  • NLayers Framework @ CodePlex

  • MSDN Forums

  • .Net vs. Java

    Due to Public Demand

Archive for December, 2010

Reflection Comparer in C#

Posted by JP on December 30, 2010

I would like to share a piece of code that can save good amount of time.

Scenario

You are having a Customer class with properties Ag, Dob, Name which are int, datetime and string respectively.

The Customer objects are stored in a list and for custom sorting them based on different properties, we need to write code by implementing IComparer.  This could be a tedious task if lots of UI screens are there and you need to write specific code for each screen.  The problem is worse if you wanted to sort ascending/descending and based on multiple properties.

image

Solution

You can accomplish the above by using the following class which implements IComparer interface.

image

The above class ‘ReflectionComparer’ has constructor which takes the property on which the object to be sorted.

The constructor takes multiple property names so that we can sort on multiple items.  There is one overloaded constructor too, which takes the SortOrder (Ascending/Descending).

Invoking

You can just call the Sort method of the array/ArrayList and pass the instance of above class to it.

Eg: list.Sort(new ReflectionComparer("Age"));

ReflectionComparer Class Explained

It contains 2 constructors which are explained above.

There is one core method named Compare() which takes arguments x and y.

public int Compare(object x, object y)

For each objects passed – the corresponding CompareTo() method is called using Reflection.

The method GetMethodInfo() returns the “CompareTo” method info object.  Some optimizations were used there to reuse the same CompareTo() MethodInfo object to speed up the sorting process.

The method GetValue() returns the value of property to be compared.  Here also Reflection is the underlying mechanism.

Test Application

The attachment contains the test application which was created in Visual Studio 2008.  The test application provides us the UI to test various scenarios and their corresponding time taken for execution in seconds.

image

Summary

Eventhough Reflection comparison will be slower than normal comparisons, we can judiciously use the code above if the sorting speed is within our expectations.  The idea for the above comparer class is to minimize the coding effort on doing the comparison code infra.   In the above screen shot, 10 thousand records were sorted within 1 second in my computer having 3GHz speed.  Reflection is slower but your computer is many times faster than your requirement – then it is a right choice to use the code above.  Happy Coding.

Source

You can download the source from: www.c-sharpcorner.com rocks!!

Advertisements

Posted in Reflection | Tagged: , , , | Leave a Comment »

Simple invoking order of Constructors

Posted by JP on December 16, 2010

In this article I am trying to show the order in which constructor and destructors are called for a class and its base class.

Importance

It is of great importance that we should know constructors work in an inherited manner – especially in interviews.

This will give us more clarity in creating or destroying objects in constructors/destructors.

Example

We have a class named ChildClass having a constructor and destructor

Also, a class named ParentClass having a constructor and destructor

image

Whenever the constructor or destructor is called it logs a message to the main form.

Implementation

We create an instance of ChildClass and make Garbage Collector to destroy the instance.

Thus we are able to invoke the entire constructors/destructors involved.

new ChildClass();

Result

We are able to see the result like: Even though we are creating the instance of ChildClass the ParentClass constructor is invoked first.

But while on destruction the ChildClass destructor is invoked first.

image

Class: ParentClass

public class ParentClass

{

    public ParentClass()

    {

        MainForm.AddMessage("ParentClass constructor invoked");

    }

 

    ~ParentClass()

    {

        MainForm.AddMessage("ParentClass destructor invoked");

    }

}

Class: ChildClass

 

public class ChildClass : ParentClass

{

    public ChildClass()

    {

        MainForm.AddMessage("ChildClass constructor invoked");

    }

 

    ~ChildClass()

    {

        MainForm.AddMessage("ChildClass destructor invoked");

    }

}

 

Posted in C# | Tagged: , , , | Leave a Comment »

Dynamically extending responsibilities using Decorator Pattern

Posted by JP on December 9, 2010

Definition

“Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to sub classing for extending functionality”

Closed for Modification and Open for Extension

One of the main challenges we face in development is Change. The Closed for Modification and Open for Extension principle says a new functionality can be added by keeping the original code unchanged.

Example:

You have an Album class today which is just blank now. Tomorrow if the customer wants a Christmas tree on that.. What would be our approach?

We will modify the original Album class to incorporate the Christmas tree on it. This should not be the best approach. There is a better approach to this. We can still keep the Album class unchanged and add the Christmas tree to it. Everything happens in the runtime… that is the cool part of it.

Some more examples

We can see real life controls like Form, Button etc. There would be a Form class which having inbuilt functionality. Still the user can use it and add new controls on it / extend the functionality. Here we will be basically deriving from the existing Form/Button class and add new methods or properties to it.

The difference between the above approach and Decorator pattern is that, in the Decorator pattern, we are assigning the responsibility in the runtime.

Conclusion on Change

So basically we can conclude that whenever changes are required, the possible solutions could be:

· Change the original class

· Subclass it and create instance of subclass

· Use Decorator Pattern and still using the original class instance

Here we are going to see how we can use Decorator Pattern to help with the following scenario.

Requirement

The requirement here would be to provide a default Album object and based on dynamic requirement from the user in runtime, we have to draw other pictures to the album.

clip_image002

Design

Our first class would be the Album class which has a Graphics object as parameter.

It contains a Draw() method which is virtual and just clears the graphics object.

public class Album

{

public Graphics Graphics

{

get;

set;

}

public Album()

{

}

public Album(Graphics graphics)

{

Graphics = graphics;

}

public virtual void Draw()

{

Graphics.Clear(Color.White);

}

}

Decorator

We are adding the class named AlbumDecorator which will serve as the base class for all decorators.

public abstract class AlbumDecorator : Album

{

protected Album _album;

public AlbumDecorator(Album album)

{

_album = album;

}

public override void Draw()

{

_album.Draw();

}

}

It takes an Album class as parameter in the constructor.

There are ChristmasTreeDecorator, SantaClausDecorator, StarDecorator deriving from AlbumDecorator:

public class ChristmasTreeDecorator : AlbumDecorator

public class SantaClausDecorator : AlbumDecorator

public class StarDecorator : AlbumDecorator

Each class deriving from AlbumDecorator would be having it’s own picture to draw.

Invoking

In the main form we create an instance of Album class and assigns it to form field _album.

private Album _album;

_album = new Album(_graphics);

_album.Draw();

In the runtime, when user wanted Christmas Tree, instance of ChristmasTreeDecorator is created.

_album = new ChristmasTreeDecorator(_album);

_album.Draw();

In the above code we can see the same _album.Draw() method is called.

How it works

Whenever we call the Draw() method of a decorator class, it in turns calls the original Album.Draw(). After that it will call it’s own Draw() method. In this way we can pass the same album instance to multiple decorators. If there are 10 decorators, all the decorator Draw() methods will be invoked.

You can test this placing a breakpoint inside the StarDecorator Draw() method.

Note

Using decorator we can add dynamic responsibilities to an object in runtime. This provides us the flexibility of creating instance of decorators on need base. This would provide real advantage in scenarios like the additional responsibility instance consists of much memory usage.

Posted in C#, Design Patterns | Tagged: , , | Leave a Comment »

One Line Lambda–Lookup list of Lambda Expressions for common scenarios

Posted by JP on December 7, 2010

I have observed that Lambda Expressions got good steam among developers.  It helps us in reducing lot of code and save time.

I would like to list some of the useful Lambda Expressions here comparing with the without-lambda approach.

Common Setup Code

Here the common initialization code for using the below examples are given:

List<int> list = new List<int>(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10});

Scenario Lambda Approach Traditional Approach
Descending Sort

list.OrderByDescending(i => i);

list.Sort(delegate(int x, int y)

    {

        return y.CompareTo(x);

    });

Check all numbers are less than 100

bool result = list.All(i => i < 100);

bool result = true;

foreach (int i in list)

    if (i >= 100)

        result = false;

Check any numbers are equal to 5

bool result = list.Any(i => i == 5);

bool result = false;

foreach (int i in list)

    if (i == 5)

        result = true;

Get the top 5 items in the list

var sublist = list.Take(3);

var sublist = new List<int>();

for (int i = 0; i < 5; i++)

    if (i < list.Count)

        sublist.Add(i);

Sort descending, get all numbers less than 8, take the top 5

var result = list.OrderByDescending(i => i).Where(i => i < 8).Take(5);

list.Sort(delegate(int x, int y)

{ 

    return y.CompareTo(x); 

});

 

List<int> result = new List<int>();

foreach (int i in list)

    if (i < 8 )

        if (result.Count < 5)

            result.Add(i);

 

Summary

I think the examples above demonstrate, how complex the code will look even if you do the simple sorting and selection.

Surely Lambda Expressions is worth learning and in the long run it would give more manageable code.

Note

In the sorting scenario above, the original list is not updated, OrderBy() will be giving a sorted view of the original list.

For assigning it back to the original list we have to use the ToList<int>() method as:

list = list.OrderByDescending(i => i).ToList<int>();

Posted in C# | Tagged: , , , | Leave a Comment »

One Line Lambda – To select last 3 items in the list and find sum

Posted by JP on December 5, 2010

Here I am trying to show the advantage of Lambda Expression in code reduction and time saving.

Scenario

You have got a list containing 10 items.

1

2

3

4

5

6

7

8

9

10

You need to get the sum of last 3 items in the list.

Normal Approach

In a normal approach, we have to start from the last item in a for loop and decrementing the index variable. 

IList<int> list = new List<int>(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 });

int sum = 0;
for (int i = list.Count – 1; i >= list.Count – 3; i–)
      sum += list[i];

Lambda Approach

The same functionality can be applied in a single line using the inbuilt methods Reverse(), Take() and Sum().

// Single line of code to attain the above task

int sum = list.Reverse().Take(3).Sum();

Code Explained

The method Reverse() reverses the list

The method Take() takes the specified number of items

The method Sum() performs the sum operation

Summary

In the above scenario, Lamba helped us from

  1. Little hectic code of for loop and decrementing index
  2. Reduced the number of lines from 3 to 1
  3. Helped in attaining the functionality in ease

Posted in Lambda Expressions | Tagged: , , , | Leave a Comment »

One Line Lambda – To remove items in a list

Posted by JP on December 5, 2010

I would like to show the advantage of Lambda expressions in time and coding effort saving

Scenario

You are given a list of integers:

1

2

3

4

5

6

2

8

9

2

5

You need to remove the numbers 2 from the list:

The numbers are stored in IList<int> list;

Normal Approach

If you try to remove the object by using a foreach. It will result in the following exception.

IList<int> list = new List<int>(new int[] {1, 2, 3, 4, 5, 6, 2, 8, 9});

foreach (int i in list)

if (i == 2)

list.Remove(i);

Error: Collection was modified; enumeration operation may not execute.

Another Approach

We can employ a while/for loop to achieve the same:

IList<int> list = new List<int>(new int[] {1, 2, 3, 4, 5, 6, 2, 8, 9});

for(int i = 0; i < list.Count; i++)

if (list[i] == 2)

{

list.RemoveAt(i);

i–;

}

The code above works fine. But seeing the lambda approach below you can feel the reduced coding effort.

Lambda Approach

IList<int> list = new List<int>(new int[] {1, 2, 3, 4, 5, 6, 2, 8, 9});

list = list.Where(i => (i != 2)).ToList<int>();

// Here we are selecting the numbers which are not equal to 2 and

// converting the result into a new list

Output

The output of the application will be:

1

3

4

5

6

8

9

Note

Lambda Expressions are really powerful tool, which results in reduced code and saving time. It is really investing at the cost of just 10 minutes learning curve involved.

There are tons of fun code associated with Lambda Expressions awaiting you!!

Posted in Lambda Expressions | Tagged: , , , | Leave a Comment »

For Beginners: In ASP.NET how to show a Javascript Alert message box?

Posted by JP on December 2, 2010

I have seen frequently that beginners in ASP.NET try to use Windows Forms MessageBox and fails.

I would like to say that MessageBox class is meant for Windows Forms Application and not ASP.NET Web applications.

In ASP.NET applications, you have to:

Use either a page to show the message

or

Use javascript alert function to show the message (the example is given below)

Example

Create a new web application using File > New Project > Web > ASP.NET Web Application

image

In the solution Explorer, right click on the Default.aspx and use View Code command.

Replace the Page_Load method code as below:

protected void Page_Load(object sender, EventArgs e)

{

    string message = "Test Message Box in ASP.NET";

    string script = "<script language=’javascript’>alert(‘" + message + "’);</script>";

    ClientScript.RegisterStartupScript(GetType(), "key", script);

}

Now you can execute the application.

Output

On loading the page you will see the following message box (if not enable javascript in your browser)

image

Posted in C# | Tagged: , , | Leave a Comment »

For Beginners: Adding References in Visual Studio

Posted by JP on December 2, 2010

This is a simple post that shows how to add reference to projects in Visual Studio.

Project 1: Run Visual Studio and choose File>New Project>Console Application

image

Project 2: This time from the Solution Explorer choose Add>New Project

image

In the appearing dialog, choose Class Library

Projects

Now in the solution explorer, you can see two projects as shown below.

image

Now we have to refer the ClassLibrary1 project in the ConsoleApplication1.

For this, right click on the References item under ConsoleApplication1 and choose Add Reference.

image

The following dialog will appear.

image

The first tab .NET refers to .Net libraries you can refer to.  They will be residing in the GAC (Global Assembly Cache)

The COM tab refers to the registered COM servers in your machine.

The Projects tab refers to your existing projects in the solution.  It will not show the project from where Add Reference is invoked.

The Browse tab helps us to locate the library by exploring through your machine folders.

The Recent tab remembers your recently added references.  It is easier to locate them.

Projects Tab

Our tab of interest is Projects tab.  Click on the Projects tab and you will be able to see the ClassLibrary1.  Select it and click Ok.

image

That completes adding the reference.

Testing

From the ConsoleApplication1, you can select the Program.cs and type the following.

namespace ConsoleApplication1

{

    class Program

    {

        static void Main(string[] args)

        {

            ClassLibrary1.Class1 class1 = new ClassLibrary1.Class1();

        }

    }

}

If you can build the entire thing, you are done successfully.

Posted in C# | Tagged: , , | Leave a Comment »