Archive for the ‘Dotnet basics’ Category

Managed Extensible Framework

Posted: September 4, 2011 in Dotnet basics

Introduction to MEF

What is MEF?

MEF stands for Managed Extensible Framework. It is part of Dotnet 4.0 and is useful for building extensible applications. It can be used to plug-in components to already existing application. It is useful as it decouples the components and also it has mechanism to discover components and thus avoid dependencies. MEF enables developers to create extensions dynamically, without the extending application or the extension requiring any specific knowledge of the other

Basic of MEF :

  • Composition : This is the process of assembling of several different objects into one.
  •  ComposableParts : The key building blocks of MEF. ComposableParts enable applications to expose and consume component extensions via Exports and Imports.
  • Contracts : The avenue for communication between Export and Import components. A Contractis normally implemented via an Interface class.
  • Import and Export : Import and Export attributes can be thought of in the same aspect as a supplier and consumer respectively. Export components supply some value; Import components consume that value.
  • ImportMany :  It loads all the components that match the given contract as a collection.
  • Composition Container – Core of MEF. In order to discover the parts available to it, the composition containers makes use of a catalog
  • Catalog : A catalog is an object that makes available parts discovered from some source. MEF provides catalogs to discover parts from a provided type, an assembly, or a directory.

 

Different types of Catalog are :

  • Assembly Catalog: Discovers the different parts on a specific assembly.
  • Directory Catalog: Discovers parts inside the assemblies on a specific directory.
  • Aggregate Catalog: Allows use more than one catalog combining them.
  • Type Catalog: Looks inside the assemblies for specific types.

Why MEF :

  • Loosely coupled architecture – no need to add dependencies but you can directly use Composition using interfaces for mapping Exports and Imports
  • Provides a way for building pluggable components which can be discovered at runtime and so need to recompilation
  • MEF allows tagging extensions with additonal metadata which facilitates rich querying and filtering

Where is MEF available :

It is available as part of .Net 4.0 as well as it is available in Codeplex.

This is just an introduction to MEF, basic terminologies used and how it is useful. I will come up with a follow up article which has some samples very soon.

Advertisements

Introduction to Exception Handling Block
Application blocks are Microsoft recommended patterns and practices which address some of the most common scenarios like logging, caching, exception handling, dependency injection and so on. All the application blocks are bundled together under an umbrella called as the Microsoft Enterpise Library. The current version of Enterprise Library is 5.0 (http://msdn.microsoft.com/en-us/library/ff648951.aspx).
Why use Enterprise Library ?
1. Address most common scenarios
2. Can be added to any application easily
3. It is collection of reusable components and best practices
4. Is configuration driven
5. They can be easily extended
I wil focus on Exception Handling Block in this article.
Steps to include Exception Handling Block :
1. Download Enterprise Library 5.0
2. Add reference to the following dlls :
Microsoft.Practices.EnterpriseLibrary.Common and Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.

3. Within your class, include namespaces :

using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;

4. Then, policies need to be defined for your application
Policies may be like whether you want to rethrow exception or throw new exception or just handle the exception. This is done by setting postHandlingAction attribute. We can also have handlers associated with the policy like if we are rethrowing an exception what should be the new exception, should we wrap the exception or should we replace the exception. We can as well log the exception to a file or database. Again there are lot of extensible features.

The beauty however lies in the fact that this is completely configuration driven. There is a tool called “EntLibConfig.exe” within the downloaded Enterprise Library folder which has UI for configuring all of the Enterprise Libraries.

5. Once policies are defined, then we have to get handle to instance of appropriate classes (Exception Manager here) and then use it accordingly. The code snippet will be as shown below :

try
{
_input1 = Convert.ToInt32(textBox1.Text);
_input2 = Convert.ToInt32(textBox2.Text);
}
catch (Exception ex)
{
var exceptionManager = EnterpriseLibraryContainer.Current.GetInstance();
exceptionManager.HandleException(ex, “UIPolicy”);
}

Here UIPolicy is a defined policy for exception handling.
I have enabled Logging using Logging Application Block.

Appconfig

Happy coding!

SOAP vs REST

Posted: December 6, 2010 in Dotnet basics

SOAP vs REST

SOAP – Simple Object Access Protocol
REST – REpresentation State Transfer

SOAP is a protocol for sending/receiving data over HTTP as XML.
A typical WebService will be a few methods an WSDL that describes how to call it. There’s no real convention for how these should be structured, so you

always need lots of API documentation.
Typically this will be something like (for .net):
•Http POST to mysite.com/products.asmx/ListAllProducts – returns XML list of products
•Http POST to mysite.com/products.asmx/GetProduct – returns XML for product based on SOAP XML in the posted content
•Http POST to mysite.com/products.asmx/UpdateProduct – changes product based on SOAP XML in the posted content

REST is more of a convention for structuring all of your methods:
•Http GET from mysite.com/products – returns XML or JSON listing all products
•Http GET from mysite.com/products/14 – returns XML or JSON for product 14
•Http POST to mysite.com/products/14 – changes product 14 to what you post in the HTML form.
So REST works more like you’d expect browser URLs to. In that way it’s more natural and as a convention is much easier to understand. All REST APIs work in

a similar way, so you don’t spend as long learning the quirks of each system.
REST goes further, so ideally the following would work:
•Http DELETE to mysite.com/products/14 – removes product 14
•Http PUT to mysite.com/products – adds a new product
Unfortunately the majority of browsers don’t implement these HTTP verbs, so you have to rely on GET and POST for now

—————————————————————————————————————–

SOAP – SOAP has become the standard for exchanging XML-based messages. SOAP was also designed from the ground up to be extensible, so that other standards

could be integrated into it–and there have been many, often collectively referred to as WS-*: WS-Addressing, WS-Policy, WS-Security, WS-Federation, WS-

ReliableMessaging, WS-Coordination, WS-AtomicTransaction, WS-RemotePortlets, and the list goes on.

The basic structure of SOAP is like any other message format (including HTML itself): header and body. In SOAP 1.2 this would look something like
<!–

<env:Envelope xmlns:env=”http://www.w3.org/2003/05/soap-envelope“>
<env:Header>
Header information here
</env:Header>
<env:Body>
Body or “Payload” here, a Fault if error happened
</env:Body>
</env:Envelope>

–>

Note that the <Header> element is optional here, but the <Body> is mandatory

The SOAP Header Element The optional SOAP Header element contains application-specific information (like authentication, payment, etc) about the SOAP

message. If the Header element is present, it must be the first child element of the Envelope element.

The mustUnderstand Attribute The SOAP mustUnderstand attribute can be used to indicate whether a header entry is mandatory or optional for the recipient to

process.  If you add mustUnderstand=”1″ to a child element of the Header element it indicates that the receiver processing the Header must recognize the

element. If the receiver does not recognize the element it will fail when processing the Header.

<!–
<?xml version=”1.0″?>
<soap:Envelope
xmlns:soap=”http://www.w3.org/2001/12/soap-envelope
soap:encodingStyle=”http://www.w3.org/2001/12/soap-encoding“>

<soap:Header>
<m:Trans xmlns:m=”http://www.w3schools.com/transaction/
soap:mustUnderstand=”1″>234
</m:Trans>
</soap:Header>


</soap:Envelope>
–>

The SOAP <Body>
The SOAP body contains the “payload” of the message, which is defined by the WSDL’s <Message> part. If there is an error that needs to be transmitted back to

the sender, a single <Fault> element is used as a child of the <Body>.

The SOAP <Fault>
The <Fault> is the standard element for error handling. When present, it is the only child element of the SOAP <Body>. The structure of a fault looks like:
<!–
<env:Fault xmlns:m=”http://www.example.org/timeouts“>
<env:Code>
<env:Value>env:Sender</env:Value>
<env:Subcode>
<env:Value>m:MessageTimeout</env:Value>
</env:Subcode>
</env:Code>
<env:Reason>
<env:Text xml:lang=”en”>Sender Timeout</env:Text>
</env:Reason>
<env:Detail>
<m:MaxTime>P5M</m:MaxTime>
</env:Detail>
</env:Fault>
–>
A Simple SOAP Example
Putting it all together, below is an example of a simple request-response in SOAP for a stock quote. Here the transport binding is HTTP.

The request:

GET /StockPrice HTTP/1.1
Host: example.org
Content-Type: application/soap+xml; charset=utf-8
Content-Length: nnn

<?xml version=”1.0″?>
<env:Envelope xmlns:env=”http://www.w3.org/2003/05/soap-envelope
xmlns:s=”http://www.example.org/stock-service“>
<env:Body>
<s:GetStockQuote>
<s:TickerSymbol>IBM</s:TickerSymbol>
</s:GetStockQuote>
</env:Body>
</env:Envelope>

The response:

HTTP/1.1 200 OK
Content-Type: application/soap+xml; charset=utf-8
Content-Length: nnn

<?xml version=”1.0″?>
<env:Envelope xmlns:env=”http://www.w3.org/2003/05/soap-envelope
xmlns:s=”http://www.example.org/stock-service“>
<env:Body>
<s:GetStockQuoteResponse>
<s:StockPrice>45.25</s:StockPrice>
</s:GetStockQuoteResponse>
</env:Body>
</env:Envelope>
——————————————————————————————————————-

REST – The emergence of the RESTful style of web services was a reaction to the more heavy-weight SOAP-based standards. In RESTful web services, the emphasis

is on simple point-to-point communication over HTTP using plain old XML (POX).

Representative State Transfer (REST). REST is an architectural style that can be summed up as four verbs (GET, POST, PUT, and DELETE from HTTP 1.1).

HTTP     CRUD Equivalent
==============================
GET      read
POST     create,update,delete
PUT      create,update
DELETE   delete

Re-writing the stock quote service above as a RESTful web service provides a nice illustration of the differences between SOAP and REST web services.

The request:

GET /StockPrice/IBM HTTP/1.1
Host: example.org
Accept: text/xml
Accept-Charset: utf-8
The response:
HTTP/1.1 200 OK
Content-Type: text/xml; charset=utf-8
Content-Length: nnn

The response :

<?xml version=”1.0″?>
<s:Quote xmlns:s=”http://example.org/stock-service“>
<s:TickerSymbol>IBM</s:TickerSymbol>
<s:StockPrice>45.25</s:StockPrice>
</s:Quote>
To summarize their strengths and weaknesses:

*** SOAP ***

Pros:
Langauge, platform, and transport agnostic
Designed to handle distributed computing environments
Is the prevailing standard for web services, and hence has better support from other standards (WSDL, WS-*) and  tooling from vendors
Built-in error handling (faults)
Extensibility

Cons:
Conceptually more difficult, more “heavy-weight” than REST
More verbose
Harder to develop, requires tools

*** REST ***

Pros:

Language and platform agnostic
Much simpler to develop than SOAP
Small learning curve, less reliance on tools
Concise, no need for additional messaging layer
Closer in design and philosophy to the Web

Cons:

Assumes a point-to-point communication model–not usable for distributed computing environment where message may  go through one or more intermediaries.
Lack of standards support for security, policy, reliable messaging, etc., so services that have more sophisticated  requirements are harder to develop

(“roll your own”)
Tied to the HTTP transport model

IComparer / IComparable are interfaces used to compare two objects. The implementing class has to define the logic for sorting. It provides a way to customize the sort order of a collection.

namespace WpfApplication1
{
///

/// Interaction logic for MainWindow.xaml
///

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();

// Exception as there is no IComparable implementation for Sorting. Exception message – Failed to compare two elements in the array
List empList = new List();
empList.AddRange(new List(){new Emp { Name = "A", Age = 25, Address = "Test StreetA" },
new Emp { Name = "A", Age = 26, Address = "Test StreetA1" },
new Emp { Name = "B", Age = 25, Address = "Test StreetB" },
new Emp { Name = "C", Age = 26, Address = "Test StreetC" },
new Emp { Name = "Z", Age = 25, Address = "Test StreetZ" },
new Emp { Name = "D", Age = 26, Address = "Test StreetD" }});
empList.Sort();

}
}

public class Emp
{
public string Name { get; set; }
public int Age { get; set; }
public string Address { get; set; }
}

Implementation of IComparable in WPF. Here, we implement the CompareTo method and sort the Emp objects based on Age property.

namespace WpfApplication1
{
///

/// Interaction logic for MainWindow.xaml
///

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();

// Sorting using IComparable based Age ascending order
List empList = new List();
empList.AddRange(new List(){new Emp { Name = "A25", Age = 25, Address = "Test StreetA25" },
new Emp { Name = "B35", Age = 35, Address = "Test StreetB35" },
new Emp { Name = "C15", Age = 15, Address = "Test StreetC15" },
new Emp { Name = "D45", Age = 45, Address = "Test StreetD45" },
new Emp { Name = "E5", Age = 5, Address = "Test StreetE5" }});
empList.Sort();

foreach (dynamic emp in empList)
{
string listTemp = emp.Name + "-" + emp.Age + "-" + emp.Address;
myListBox.Items.Add(listTemp);
}

}
}

public class Emp : IComparable
{
public string Name { get; set; }
public int Age { get; set; }
public string Address { get; set; }

#region IComparable Members

public int CompareTo(Emp other)
{
// Sort based on Age
if (this.Age > other.Age)
{
return 1;
}
else if (other.Age > this.Age)
return -1;
else
return 0;

}

#endregion
}
}

Note::

List test = new List();
test.Add("B");
test.Add("C");
test.Add("A");
test.Sort();

This will work because by default List and Array implement IComparable.
But below example this won’t work.

public class Emp
{
public string Name { get; set; }
}

// Sorting using IComparable based Age ascending order
List empList = new List();
empList.AddRange(new List(){new Emp { Name = "C25"}, new Emp { Name = "B35"},new Emp { Name = "A15"}});

empList.Sort();

C# compiler is not smart enough to figure out which instance of type “Emp” should come first etc.

IComparer interface :

But sometimes, we may need to sort a list of objects when class does not implement IComparable<> interface and also we may need various kinds of sorting on that class like:

1. Sort Emp by Age in Ascending Order
2. Sort Emp by Age in Descending Order
3. Sort Emp by Name

To solve this problem, .NET provides a special interface called IComparer<> which has a method Compare(), takes two object parameters X, Y and returns an int. Use of IComparer<> interface tells List how exactly you want to sort.

namespace WpfApplication1
{
///

/// Interaction logic for MainWindow.xaml
///

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();

// Sorting using IComparable based Age ascending order
List empList = new List();
empList.AddRange(new List(){new Emp { Name = "A25", Age = 25, Address = "Test StreetA25" },
new Emp { Name = "B35", Age = 35, Address = "Test StreetB35" },
new Emp { Name = "C15", Age = 15, Address = "Test StreetC15" },
new Emp { Name = "D45", Age = 45, Address = "Test StreetD45" },
new Emp { Name = "E5", Age = 5, Address = "Test StreetE5" }});

// Default sort as defined by IComparable
empList.Sort();

foreach (dynamic emp in empList)
{
string listTemp = emp.Name + "-" + emp.Age + "-" + emp.Address;
myListBox.Items.Add(listTemp);
}

// Create IComparer instance
Emp_SortByAgeByDescendingOrder descSort = new Emp_SortByAgeByDescendingOrder();

// Specify the type
empList.Sort(descSort);

foreach (dynamic emp in empList)
{
string listTemp = emp.Name + "-" + emp.Age + "-" + emp.Address;
myListBox1.Items.Add(listTemp);
}

}
}

public class Emp : IComparable
{
public string Name { get; set; }
public int Age { get; set; }
public string Address { get; set; }

public int CompareTo(Emp other)
{
// Sort based on Age
if (this.Age > other.Age)
{
return 1;
}
else if (other.Age > this.Age)
return -1;
else
return 0;

}

}

class Emp_SortByAgeByDescendingOrder : IComparer
{
#region IComparer Members

public int Compare(Emp x, Emp y)
{
if (x.Age < y.Age) return 1;
else if (x.Age > y.Age) return -1;
else return 0;
}

#endregion
}

class Emp_SortByName : IComparer
{
#region IComparer Members

public int Compare(Emp x, Emp y)
{
return string.Compare(x.Name, y.Name);
}

#endregion
}
}

Special case :: If we have both IComparer and IComparable implemented

Sort will take place based on IComparer logic first and then followed by IComparable logic.

public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();

List empList = new List();
empList.AddRange(new List(){new Emp { Name = "A", Age = 25, Address = "Test StreetA25" },
new Emp { Name = "A", Age = 35, Address = "Test StreetB35" },
new Emp { Name = "B", Age = 15, Address = "Test StreetC15" },
new Emp { Name = "B", Age = 45, Address = "Test StreetD45" },
new Emp { Name = "C", Age = 5, Address = "Test StreetE5" }});

// Create IComparer instance
// IComparer sorts by Name asc
// IComparable sorts by Age desc
// Sort should be Name asc and Age desc
Emp_SortByName descSort = new Emp_SortByName();

// Specify the type
empList.Sort(descSort);

foreach (dynamic emp in empList)
{
string listTemp = emp.Name + "-" + emp.Age + "-" + emp.Address;
myListBox1.Items.Add(listTemp);
}

}
}

public class Emp : IComparable
{
public string Name { get; set; }
public int Age { get; set; }
public string Address { get; set; }

public int CompareTo(Emp other)
{
// Sort based on Age
if (this.Age > other.Age)
{
return 1;
}
else if (other.Age > this.Age)
return -1;
else
return 0;

}

}

class Emp_SortByName : IComparer
{
#region IComparer Members

public int Compare(Emp x, Emp y)
{
return string.Compare(x.Name, y.Name);
}

#endregion
}

DLR and Iron Python

Posted: September 7, 2010 in Dotnet basics

 

DLR stands for Dynamic Language Runtime. Dotnet 4.0 supports dynamic language interaction along with static languages for which CLR extends support. Currently supported languages are Ruby and Python. The Dynamic Language Runtime enables language developers to more easily create dynamic languages for the .NET platform. In addition to being a pluggable back-end for dynamic language compilers, the DLR provides language interop for dynamic operations on objects. The DLR has common hosting APIs for using dynamic languages as libraries or for scripting in your .NET applications.

IronPython is an implementation of the Python programming language targeting the .NET Framework and Mono ( A cross platform open source Dotnet framework currently targeted for Linux). IronPython is written entirely in C#. Python is implemented on top of the Dynamic Language Runtime (DLR), a library running on top of the Common Language Infrastructure that provides dynamic typing and dynamic method dispatch, among other things, for dynamic languages. Python is mainly used by system administrators for executing scripts who do not have knowledge about .Net. Dotnet has extended support for IronPython in order to resolve this dependency so that programmers and administrators can work in conjunction.

The first step to getting started is to actual download IronPython. The project is hosted on CodePlex with all of the source code available. After the IronPython installation, its interpreter and its libraries will be installed in your Program Files directory. The interpreter is installed in ipy.exe, where ipy is pronounced “Eye-Pie.” The interpreter remains dormant when you call Python from C#. Dotnet projects which want to use Python need to reference dlls.

Sample usage of Python from IronPython console

>>> import System
>>> from System.Collections import *
>>> h = Hashtable()
>>> h["a"] = "IronPython"
>>> h["b"] = "Tutorial"
>>> for e in h: print e.Key, ":", e.Value

Once you install Iron Python, there will be Visual Studio templates available for creating the projects. Creating a sample standalone file is the best option. Create some simple script file as seen below:

File Name : Test.py

def Simple():
print "Hello from Python"
print "Call Dir(): "
print dir()

File Name : pyt.py

def factorial(n):
"factorial(n) -> returns factorial of n"
if n <= 1: return 1
return n * factorial(n-1)

Place these files in your project folder and set "Build Action" to "Content" and "Copy To Output Directory" to "Copy Always".

Now, create another application which will act as the hosting environment. Reference dlls from Program Files \ Python folder namely IronPython.dll, IronPython.Modules.dll, Microsoft.Dynamic.dll, Microsoft. Scripting.dll and Microsoft. Scripting.Debugger.dll .
Now that you have your project set up correctly you need to do two things:

1. Write or find a script containing Python code that you want to run
2. Write C# code to call the script.

Listing 2 shows a very simple IronPython script that contains a single method called Simple() that writes a few strings to a console window. Save this script to a file called Test.py, and add it to your project, as shown in Figure 2. There are several ways to do this. One is to right click on your project in the Solution Explorer, and choose Add | New Item. Add a text file, and call it Test.py. Click on the new node when it is added to your project, and set its Copy to Output Directory property to Copy Always.
Your class file from where you call the Python script will be as seen below.

Note:: The below code didn’t work along with IronPython 2.7. So, i had to setup 2.6 version and then it worked fine.

There are two examples – the first just calls one method from Python script and the second calls method, passes a parameter and captures the return value.

using System;
using IronPython.Hosting;
using Microsoft.Scripting.Hosting;
using Microsoft.Scripting;
using Microsoft.Scripting.Runtime;
using System.IO;

namespace PythonHost
{
class Program
{
static void Main(string[] args)
{
//// Creates the python runtime
ScriptRuntime ipy = Python.CreateRuntime();

//// The dynamic keyword is needed
//// here because Python is an interpreted
//// scripting language where calls are bound
//// at run time, not at compile time.
//// There is no simple or practical way to
//// bind calls to Python at compile time
//// because Python is designed to be a
//// dynamic language which is resolved
//// at runtime.
dynamic test1 = ipy.UseFile("Test.py");

// Call function
test1.Simple();

// Sample for passing parameters to Python and getting value
dynamic test2 = ipy.UseFile("pyt.py");
int p = test2.factorial(5);
}
}
}

If all is well…you should be able to run your application.

Also, using 2.7 version I was able to setup SilverLight runtime in conjunction with Python.

I setup Silverlight class library and copied the same two scripts and added the following code to setup the execution.

using System.Windows.Controls;
using Silverlight = Microsoft.Scripting.Silverlight;

namespace SilverlightApplication5
{
public partial class MainPage : UserControl
{
public MainPage() {
InitializeComponent();

var runtime = Silverlight.DynamicEngine.CreateRuntime();
var python = runtime.GetEngine("python");
dynamic script = runtime.UseFile("pyt.py");
int p = script.factorial(5);

script = runtime.UseFile("Test.py");
script.Simple();
}
}
}

For Sliverlight with 2.7 version of IronPython, i didn’t face any issues….