Jean Paul's Blog

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

    Advertisements
  • 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
  • Advertisements

Archive for May, 2011

Lambda Expressions Extension Method 3 – Take()

Posted by Paul 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

Advertisements

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

Lambda Expressions Extension Method 3 – Take()

Posted by Paul 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 Paul 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 2 – Any()

Posted by Paul 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 Paul 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 »

Lambda Expressions Extension Method 1 – All()

Posted by Paul 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 Paul 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 »

Creating a Plugin enabled Application : Part 1 of 2

Posted by Paul on May 4, 2011

 

In this article I am trying to show how to create a plugin enabled application using .Net Reflection. The plugin enabled application loads an associated piece of software during the runtime. There should not be any design time binding for the specified component.

Advantages of Plugins

We can see lots of plugin enabled applications for example Winamp. The plugin enable application provides the following flexibilities:

– Reduced Size in Initial Deployment

– Incrementing the modules as plugins

– Customers can be benefited by choosing Plugin Modules thus reduction in Cost

How Plugins works?

There will be 3 components in a plugin architecture application.

1) Plugin Container

2) Plugin Interface

3) Plugins

The Plugin Container will serve as the host holding all plugins found in runtime.

The Plugin Interface provides as a standard of communication between the Container and Plugins.

The Plugins are the actual piece of software which are located and loaded by the Plugin Container.

Execution

The plugin enabled application executes as depicted in the image below. After the application is executed, it will search for the plugins of associated interfaces. If any plugins found they are instantiated and loaded into the application.

clip_image002

Diving into the Code

I hope we had enough of theories. Now let us focus on how to build the actual code. In our example, we are trying to load plugins which contains forms. There is one Plugin.Core application which will perform as the Plugin Container and n number of plugin dll’s which contains the forms.

Each form found will be having a display name so that we can show it in the toolbar.

Component 1: Plugin Container .exe

This is a Windows Forms Application containing the Main Form to contain the plugins.

Component 2: Plugin. Interface.dll

This would be a Class Library containing the IPlugin interface.

public interface IPlugin

{

string Text { get; }

Form Form { get; }

Color BackColor { get; }

}

There will be a PluginLoader class which basically takes care of finding the plugins in given folder and loading them into the system.

Component 3: BlueForm.Plugin.dll

This will be a Class Library project containing the plugins. The plugins are nothing other than classes which implements the IPlugin interface.

In our project, we are creating a plugin class named BlueFormPlugin which holds a form.

Note

For the time being I have used Windows Forms for plugin example, but we can extend the same idea to ASP.NET, WPF, Windows Mobile applications too.

Summary

In this article the basic components of building a the Plugin based application is explained. In the next part we can see the inner details of how the plugin can be identified and loaded into the application using Reflection.

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

Lambda Expressions with Multiple Parameters

Posted by Paul on May 1, 2011

Lambda Expressions are getting good recognition among developers and it would be nice to have the next level of information regarding it.

Summary

As you know, Lambda Expressions is an anonymous function that can contain expression or statements.  The lambda expression uses the => (goes to) operator.

Example of One Parameter Lambda

var result = list.Where(i => i == 100);
Example of Two Parameter Lambda

var result = list.Where((i, ix) => i == ix);
Code Explained

In the above case the Where() method is having two overloads and we were using the second overloaded method which takes Func<T, T, bool> as argument.

clip_image002
The first argument is the element itself and second would be the index. The value of index will be passed by the caller.

Applications of Index Parameters

It could be of rare applications where we needed the lambda index parameter. I have seen in many interviews they ask scenarios based on it. Some of the scenarios are given below.

Scenario 1

You have got a list of random integers. We need to find the numbers whose value equals to the index. How to achieve this in one line?

Setup Code

The following code can be used for creating the main list.

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

list.Add(0); // Value = Index

list.Add(2);

list.Add(2); // Value = Index

list.Add(1);

list.Add(4); // Value = Index

One Line Lambda Solution

var sublist = list.Where((i, ix) => i == ix);

The Lengthy Solution

var newList = new List<int>();

int jx = 0;

foreach (int j in list)

if (jx++ == j) // Check index and increment index

newList.Add(j);

From the above code we can see without lambda expressions the solution will be taking more than 1 lines.

Result

We can see the associated result of the console application. The source code is attached with the article.

clip_image004

Summary

In this short article, we have seen the advantage of Index parameter in Lambda expressions in reducing the code and increasing the speed of development as well as execution.

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