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 May, 2011

Lambda Expressions Extension Methods Series 12 – ToLookup()

Posted by JP on May 26, 2011

The extension methods inside Enumerable.cs includes ToLookup() probably the most unused one. The purpose of the method is to create a lookup list based on key values.

Operates on: IEnumerable

Returns: ILookup<T1, T2>

Please note that the return value is a an interface of ILookup which contains 2 generic arguments. The first generic argument performs as the key and the values will be an IEnumerable of the original type.

Example

The sample list contains strings of various lengths.

private void ToLookupButton_Click(object sender, EventArgs e)

{

IList<string> list = new List<string>();

list.Add(“as”);

list.Add(“is”);

list.Add(“has”);

list.Add(“can”);

list.Add(“this”);

list.Add(“that”);

// Now there are 6 items in the list with length of 2, 3 and 4

ILookup<int, string> lookupList = list.ToLookup(s => s.Length);

// Get the lookup values for length 2

foreach (string value in lookupList[2])

MessageBox.Show(“Lookup Values for Length 2: ” + value);

}

The output of the application would be:

Lookup Values with length 2 are: as, is

Code Explained

From the above code we can see that a list was created with six string items. Then the ToLookup() method is called by passing the length as parameter. The method will return a key value pair where key equals the length and the value an IEnumerable which contains the items corresponding to the key.

Key

Values

2

as

 

is

3

has

can

4

this

 

that

Advanced Example

Now let us take a more real time example where we have a series of Employee objects having Id, Age and Name as the properties. We need to create a lookup list based on their age. The result will be having Age as key and the corresponding Employee objects.

private void ToLookupAdvanced_Click(object sender, EventArgs e)

{

IList<Employee> list = new List<Employee>();

list.Add(new Employee() { Id = 1, Age = 20, Name = “Kavin” });

list.Add(new Employee() { Id = 2, Age = 30, Name = “Alen” });

list.Add(new Employee() { Id = 3, Age = 20, Name = “Suresh” });

list.Add(new Employee() { Id = 4, Age = 30, Name = “Jay” });

list.Add(new Employee() { Id = 5, Age = 20, Name = “Nanda” });

ILookup<int, Employee> lookupList = list.ToLookup(employee => employee.Age);

foreach (Employee employee in lookupList[20])

MessageBox.Show(employee.ToString());

}

The result of the above code will be Employee objects with Age = 20:

1 Kavin

3 Suresh

5 Nanda

The class structure of Employee would be:

public class Employee

{

public int Id;

public double Salary;

public int Age;

public string Name;

public override string ToString()

{

return this.Id.ToString() + ” ” + this.Name;

}

}

Extension Method Snapshot

You can find the snapshot of ToLookup() method usage as provided by Visual Studio.

clip_image002

Advertisements

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

MSDN Forums :: 4000+ Points with 200+ Answers completed

Posted by JP on May 24, 2011

Thank you for visiting this page.  Here I would like to showcase my MSDN Forum contributions in fixing and answering queries.  I have been working on the following categories for past 2 years.

  1. Visual C# General
  2. Visual C# Language
  3. .Net Base Class Library
  4. SharePoint 2010
  5. Windows Forms
  6. Windows Communication Foundation

Please view my MSDN Profile here:

After all it is really fun to be there on the Forums.  You can find lots of programming scenarios which you never encountered and resolving them will make us learn more and sharpen the skills.  Plus on the other side our dearest friend will be happy about getting the problem resolved.

So that’s the reason I kept my forum caption as – “Resolving n Evolving!”

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

MindCracker MVP Awards 2010, 2011, 2012

Posted by JP on May 24, 2011

It was my pleasure to get the MindCracker MVP Award consecutively for 3 years.  The award was given for my contribution towards Articles and Forums in c-sharpcorner.com – a great site for .Net resources.

You can see the awards here:

  1. MindCracker MVP 2011

  2. MindCracker MVP 2010

I would like to thank all the supporters who encouraged me in posting articles and so..  I would like to thank the site leaders Mahesh Chand and Praveen Kumar for providing me this great platform.  Plus thanking my friend Dhananjay Kumar for guiding me to learn the ropes.

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

Getting Familiar with the Type releated Extenstion Methods – Select(), Cast(), OfType()

Posted by JP on May 14, 2011

The class Enumerables.cs provides various extension methods for the built-in classes like IList, ArrayList, IEnumerable etc. Among these the above 3 methods are dealing with type of the underlying element. Let us see what each can be the purpose of.

Method1: Select()

This method is used to convert one type to another. Please note that we are manually creating the instance of the new type here.

Example: We have got a list of integers 1, 2, 3, 4 and 5. We need to convert them into a class containing properties Value and Index.

private void SelectButton_Click(object sender, EventArgs e)

{

// List is holding int values

IList<int> list = new List<int>();

list.Add(1);

list.Add(2);

list.Add(3);

list.Add(4);

list.Add(5);

// Convert them to class ValueIndex

var result = list.Select((v, i) => new ValueIndex() { Value = v, Index = i });

// Display

lbx.Items.Clear();

foreach (ValueIndex vi in result)

lbx.Items.Add(vi.ToString());

}

On execution we can see that the int values got converted into class named ValueIndex:

clip_image002

Method2: Cast()

This is a tricky method. It is used to convert a type in a non-generic list to a typed IEnumerable. We can use this to convert the T objects in an ArrayList to typed IEnumerable<T>.

Note: The method throws InvalidCastException if the casting cannot be supported. An int to long casting will throw exception. But if the classes have an inheritance hierarchy the type casting is possible. We can convert a Manager elements to Employee if the former inherits from the latter.

Example: We have got an ArrayList of object s of type Car. Eventhough it is of type Car we cannot access it as type Car and we need to do conversion. The following code operates on the non-generic ArrayList and returns an IEnumerable<Car>.

private void CastButton_Click(object sender, EventArgs e)

{

// Non-generic list

ArrayList arrayList = new ArrayList();

arrayList.Add(new Car() { Name = “BMW” });

arrayList.Add(new Car() { Name = “Jaguar” });

arrayList.Add(new Car() { Name = “Nissan” });

// Convert the non-generic list into a generic IEnumerable

IEnumerable<Car> result = arrayList.Cast<Car>();

// Now we can work on the properties

IEnumerable<Car> bmwResult = result.Where(c => c.Name == “BMW”);

// Display

lbx.Items.Clear();

foreach (Car car in bmwResult)

lbx.Items.Add(car);

}

On execution, the above code converts the non-generic list items into IEnumerable<Car> and uses the Where() method to filter by car named BMW. The result is shown below:

clip_image004

Method3: OfType()

This method can be used to filter the result based on specific type.

Example: You have got a list of unrelated objects. In this example we are taking the current demo form as the container of different UI Elements. The form.Controls property contains buttons and listbox. We need to select only the Button classes and change the back color. This can be accomplished using the OfType() method.

private void OfTypeButton_Click(object sender, EventArgs e)

{

// Get the Button controls only

var buttonList = this.Controls.OfType<Button>();

// Change BackColor

foreach (Button button in buttonList)

button.BackColor = Color.YellowGreen;

}

On execution we can see that the current buttons on the form are selected and the backcolor is changed.

clip_image006

Note

The above mentioned methods are residing in the class Enumerables of .Net framework. The methods are available to the IList, ArrayList classes through the extension methods mechanism.

Summary

In this article I have tried to portray the usage of 3 Extension Methods. Using Select() extension method we can convert types, using Cast() we can work on a non-generic list to get an IEnumerable, using OfType() we can access the objects of particular type.

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

Lambda Expressions Extension Method 5 – Skip()

Posted by JP on May 14, 2011

Skip() Extension Method

The Skip() is a simple method that skips the first n elements in the enumerable.

It is similar to Take() method in the sense, Take() will return the first n elements, but Skip() will skip the first n elements. (n is the count of elements)

Parameters: Integer specifying Number of Elements to be skipped

Return Value: List of Items

Example

In the following example we are using a list of integers and the Skip() method to select the top n numbers from the list.

private IList<int> _list = new List<int>();

public InitializeList()

{

// Set data

_list.Add(1);

_list.Add(2);

_list.Add(3);

_list.Add(4);

_list.Add(5);

_list.Add(6);

}

private void SkipButton_Click(object sender, EventArgs e)

{

/// Skip method to get a sublist by skipping the first n elements

var result = _list.Skip(3);

foreach (int i in result)

MessageBox.Show(i.ToString());

}

Input

1

2

3

4

5

6

Output

4

5

6

Extension Method Snapshot

You can find the snapshot of the Skip() method usage as provided by Visual Studio.

clip_image002

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

Lambda Expressions Extension Method 4 – TakeWhile()

Posted by JP on May 14, 2011

TakeWhile()

The method TakeWhile() is a tricky method. It will take a condition as parameter and it will return the elements until the condition is true and exists the iteration.

It is not similar to Where() condition. Let me take an example. We have 1, 2, 3, 4, 5, 6 in the list and given a condition TakeWhile(i => I != 2) it will return just 1. The method works like below:

It will go through element 1 and as it satisfies the condition it will be yield returned.

On the second element 2 the condition is false and it will exits.

There is no processing for element 3.

Arguments: Condition

Return Value: List of Items

Example

In the following example we are using a list of integers and the Take() method to select the top n numbers from the list.

private IList<int> _list = new List<int>();

public InitializeList()

{

// Set data

_list.Add(1);

_list.Add(2);

_list.Add(3);

_list.Add(4);

_list.Add(5);

_list.Add(6);

}

private void TakeWhileButton_Click(object sender, EventArgs e)

{

/// TakeWhile method to get a sublist based on condition

var result = _list.TakeWhile(i => i != 2);

foreach (int i in result)

MessageBox.Show(i.ToString());

}

Extension Method Snapshot

You can find the snapshot of the TakeWhile() method usage as provided by Visual Studio

clip_image002

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

Lambda Expressions Extension Method 3 – Take()

Posted by JP on May 14, 2011

The Enumerable.cs class in .Net framework provides n number of useful methods. Let us see each methods one by one.

Take()

The method Take() can be used to get the specified number of top items from the enumerable instance.

Arguments: integer specifying number of items to be selected from the top

Return Value: List of Items

Example

In the following example we are using a list of integers and the Take() method to select the top n numbers from the list.

private IList<int> _list = new List<int>();

public InitializeList()

{

// Set data

_list.Add(1);

_list.Add(2);

_list.Add(3);

_list.Add(4);

_list.Add(5);

_list.Add(6);

}

private void TakeButton_Click(object sender, EventArgs e)

{

/// Take method to get a sublist

var result = _list.Take(3);

foreach (int i in result)

MessageBox.Show(i.ToString());

}

Extension Method Snapshot

You can find the snapshot of the Take() method usage as provided by Visual Studio

clip_image002

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

Lambda Expressions Extension Method 2 – Any()

Posted by JP on May 14, 2011

The Enumerable.cs class in .Net framework provides n number of useful methods. Let us see each methods one by one.

Any()

The method Any() can be used to test whether any elements in the collection satisfies a particular condition.

Please remember that the previous All() method ensures all the elements satisfy the condition, but the Any() method ensures just any of the elements satisfies the condition.

Return Value: Boolean

Example

In the following example we are using a list of integers and the Any () method is used to validate whether any of the elements are equal to 5.

private IList<int> _list = new List<int>();

public InitializeList()

{

// Set data

_list.Add(1);

_list.Add(2);

_list.Add(3);

_list.Add(4);

_list.Add(5);

_list.Add(6);

}

private void AnyButton_Click(object sender, EventArgs e)

{

/// Any method to ensure atleast one elements == 5

var result = _list.Any(i => i == 5);

MessageBox.Show(“Elements == 5: ” + result.ToString());

}

Extension Method Snapshot

You can find the snapshot of the Any() method usage as provided by Visual Studio

clip_image002

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

Lambda Expressions Extension Method 1 – All()

Posted by JP on May 14, 2011

The Enumerable.cs class in .Net framework provides n number of useful methods. Let us see each methods one by one.

All()

The method All() can be used to test whether all elements in the collection satisfies a particular condition.

Return Value: Boolean

Example

In the following example we are using a list of integers and the All() method is used to validate whether all elements are greater than 0.

private IList<int> _list = new List<int>();

public InitializeList()

{

// Set data

_list.Add(1);

_list.Add(2);

_list.Add(3);

_list.Add(4);

_list.Add(5);

_list.Add(6);

}

private void AllButton_Click(object sender, EventArgs e)

{

/// All method to ensure all elements are > 0

var result = _list.All(i => i > 0);

MessageBox.Show(“Elements are > 0: ” + result.ToString());

}

Extension Method Snapshot

You can find the snapshot of the All() method usage as provided by Visual Studio

clip_image002

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

Creating a Plugin enabled Application : Part 2 of 2

Posted by JP on May 4, 2011

This article is a continuation of the article Creating a Plugin enabled Application : Part 1 of 2. The code samples would be the same. In the previous article we have seen how to create the Plugin Container, Plugin Interface and the actual Plugin modules. Here I am going to explain how the plugin modules are written and how they are loaded into the application.

The 3 Components

1) Plugin Container

2) Plugin Interface

3) Plugin

Steps Involved

1. The Plugin.Container application is executed

2. The MainForm inside it calls the PluginLoader class – LoadPlugins() method

3. The LoadPlugins() method searches the given folder for any files with *Plugin.dll in name and loads the Assembly

4. The Assembly loaded will be searched for public types implementing interface IPlugin

5. The classes which implements IPlugin will be instantiated and returned to the caller as IList

6. The MainForm calls the plugin.Text property to display the caption in form as a button

7. On click of the button the form is instantiated using plugin.Formproperty

Class Diagram

clip_image002

The IPlugin interface shown above contains 3 properties.

· BackColor – Just a color for the form and button

· Form – The actual plugin form

· Text – The text description of the plugin form

The PluginLoader class contains only one method LoadPlugins which searches and loads the plugins.

The Solution Explorer with all the projects will look like below:

clip_image004

LoadPlugins()Explained

.Net Reflection is used to load the plugin files. The body of the LoadPlugins() method is given below:

public IList<IPlugin> LoadPlugins(string folder)

{

IList<IPlugin> plugins = new List<IPlugin>();

// Get files in folder

string[] files = Directory.GetFiles(folder, “*Plugin.dll”);

foreach (string file in files)

{

Assembly assembly = Assembly.LoadFile(file);

var types = assembly.GetExportedTypes();

foreach (Type type in types)

if (type.GetInterfaces().Contains(typeof(IPlugin)))

{

object instance = Activator.CreateInstance(type);

plugins.Add(instance as IPlugin);

}

}

return plugins;

}

The method will accept a folder path as argument . The Directory.GetFiles() method searches on the folder and returns all files with *Plugin.dll in the file name.

The files array will be used in the foreach loop above, and each file item will be used to load the Assembly. The method Assembly.LoadFile() is used for it.

Once loaded as Assembly we can get all the public types inside the assembly using the method GetExportedTypes(). This method will return all the public types inside the assembly. Iterating through each type (or class) we can find the classes which implements the IPlugin interface.

For the classes which implement IPlugin, we instantiate the class and added to the plugins list. The Activator.CreateInstance() method is used to create the instance dynamically. This method on completion of all plugin files check, returns the list of Plugin objects.

MainForm calling LoadPlugins()

The MainForm calls the LoadPlugins() in the Form_Load event. The code is given below.

private void MainForm_Load(object sender, EventArgs e)

{

string path = GetExecutionFolder();

var plugins = _pluginLoader.LoadPlugins(path);

if (plugins.Count == 0)

MessageBox.Show(“No Plugins found!”);

else

{

foreach (IPlugin plugin in plugins)

{

Button button = new Button() { Width = 200, Height = 40, Left = 2, Top = PluginsPanel.Controls.Count * 40};

button.Text = plugin.Text;

button.BackColor = plugin.BackColor;

button.Tag = plugin;

button.Click += new EventHandler(button_Click);

PluginsPanel.Controls.Add(button);

}

}

}

If no plugins are found a message box is shown. If plugins found, each plugin instance will be iterated and a button is created to represent the plugin. The button is given backcolor based on the plugin.BackColor property. The button’s tag will be setted with the plugin instance for future use.

The button created will be having a Click event which is described below.

void button_Click(object sender, EventArgs e)

{

IPlugin plugin = (sender as Button).Tag as IPlugin;

plugin.Form.Show();

}

From the button click method above, we can see the tag property of button is used to get the exact Plugin instance and the plugin.Form.Show() method is called.

Adding a New Plugin

For creating a new plugin the following steps are needed.

1) Create a new project with name ending with *Plugin.dll. For time being I am using a project named GreenForm.Plugin class library project. Make sure you add reference to System.Windows.Forms and System.Drawing and Plugin.Interface project.

2) Add a class named GreenFormPlugin implementing interface IPlugin. The code will look like below.

namespace GreenForm.Plugin

{

public class GreenFormPlugin : IPlugin

{

public string Text

{

get { return “A Green Form”; }

}

public Form Form

{

get

{

return new Form() { Text = this.Text,

BackColor = Color.Green };

}

}

public Color BackColor

{

get { return Color.Green; }

}

}

}

3) Build the project and copy the Green.Plugin.dll to bin\debug folder of the Plugin.Container project.

4) Run the Plugin.Container.exe from the same folder and you should see the button listed there

clip_image006

Note

In the current example, we are loading plugin by directly parsing the application folder. In real world applications, we should be able to locate plugins in different folder. A configuration file with various plugin locations could be apt for this case.

Summary

In this article we have discussed the implementation part of Plugin loader works as well as adding a new plugin. For real business applications we can reduce the deployment package size by including only the required plugin files chosen by customer. Still the customer has the flexibility to choose additional plugins and we need to only deploy the needed file.

You can download the application from c-sharpcorner.com:

http://www.c-sharpcorner.com/uploadfile/40e97e/creating-a-plugin-enabled-application-part-2-of-2/

Posted in C# | Tagged: , , , , | 11 Comments »