Friday, 27 July 2012

Microsoft Extensibility Framework(MEF)-Introduction

What is MEF?

Managed Extensibility Framework (MEF) is a component of .NET Framework 4.0 for creating lightweight, extensible applications. It allows application developers to discover and use extensions with no configuration required. It also lets extension developers easily encapsulate code and avoid fragile hard dependencies. MEF not only allows extensions to be reused within applications, but across applications as well. MEF was introduced as a part of .NET 4.0 and Silverlight 4.


Why was MEF Introduced?

How does a dotnet application work?
If there are many libraries that are referenced in a dot net project,with CLR and JIT in the application loader tries to load only those libraries that are needed for execution at the Form_Load.Whenever a method is called ,the IL for those methods are compiled JIT on demand and loaded into memory.

This is the concept of dynamic loading of libraries.

As the Microsoft says,"The Managed Extensibility Framework (MEF) is a new library in .NET that enables greater reuse of applications and components. Using MEF, .NET applications can make the shift from being statically compiled to dynamically composed. If you are building extensible applications, extensible frameworks and application extensions, then MEF is for you."

Now, although .NET uses the concept of loading the dlls on demand but still if you run a program , remove the referenced dll from bin and as soon as the execution reaches the point where the dll has to be loaded ,you add the dll the application fails to run and exit with an error. This is the problem that MEF tries to resolve.

Without MEF also, this problem of dynamically loading the dll during execution can be solved using the concept of reflection. But the amount of time and LOC used to solve this problem is complex and high.
So, the concept of MEF entered.

  • MEF provides a standard way for the host application to expose itself and consume external extensions. Extensions, by their nature, can be reused amongst different applications. However, an extension could still be implemented in a way that is application-specific. Extensions themselves can depend on one another and MEF will make sure they are wired together in the correct order (another thing you won't have to worry about).
  • MEF offers a set of discovery approaches for your application to locate and load available extensions.
  • MEF allows tagging extensions with additional metadata which facilitates rich querying and filtering.

Looking inside MEF

MEF's core consists of a catalog and a CompositionContainer. A catalog is responsible for discovering extensions and the container coordinates creation and satisfies dependencies.

The essence of MEF paradigm is built upon the idea of needs and part that can be discovered (in order of satisfying the needs).  MEF assume that applications are build from parts, each part may have needs to   consume other parts, or may be discover and consumed by other.

 In general parts consumers care about the contract and doesn't care about the parts implementation. 

MEF using Import solves the needs  term of Contract (the contract present the capabilities that is needed). Uses Export,to Expose discoverable parts (that latter can be instantiate and consumed by the Import), the Export is also Contract based. Compose: is handle by the MEF engine, it responsible of putting the pieces together (discover and instantiate the matching Exports, and hand it to the Imports).



Basic Terms Used in MEF

  • Part: A Part is an object (e.g. a class, a method or a property) that can be imported or exported to the application.
  • Catalog: An object that helps in discovering the available composable parts from an assembly or a directory.
  • Contract: The import and exported parts need to talk between themselves via some contract (e.g. an Interface or predefined data type like string)
  • Import: It defines the need that a part has. It is applicable only for single Export Attribute.
  • ImportMany: It is similar to Import Attribute but supports for multiple Export Attributes.
  • Export: The import attribute creates the needs. The Export attribute fulfills that. It exposes those parts that will participate in the composition.
  • Compose: In MEF jargon, Compose is that area where the Exported parts will be assembled with the imported ones.

Advantages

  • MEF breaks the tightly coupled dependencies across the application but respects the type checking of the loosely coupled parts.
  • Applications can be extended.
  • Components can be added at runtime.
  • Dynamic discovery of the components.
  • Great piece of reusability.

Conclusion



MEF works upon the principle of demand and supply ;needs of parts. 
Step 1:Parts and needs should be decorated with Import and Export attributes.
Step 2:The needs and parts must agree to the contract. 
Step 3:Using Catalog MEF discovers the parts to be plugged in
Step 4: Composition engine makes sure that parts satisfy the contract.



Thursday, 26 July 2012

Difference Between MVC ,MVP and MVVM



The common motivation behind all MVC,MVP and MVVM is separation of concerns.
Advantages of these approaches are
  • good for UI designers
  • swapping UIs (for instance windows to web)
  • make UI easy for Unit Testing, etc. 
    Following table gives the differences between the three patterns







             MVC                                           MVP


MVVM



Model-view-Controller (MVC)

  • MVC architecture in .net is useful in the independent development, maintenance and testing every component without interrupting with the other. 
  • MVC.Net is often used in the web platform that uses either HTML or XHTML. 
  • MVC pattern in asp.net can be very flexible for the programmers as testing, design, maintenance and development can be effectively handled. 
  • MVC  applications functions distinctively in that the user interacts with the user interface and the controller will be able to handle the information from the interface. Both the end users and the software programmers are highly benefited by this software.
  •  Hence the use of MVC architecture c# programs can be highly beneficiary for any business holders. Asp .net MVC design and development can be faster in processing and can they can keep the system performance high. 
  • Let us see the three components
What is a Model?

  • MVC model is basically a C# or VB.NET class
  • A model is accessible by both controller and view
  • A model can be used to pass data from Controller to view
  • A view can use model to display data in page.
What is a View?

  • View is an ASPX page without having a code behind file
  • All page specific HTML generation and formatting can be done inside view
  • One can use Inline code (server tags ) to develop dynamic pages
  • A request to view (ASPX page) can be made only from a controller’s action method

What is a Controller?

  • Controller is basically a C# or VB.NET class which inherits system.mvc.controller
  • Controller is a heart of the entire MVC architecture
  • Inside Controller’s class action methods can be implemented which are responsible for responding to browser OR calling views.
  • Controller can access and use model class to pass data to views
  • Controller uses ViewData to pass any data to view
Advantages
The main advantage of using the MVC pattern is :
  • That it makes the code of the user interface more testable
  • It makes a very structured approach onto the process of designing the user interface, which in itself contributes to writing clean, testable code, that will be easy to maintain and extend
  • The Model-View-Controller is a well-proven design pattern to solve the problem of separating data (model) and user interface (view) concerns, so that changes to the user interface do not affect the data handling, and that the data can be changed without impacting/changing the UI. 
  • The MVC solves this problem by decoupling data access and business logic layer from UI and user interaction, by introducing an intermediate component: the controller. This MVC architecture enables the creation of reusable components within a flexible program design (components can be easily modified)
Limitations
  This design approach is not suitable for smaller applications. It Overkills the small applications.

Adapter Pattern


What is Adapter pattern?

The adapter pattern is adapting between classes and objects. 


Explanation

Like any adapter in the real world it is used to be an interface, a bridge between two objects.
In real world we have adapters for power supplies, adapters for camera memory cards, and so on. Probably everyone have seen some adapters for memory cards. If you can not plug in the camera memory in your laptop you can use and adapter.You plug the camera memory in the adapter and the adapter in to laptop slot. 




public class Rectangle
{
public int Width;
public int Height;
}
public class Calculator
{
public int GetArea(Rectangle rectangle)
{
int area = rectangle.Width * rectangle.Height;
return area;
}
}
As we cn see from the above example an instance of Rectangle is needed to calculate the area. If we have a square class of definition below, the calculation cannot be done.
public class Square
{
public int Size;
}
Here we have to create a new CalculatorAdapter to get the work done.
public class CalculatorAdapter
{
public int GetArea(Square square)
{
Calculator calculator = new Calculator();
Rectangle rectangle = new Rectangle();
rectangle.Width = rectangle.Height = square.Size;
int area = calculator.GetArea(rectangle);
return area;
}
}
The CalculatorAdapter performs the following functions:
· Takes the Square parameter
· Convert Square to Rectangle
· Call the original Calculator.GetArea() method
· Return the value received
The invoking code is shown below:
// Create Square class and assign Size from UI
Square square = new Square();
square.Size = SquarePanel.Width;
// Use Adapter to calculate the area
CalculatorAdapter adapter = new CalculatorAdapter();
int area = adapter.GetArea(square);
// Display the result back to UI
ResultLabel.Text = “Area: ” + area.ToString();


Design patterns in .net



What are Design Patterns?

To say what design patterns are in a single sentence is difficult but we can say as design patterns are :
• Solutions to recurring design problems.
• They are a set of rule which help the developer to accomplish a certain task.
• Design patterns are architectural patterns and generalized solutions , which can be applied when needed.
• These are standardized and efficient solutions to software design and programming problems that are re-usable.
Generally Gang-of-Four(GoF) are used.

Why to Use Design Patterns?

Design patterns are proven solution templates, using design templates not only reduces the overhead of architecting a solution afresh but these are also  optimized ,easy to do , easy to learn solutions.


What are the common design patterns used?

CREATIONAL
creational design patterns are design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation
STRUCTURAL
Design Patterns that ease the design by identifying a simple way to realize relationships between entities.
BEHAVIOURIAL
Identify common communication patterns between objects and realize these patterns.


CREATIONAL PATTERNS

  Abstract Factory
  Creates an instance of several families of classes
  Builder
  Separates object construction from its representation
  Factory Method
  Creates an instance of several derived classes
  Prototype
  A fully initialized instance to be copied or cloned
  Singleton
  A class of which only a single instance can exist


STRUCTURAL PATTERNS

  Adapter
  Match interfaces of different classes
  Bridge
  Separates an object’s interface from its implementation
  Composite
  A tree structure of simple and composite objects
  Decorator
  Add responsibilities to objects dynamically
  Facade
  A single class that represents an entire subsystem
  Flyweight
  A fine-grained instance used for efficient sharing
  Proxy
  An object representing another object

BEHAVIORIAL

  Chain of Resp.
  A way of passing a request between a chain of objects
  Command
  Encapsulate a command request as an object
  Interpreter
  A way to include language elements in a program
  Iterator
  Sequentially access the elements of a collection
  Mediator
  Defines simplified communication between classes
  Memento
  Capture and restore an object's internal state
  Observer
  A way of notifying change to a number of classes
  State
  Alter an object's behavior when its state changes
  Strategy
  Encapsulates an algorithm inside a class
  Template Method
  Defer the exact steps of an algorithm to a subclass
  Visitor
  Defines a new operation to a class without change

Patterns I have used?

I have used Creational and Structural and have never implemented any Behaviorial Pattern.

In Creational I have used:
  • Abstract Factory
  • Factory Method
  • Singleton Method

In Structural I have used
  • Adapter Pattern
  • Facade Pattern
Other patterns I know are:
  • Decorator
  • Builder
  • Iterator


Can we create our own pattern?

Whenever a certain solution that is reusable in a vast majority of your projects, it can be abstracted to a design pattern and cab be used across the organisation.

Abstract Factory


What is Abstract factory

To create an abstract factory ,provide an interface for creating families of related or dependent objects without specifying their concrete classes.

Explanation

Abstract factory is the extension of basic Factory pattern. It provides Factory interfaces for creating a family of related classes.In an Abstract Factory class implementation you declare interfaces for Factories, which will in turn work in similar fashion as with Factories.



public interface IFactory1
    {
        IPeople GetPeople();
    }
    public class Factory1 : IFactory1
    {
        public IPeople GetPeople()
        {
            return new Villagers();
        }
    }

    public interface IFactory2
    {
        IProduct GetProduct();
    }
    public class Factory2 : IFactory2
    {
        public IProduct GetProduct()
        {
            return new IPhone();
        }
    }

    public abstract class AbstractFactory12
    {
        public abstract IFactory1 GetFactory1();
        public abstract IFactory2 GetFactory2();
    }

    public class ConcreteFactory : AbstractFactory12
    {

        public override IFactory1 GetFactory1()
        {
            return new Factory1();
        }

        public override IFactory2 GetFactory2()
        {
            return new Factory2();
        }
    }



Where to Use

We should use the Abstract Factory design pattern when:
  • The system needs to be independent from the way the products it works with are created.
  • The system is or should be configured to work with multiple families of products.
  • A family of products is designed to work only all together.T
  • The creation of a library of products is needed, for which is relevant only the interface, not the implementation.

Conclusion


  • The abstract factory class defines the abstract methods that have to be implemented by concrete factory classes. It serves as interface and contract definition.
  • The methods return values are also defined by abstract classes, this allows a high flexibility and independence, leading to methods that must only be implemented once.

Factory Pattern


What is Factory Pattern?

Factory Method pattern defines an interface for creating an object, but let subclasses decide which class to instantiate. Factory method lets a class defer instantiation to subclasses.

Explanation

This pattern is very simple.The client needs a product, but instead of creating it directly using the new operator, it asks the factory object for a new product, providing the information about the type of object it needs.
The factory instantiates a new concrete product and then returns to the client the newly created product(casted to abstract product class).The client uses the products as abstract products without being aware about their concrete implementation.


This adheres the OCP of SOLID design principles.

ADO.Net uses the factory method pattern for creating connection object based on providers.

Conclusion

While designing an application just think if you really need it a factory to create objects.Using it unnecessarily may bring unnecessary complexity in application. If you have many objects of the same base type and you manipulate them mostly casted to abstract types, then you need a factory.