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

JQuery

Posted: September 4, 2011 in General Tech

JQuery

JQuery is a Javascript library which is used extensively for client side validation and manipulation of Dom elements.It is a light weight, cross browser compatible and is a repository of many reusable Javascript functions. To learn JQuery, we should have awareness of Html, CSS and Javascript.

The jQuery library contains the following features:

  • HTML element selections and manipulations
  • CSS manipulation
  • HTML event functions
  • JavaScript Effects and animations
  • HTML DOM traversal and modification
  • AJAX

Adding JQuery to a page :

The jQuery library is stored as a single JavaScript file, containing all the jQuery methods.

It can be added to a web page with the following mark-up:

<head>
<script type=”text/javascript” src=”jquery.js”></script>
</head>

Please note that the <script> tag should be inside the page’s <head> section.

jQuery syntax :

Basic syntax is: $(selector).action()

  • A dollar sign to define jQuery
  • A (selector) to “query (or find)” HTML elements
  • A jQuery action() to be performed on the element(s)

Examples:

$(this).hide() – hides current element

$(“p”).hide() – hides all paragraphs

$(“p.test”).hide() – hides all paragraphs with class=”test”

$(“#test”).hide() – hides the element with id=”test”

$(“p”).css(“background-color”,”yellow”);

 

jQuery Events

Here are some examples of event methods in jQuery:

$(document).ready(function) Binds a function to the ready event of a document
(when the document is finished loading)
$(selector).click(function) Triggers, or binds a function to the click event of selected elements
$(selector).dblclick(function) Triggers, or binds a function to the double click event of selected elements
$(selector).focus(function) Triggers, or binds a function to the focus event of selected elements
$(selector).mouseover(function) Triggers, or binds a function to the mouseover event of selected

JQuery updates and downloads :

jQuery.com has all the updates. JQuery is available in two flavors Minified (for production) and Uncompressed (for development and testing). Current version of JQuery is 1.6.2. We can download JQuery file and place it on our application folder and just mark a reference to JQuery file within the html file to make it work.

If you don’t want to download JQuery, you can directly use hosted JQuery library from Google or Microsoft CDN.

 

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!

Assembly in Dotnet – Part1

Posted: February 3, 2011 in Uncategorized

Assembly in Dotnet – Part1

An assembly in dotnet world is nothing but a DLL or an exe. It is basic building block of any Dotnet application. Assembly contains
metadata and manifest information. The reason for the emergence of assembly concept was to overcome the common “DLL Hell” problem in COM. The assembly contains all the code, resources, metadata and even version information
. Metadata contains the details of every “type” inside the assembly. In addition to metadata,assemblies also have a special file called Manifest. It contains information about the current version of the assembly, culture information, public key token if available and other related information.

There is tool called ildasm which can used to view  the assembly information. There is also a Dotnet reflector which can be used to dig into assembly details.

Functions of a assembly :

  1. It contains code that the common language runtime executes. It is a managed environment
  2. It forms a security boundary. An assembly is the unit at which permissions are requested and granted
  3. It is the unit at which side-by-side execution is supported.
  4. It forms a deployment unit. When an application starts, only the assemblies that the applicationinitially calls must be present. Other assemblies, such as localization resources or assemblies containing utility classes,can be retrieved on demand
  5. It forms a version boundary. The assembly is the smallest versionable unit in the common language runtime; all types and resources in the same assembly are versioned as a unit.

There are in all 3 different types of assemblies :

  • 1. Private Assembly
  • 2. Shared or Strong named assembly
  • 3. Satellite assembly

This article focuses only on private assembly and few other assembly concepts. Private assembly is a managed standalone executable or a class library file.

§ Creating a simple assembly and referencing other assembly to it

§ Assembly probing

Creating a simple assembly and referencing other assembly to it

I have a created an assembly called “AssemblyHost” and added reference to “Test” assembly. I am calling method “Add” defined
within Test assembly’s class.

Test
Assembly

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace Test

{

public class MyClass

{

public static int Add(int i,int j)

{

return (i + j);

}

}

}

AssemblyHost assembly

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Test;

namespace AssemblyHost
{
    class Program
    {
        static void Main(string[] args)
        {
            int j = MyClass.Add(5, 7);
            Console.WriteLine(j.ToString());
            Console.ReadLine();
        }
    }
}

Output

2. Assembly Probing – Dotnet runtime searches for the assembly in the following path

§

  • Look for the dll or exe under the Application directory (generally bin folder) or AppBase – Example shown above works in this fashion
  • §
  • Look for the assembly folder under the Application directory (generally bin/<assemblyname>) and try to find dll or exe .

Suppose I create one more project “Test1” as seen below :

When I try to load the new assembly without referencing, I get an error. However, if copy and paste a folder “Test1” under my application directory (bin/Debug) and copy the dll..it works

Application Directory – AssemblyHost/bin/Debug

Folder Path – AssemblyHost/bin/Debug/Test

Dll Path – Folder Path/Test.dll

§
Look for probing path defined under configuration file

I have to define my application config file as seen below to search for dll or exes to be loaded into my running assembly. The below configuration searches within MyLib folder inside my Application Directory and searches for all dlls.

<?xml version=1.0 encoding=utf-8 ?>

<configuration>

<runtime>

<assemblyBinding xmlns=urn:schemas-microsoft-com:asm.v1>

<probing privatePath=MyLib/>

</assemblyBinding>

</runtime>

</configuration>

GAC(Global Assembly Cache)

If the private probing fails, then the assembly is searched from within GAC. I will cover GAC in the next part of this article.

Till then happy reading.

WCF Services using REST

Posted: January 22, 2011 in WCF

WCF Using REST
REST stands for Representational State Transfer. Architectural pattern more inclined towards web. Web of Services should work in the same way as Web Of Pages works – Each resource is identified by an unique id in the form of an URI. Resource can be anything a Website, HTML page, xml document etc. Services can be built on top of REST architecture. Structured way of uniquely identifying resources and accessing them. Uses only standard verbs POST, GET, PUT and DELETE. REST is not a standard as such but just an architectural pattern.

Rest Principles :
1. Identify each resource uniquely. Resource can be anything a Website, HTML page, xml document etc.
2. Simple and Open – It is an architecture pattern and can be applied to any system. Uses only standard Http Verbs.
3. Use Universal API – Http – It can be used by any client or can be called from any programming language. It is technology independent.
4. Linked Resources – resources can contain link to other resources.

Rest usage examples :
REST – Yahoo web services use REST, including Flickr, del.icio.us API uses it
SOAP and REST both – EBay and Amazon
Google Web Services – SOAP

High REST and Low REST
High REST – Uses all 4 verbs and uses well-constructed URIs.
LOW REST – Uses mostly Get and POST verbs only. More suited for Ajax services.
NOTE ::
PUT and DELETE verbs are not supported by all browsers. Also, PUT and DELETE can be handled using POST verb itself.

HTTP Verbs
HTTP defines nine methods (sometimes referred to as “verbs”) indicating the desired action to be performed on the identified resource.

Verb Action
GET Fetch a resource
PUT Update resource
DELETE Delete a resource
POST Append to resource

Advantages of REST :
1. LightWeight – uses POX or JSON or ATOMPub for data transmission
2. REST does not support WS-* standard.
3. Message transmission can be controlled and supports different formats such as JSON, POX, AtomPub. Developers need not understand SOAP message structure as in case of SOAP.
4. Browsers can talk to rest services directly because REST works using URIs, QueryStrings, SSL.
5. WADL (Web Application Description Language) is a new standard available to support metadata for REST services.
6. Uses only standard Http Verbs and is technology independent.

Limitations :
1. Less secular has they do not obey WS-* specifications
2. No metadata – WSDL. WADL is available but still its not universally accepted.

WCF REST basics

1. Is supported since Dotnet 3.5. There are readily available templates for REST projects.Dotnet 3.5 has REST starter kit as well.
2. REST in .NET 4 is greatly simplified and leverages the Web Routing capabilities used in ASP.NET MVC and other parts of the web frameworks
3. Special binding available for REST support
WebHttpBinding – A binding used to configure endpoints for Web services that are exposed through HTTP requests instead of SOAP messages.
4. WebGet and WebInvoke (all other verbs apart from GET) attributes were added to WCF. Message transmission format is POX or JSON.
5. UriTemplate :
o String that allows to define the structure of the URL. It is similar to ASP.Net Routing.
o UriTemplate only supports string parameters.
o The segments in curly braces describe variables or holes. The segments not in curly braces describe literal strings. Template is bound with parameters to fill the holes.
o UriTemplate can have a single wildcard character and also default values for variables. UriTemplate also includes wildcard capabilities. UriTemplate=”*”will route all URIs to one method
Example :
URI Template
/weather/wa/seattle/cycling /weather/{state}/{city}/{activity}
/weather/wa seattle /weather/{state}{city}
/weather/USA/wa/Climate /weather/{country=USA}/{state}/Climate
/weather/A /weather/B /weather/*

6. Global.asax is used to set the route to your service using the new ServiceRoute class
7. SOAP and REST based endpoints can co-exist side by side.
http://www.servicestack.net/ framework does it for you can you can as well do it yourself by defining multiple endpoints.

Sample Soure Code :

I am assuming that you have added an ADO.Net Entity Model object in your project file which maps to an Area table having following fields

ID – Primary Key, varchar
Name – varchar
Code – varchar

This entity is available under SampleEntities Object context.

My code looks as seen below :

————————————————————————————————

using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;

namespace WcfRestService1
{
// Start the service and browse to http://:/Service1/help to view the service’s generated help page
// NOTE: By default, a new instance of the service is created for each call; change the InstanceContextMode to Single if you want
// a single instance of the service to process all calls.
[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
// NOTE: If the service is renamed, remember to update the global.asax.cs file
public class AreaService
{

[WebGet(UriTemplate = “/GetAllAreas”, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
public List

GetAllAreas()
{
SampleEntities1 ctx = new SampleEntities1();

var allAreas = (from p in ctx.Areas select p).ToList

();
return allAreas;
}

[WebGet(UriTemplate = “/GetArea/{id}”, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
public Area GetAreaWithID(string id)
{
SampleEntities1 ctx = new SampleEntities1();
var area = (from p in ctx.Areas where p.ID == id select p).Single();
return area;
}

[WebInvoke(UriTemplate = “/AddArea/{id} {name} {code}”,Method=”POST”)]
public void AddArea(string id, string name, string code)
{
SampleEntities1 ctx = new SampleEntities1();
Area a1 = new Area { ID = id, Name = name, Code = code };
ctx.Areas.AddObject(a1);
ctx.SaveChanges();
}

[WebInvoke(UriTemplate = “/Delete/{id}”, Method = “DELETE”, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
public void DeleteArea(string id)
{
SampleEntities1 ctx = new SampleEntities1();
Area a1 = ctx.Areas.Where(p => p.ID == id).SingleOrDefault();
ctx.Areas.DeleteObject(a1);
ctx.SaveChanges();
}

}
}

——————————————————————————————-

I am using the default web.config which uses standard endpoints .WebHttpBinding is used for REST services as it does not Soap message format for data tranmission. You can customize the message transmission format and choose either POX, JSON,AtomPub to name a few.

I am using C# Rest WCF Template available for .Net 4.0. It uses Routing and WebHttpBinding internally. So, there wont be any manual changes to the default web.config provided by the template . However, an entry for ADO.Net Entity object will be added that too once you configure the ADO.Net Entity.

OData

Posted: January 5, 2011 in Uncategorized

Open Data Protocol (or OData, http://www.odata.org) is an open protocol for sharing data. It is built upon AtomPub. OData is a REST (Representational State Transfer) protocol; therefore a simple web browser can view the data exposed through an OData service. The basic idea behind OData is to use a well known data format (Atom feed) to expose a list of entities. AtomPub extends the basic Atom Protocol by allowing not only read but the whole set of CRUD operations. Odata can either use AtomPub or JSON format for data transmission.

OData isn’t only about querying. It enables CRUD operations. Those are performed by using different HTTP verbs (GET for reading, PUT for creating, POST for updating, and DELETE for deleting). By default, an OData service returns Atom XML format. It also supports JSON. In order to receive a JSON representation, this must be encoded in the HTTP header.

 

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