Thursday, November 10, 2011

Factory Method Pattern

Very useful pattern, that I am using almost each day - Factory Method Pattern.
I would like to explain it with very simple code that I created for this post:

Before just to image how its looks:



C# Code:

3 Instances that will need to create according to some conditions and we did know before:


 public class Instance1IInstance
    {
        public void Print()
        {
            Console.WriteLine(ToString());
            Console.ReadLine();
        }
    }


 public class Instance2IInstance
    {
        public void Print()
        {
            Console.WriteLine(ToString());
            Console.ReadLine();
        }
    }


 public class Instance3IInstance
    {
        public void Print()
        {
            Console.WriteLine(ToString());
            Console.ReadLine();
        }
    }

All this instances inherits from IInstance interface that have only one PRINT(); method:

 public interface IInstance
    {
        void Print();   
    }

Next - its a Factory class that do all works (concrete of IFactory interface), create one of three above Instance classes according to some condition, in our case its simply swithch caseindex.


 public interface IFactory
    {
        IInstance CreateInstance();
    }



 public class FactoryIFactory
    {
        private int Index { getset; }
 
        public Factory(int instanceIndex)
        {
            Index = instanceIndex;
        }
        public IInstance CreateInstance()
        {
            switch (Index > 2 ? 3 : Index)
            {
                case 1:
                    return new Instance1();                    
                case 2:
                    return new Instance2();
                default:
                    return new Instance3();
            }
        }        


and, main that will run our modest programm:

 static void Main(string[] args)
 {
      IInstance instance = new Factory(2).CreateInstance();
      instance.Print();
 }


Enjoy!























Thursday, November 3, 2011

Observer Pattern with Managed Extensibility Framework (MEF)

Following example expose using of Observer Pattern with MEF dependency injection.
I will need send to all observers XmlElement I got from WebService.

Interfaces of Observer Pattern:


public interface IResponceObserver
{
        void Update();
}

public interface IResponceSubject
{
        List<IResponceObserver> Observers { getset; }
        void Attach(IResponceObserver observer);
        void Detach(IResponceObserver observer);
        void Notify();
}



And Concrete of Subject interface:


public class ResponceSubjectIResponceSubject
{
        public List<IResponceObserver> Observers { getset; }
        
        public void Attach(IResponceObserver observer)
        {
            Observers.Add(observer);
        }
 
        public void Detach(IResponceObserver observer)
        {
            Observers.Remove(observer);
        }
 
        public void Notify()
        {
            foreach (IResponceObserver o in Observers)
            {
                o.Update();
            }
        }
}

Suppose we have two observer classes that need to realize Update() method:



[Export(typeof(IResponceObserver))]
public class LoginCommandHandler_1 CommandHandlerBase, IResponceObserver {
     public void Update()
     {
        WriteLine ("LoginCommandHandler_1")
     }
}

[Export(typeof(IResponceObserver))]
public class LoginCommandHandler_2 CommandHandlerBase, IResponceObserver {
     public void Update()
     {
        WriteLine ("LoginCommandHandler_2")
     }
}

And Main Class that will add observer to List of subject and Notify all observers:

public class CustomerServiceAgent : ICustomerServiceAgent
{         
        [ImportMany]
        public IResponceObserver[] ResponseObservers getset; }

        public void SomethingDo()
        {
            //REGISTER ALL OBSERVERS WHO WANT TO GET ANY FROM response.Customer
            IResponceSubject responceSubject = new ResponceSubject();
            foreach (var observer in ResponseObservers)
            {
                responceSubject.Attach(observer);   
            }            
 
            //YOUR CODE HERE:
            //UPDATE All Observers with response.Customer.Any
            responceSubject.Notify();
 
            return customer;
        }
}

Output:

\> LoginCommandHandler_1
\> LoginCommandHandler_2

I hope its help to understand MEF and return against on Observer Pattern

Thanks,
Enjoy! 

Sunday, October 30, 2011

Explicit Interface C#


In this article we will see how to explicitly implement interface members and how to access those members from the interface instances.
 
One of the challenges we face with interfaces is that they may include that have the same name as existing class member or any other interface that you may be implementing. Hence we use explicit interface implementation to distinguish the interface methods that would otherwise conflict. When a member is explicitly implemented, it cannot be accessed through a class instance, but only through an instance of the interface.
 
Let us look at an example where we have two interfaces and we will implement the same in our class:
 
interface Interface1
    {
        void InterfaceMethod();
    }

    interface Interface2
    {
        void InterfaceMethod();
    }

    class MyClass : Interface1, Interface2
    {
        public void InterfaceMethod()
        {
            Console.WriteLine("MyClass.InterfaceMethod()");
        }
    }

In this case, InterfaceMethod is a public class member that implicitly implements a member of both interfaces. InterfaceMethod() can be invoked through either interface or through the class itself as follows:
 
MyClass mclass = new MyClass();
Interface1 minterface1 = (Interface1)mclass;
Interface2 minterface2 = (Interface2)mclass;

minterface1.InterfaceMethod();
minterface2.InterfaceMethod();
mclass.InterfaceMethod();

 
The output from this code is:
 
MyClass.InterfaceMethod()
MyClass.InterfaceMethod()
MyClass.InterfaceMethod()

 
This works fine if you want InterfaceMethod() to do the same thing in both interfaces. But in real scenarios methods which are in different interfaces have unique purpose and implementation, so here we will see the implementation of Explicit interface by just using its fully qualified name.
 
Let change our MyClass code a little like the one below:
 
class MyClass : Interface1, Interface2
    {
        public void InterfaceMethod()
        {
            Console.WriteLine("MyClass.InterfaceMethod()");
        }

        void Interface1.InterfaceMethod()
        {
            Console.WriteLine("Interface1.InterfaceMethod()");
        }
    }

 
Now when we run our application we get the following output:

Interface1.InterfaceMethod()
MyClass.InterfaceMethod()
MyClass.InterfaceMethod()
 
Remember that when an interface method is explicitly implemented, we cannot access that as a public member of the class. The only way to access it is through the interface.
 
Lets modify the MyClass to check this:
 
class MyClass : Interface1, Interface2
    {
        void Interface1.InterfaceMethod()
        {
            Console.WriteLine("Interface1.InterfaceMethod()");
        }
    }

 
Let's run our program and check the output:
 
We get a compile error:
 
MyClass does not contain a definition for 'InterfaceMethod' and no extension method 'InterfaceMethod' accepting a first argument of type MyClass could be found (are you missing a using directive or an assembly reference?
 
We get this error because the explicit implementation of Interface1.InterfaceMethod()
 
hides from the class. The only way to call Interface1.InterfaceMethod() now is through MyClass minterface1 interface.
 
Let's look at an example where we want to call default methods and implement the methods normally from one interface, and explicitly implement the methods from another interface:
 
MyClass implementation is changed to show this example:
 
interface Celsius
    {
        void GetTemp();
    }

    interface Fahrenheit
    {
        void GetTemp();
    }

class MyClass : Celsius,Fahrenheit
    {
        public void GetTemp()
        {
            Console.WriteLine("Get Celsius Temp");
        }

        void Fahrenheit.GetTemp()
        {
            Console.WriteLine("Get Fahrenheit Temp");
        }
    }

 
In this case, you can access the Celsius GetTemp from the class instance and access the Fahrenheit  GetTemp from the interface instance:
 
MyClass mclass = new MyClass();
Fahrenheit mfahrenheit  = (Fahrenheit)mclass;

mclass.GetTemp();
mfahrenheit.GetTemp();

 
Following is the output in the above case:
 
Get Celsius Temp
Get Fahrenheit Temp

 
Hope you liked this article.
 
Coder-Forever!

Monday, September 26, 2011

Visitor Design Pattern

In Simple words - In object-oriented programming and software engineering, the visitor design pattern is a way of separating an algorithm from an object structure on which it operates. A practical result of this separation is the ability to add new operations to existing object structures without modifying those structures. It is one way to easily follow the open/closed principle.


UML:
File:VisitorClassDiagram.svg


The participants classes in this pattern are:
  • Visitor - This is an interface or an abstract class used to declare the visit operations for all the types of visitable classes. Usually the name of the operation is the same and the operations are differentiated by the method signature: The input object type decides which of the method is called.

  • ConcreteVisitor - For each type of visitor all the visit methods, declared in abstract visitor, must be implemented. Each Visitor will be responsible for different operations. When a new visitor is defined it has to be passed to the object structure.

  • Element- is an abstraction which declares the accept operation. This is the entry point which enables an object to be "visited" by the visitor object. Each object from a collection should implement this abstraction in order to be able to be visited.

  • ConcreteElement - Those classes implements the Visitable interface or class and defines the accept operation. The visitor object is passed to this object using the accept operation.


A user object receives a pointer to another object which implements an algorithm. 


A Diagram of the Java Code Example.        I, the copyright holder of this work, hereby release it into the public domain.  This applies worldwide. In case this is not legally possible, I grant any entity the right to use this work for any purpose, without any conditions, unless such conditions are required by law.


The visitor pattern is used when:


  • Similar operations have to be performed on objects of different types grouped in a structure (a collection or a more complex structure).

  • There are many distinct and unrelated operations needed to be performed. Visitor pattern allows us to create a separate visitor concrete class for each type of operation and to separate this operation implementation from the objects structure.

  • The object structure is not likely to be changed but is very probable to have new operations which have to be added. Since the pattern separates the visitor (representing operations, algorithms, behaviors) from the object structure it's very easy to add new visitors as long as the structure remains unchanged.








Wednesday, September 14, 2011

The Observer Pattern

With this post I opening my new posts line of Design Patterns.
And First one, I think, important one - Observer Pattern.
I really hope I'll possible explain pattern in easy and understandable way.
Enjoy :-)

Why to use:

The need to maintain consistency between related objects without making
classes tightly coupled.


When to use:


Use the Observer pattern in any of the following situations:
- When an abstraction has two aspects, one dependent on the other.
   Encapsulating these aspects in separate objects lets you vary and reuse
   them independently.
- When a change to one object requires changing others
- When an object should be able to notify other objects without making
   assumptions about those objects





Participants:
Subject
  • Keeps track of its observers
  • Provides an interface for attaching and detaching Observer objects

Observer

  • Defines an interface for update notification

ConcreteSubject

  • The object being observed
  • Stores state of interest to ConcreteObserver objects
  • Sends a notification to its observers when its state changes

ConcreteObserver

  • The observing object
  • Stores state that should stay consistent with the subject's
  • Implements the Observer update interface to keep its state consistent with the subject's
Benefits
Minimal coupling between the Subject and the Observer
  • Can reuse subjects without reusing their observers and vice versa
  • Observers can be added without modifying the subject
  • All subject knows is its list of observers
  • Subject does not need to know the concrete class of an observer, just that each observer implements the update interface
  • Subject and observer can belong to different abstraction layers
Support for event broadcasting
  • Subject sends notification to all subscribed observers
  • Observers can be added/removed at any time

Consequences
Liabilities
  • Possible cascading of notifications
  • Observers are not necessarily aware of each other and must be careful about triggering updates
  • Simple update interface requires observers to deduce changed item

Implementation Issues
How does the subject keep track of its observers?
  • Array, linked list
What if an observer wants to observe more than one subject?
  • Have the subject tell the observer who it is via the update interface
Who triggers the update?
  • The subject whenever its state changes
  • The observers after they cause one or more state changes
  • Some third party object(s)
Make sure the subject updates its state before sending out notifications
How much info about the change should the subject send to the observers?
  • Push Model - Lots
  • Pull Model - Very Little

Can the observers subscribe to specific events of interest?
  • If so, it's publish-subscribe
Can an observer also be a subject?
  • Yes!
What if an observer wants to be notified only after several subjects have
changed state?
  • Use an intermediary object which acts as a mediator
  • Subjects send notifications to the mediator object which performs any necessary processing before notifying the observers.
Known Uses
Smalltalk Model/View/Controller user interface framework
  • Model = Subject
  • View = Observer
  • Controller is whatever object changes the state of the subject
Related Patterns
  • Mediator
              › To encapsulate complex update semantics.



And now, some thing you are waiting for....code sample :-)

Observable Class:

public Observable()
 Construct an Observable with zero Observers
public synchronized void addObserver(Observer o)
 Adds an observer to the set of observers of this object
public synchronized void deleteObserver(Observer o)
 Deletes an observer from the set of observers of this object
protected synchronized void setChanged()
 Indicates that this object has changed
protected synchronized void clearChanged()
 Indicates that this object has no longer changed, or that it has already
 notified all of its observers of its most recent change.  This method is called
 automatically by notifyObservers().

public synchronized boolean hasChanged()
 Tests if this object has changed.  Returns true if setChanged() has been
 called more recently than clearChanged() on this object; false otherwise.
public void notifyObservers(Object arg)
 If this object has changed, as indicated by the hasChanged() method, then
 notify all of its observers and then call the clearChanged() method to
 indicate that this object has no longer changed.  Each observer has its
 update() method called with two arguments: this observable object and the
 arg argument. The arg argument can be used to indicate which attribute of
 the observable object has changed.
public void notifyObservers()
 Same as above, but the arg argument is set to null.  That is, the observer is
given no indication what attribute of the observable object has changed.

Observer Interface

public abstract void update(Observable o, Object arg)
 This method is called whenever the observed object is changed. An
 application calls an observable object's notifyObservers method to have all
 the object's observers notified of the change.
 Parameters:
   › o - the observable object
   › arg - an argument passed to the notifyObservers method

-------------------------------------------------------------------------------------------------------


/**
 * A subject to observe!
 */
public class ConcreteSubject extends Observable
{
  private String name;
  private float price;

  public ConcreteSubject(String name, float price)
  {
    this.name = name;
    this.price = price;
    System.out.println("ConcreteSubject created: " + name + " at "
      + price);
  }

  public String getName() {return name;}
  public float getPrice() {return price;}

  public void setName(String name)
  {
    this.name = name;
    setChanged();
    notifyObservers(name);
   }

  public void setPrice(float price)
  {
    this.price = price;
    setChanged();
    notifyObservers(new Float(price));
  }
}

----------------------------------------------------------------------------------------------------


An observer of name changes.
public class NameObserver implements Observer
{
  private String name;
  public NameObserver()
 {
    name = null;
    System.out.println("NameObserver created: Name is " + name);
  }
  public void update(Observable obj, Object arg)
  {
    if (arg instanceof String)
    {
      name = (String)arg;
      System.out.println("NameObserver: Name changed to " + name);
    }
    else
    {
      System.out.println("NameObserver: Some other change to subject!");
     }
   }
}

// An observer of price changes.
public class PriceObserver implements Observer
{
  private float price;
  public PriceObserver()
  {
    price = 0;
    System.out.println("PriceObserver created: Price is " + price);
  }
  public void update(Observable obj, Object arg)
  {
    if (arg instanceof Float)
    {
      price = ((Float)arg).floatValue();
      System.out.println("PriceObserver: Price changed to " + price);
    }
    else
    {
      System.out.println(”PriceObserver: Some other change to subject!");
    }
  }
}

----------------------------------------------------------------------------------------------------

// Test program for ConcreteSubject, NameObserver and PriceObserver
public class TestObservers
{
    public static void main(String args[])
    {
        // Create the Subject and Observers.
        ConcreteSubject s = new ConcreteSubject("Corn Pops", 1.29f);
        NameObserver nameObs = new NameObserver();
        PriceObserver priceObs = new PriceObserver();
        // Add those Observers!
        s.addObserver(nameObs);
        s.addObserver(priceObs);
        // Make changes to the Subject.
        s.setName("Frosted Flakes");
        s.setPrice(4.57f);
        s.setPrice(9.22f);
        s.setName("Sugar Crispies");
    }
}

Test program output
    ConcreteSubject created: Corn Pops at 1.29
    NameObserver created: Name is null
    PriceObserver created: Price is 0.0
    PriceObserver: Some other change to subject!
    NameObserver: Name changed to Frosted Flakes
    PriceObserver: Price changed to 4.57
    NameObserver: Some other change to subject!
    PriceObserver: Price changed to 9.22
    NameObserver: Some other change to subject!
    PriceObserver: Some other change to subject!
    NameObserver: Name changed to Sugar Crispies



Wednesday, September 7, 2011

MEF introduction

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.

You can download it from here: http://mef.codeplex.com/

AddReference1.JPG

Lets start with what MEF is not another DI (dependency injection), you should think of MEF as plug-ins infrastructure rather then being DI.

MEF is very friendly plug-ins framework which help you to get greater extensibility with less efforts and more consistency. It is very simple decoration module which having supper light dependencies.I hope you find this post useful, I'm having intensions to write future post which will cover the MEF in more details including some advance technique.

MEF presents a simple solution for the runtime extensibility problem. Until now, any application that wanted to support a plugin model (a piece of software which enhances another software application and usually cannot be run independently) needed to create its own infrastructure from scratch. Those plugins would often be application-specific and could not be reused across multiple implementations.
  • 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 additonal metadata which facilitates rich querying and filtering

How does MEF work?

Roughly speaking, MEF's core is comprised of a catalog and a CompositionContainer. A catalog is responsible for discovering extensions and the container coordinates creation and satisfies dependencies.
  • MEF's first-class citizen is a ComposablePart (see Parts below). A composable part offers up one or more Exports, and may also depend on one or more externally provided services or Imports. A composable part also manages an instance, which can be an object instance of a given type (it is in the default MEF implementation). MEF, however, is extensible and additonal ComposablePart implementations can be provided as long as they adhere to the Import/Export contracts.
  • Exports and imports each have a Contract. Contracts are the bridge between exports and imports. An export contract can consist of further metadata that can be used to filter on its discovery. For example, it might indicate a specific capability that the export offers.
  • MEF's container interacts with Catalogs to have access to composable parts. The container itself resolves a part's dependencies and exposes Exports to the outside world. You're free to add composable part instances directly to the container if you wish.
  • A ComposablePart returned by a catalog will likely be an extension to your application. It might have Imports (dependencies) on components the host application offers, and it's likely to Export others.
  • The default MEF composable part implementation uses attribute-based metadata to declare exports and imports. This allows MEF to determine which parts, imports, and exports are available completely through discovery.
MEF_Diagram.png

Composable Parts

A Composable Part is a composable unit within MEF. Composable Parts export services that other Composable Parts need, and import services from other Composable Parts. In the MEF programming model, Composable Parts are attributed with the System.ComponentModel.Composition.Import and [System.ComponentModel.Composition.Export] attribute in order to declare their exports and imports. A Composable Part should contain at least one export. Composable Parts are either added to the container explicity or created through the use of catalogs. The default catalogs that MEF ship with identify Composable Parts through the presence of an export attribute.

Contracts

Composable Parts do not directly depend on one another, instead they depend on a contract, which is a string identifier. Every export has a contract, and every import declares the contract it needs. The container uses the contract information to match up imports to exports. If no contract is specified, MEF will implicitly use the fully qualified name of the type as the contract. If a type is passed, it will also use the fully qualified name.

Note: By default a type should be passed for a contract, and not a string. Although contracts can be an arbitrary string this can lead to ambiguity. For example "Sender" might overlap with another implementation of "Sender" in a different library. For this reason if you do need to specify a string constract, it is recommend that contract names should be qualified with a namespace that includes the Company Name for example "Contoso.Exports.Sender".

In the code snippet below, all export contracts are equivalent.
namespace MEFSample 
{
  [Export]
  public class Exporter {...}

  [Export(typeof(Exporter))]
  public class Exporter1 {...}

  [Export("MEFSample.Exporter")]
  public class Exporter2 {...}
}
Namespace MEFSample
    <Export()>
    Public Class Exporter
        ... 
    End Class
    <Export(GetType(Exporter))> 
    Public Class Exporter1
        ... 
    End Class
    <Export("MEFSample.Exporter")>
    Public Class Exporter2
        ... 
    End Class
End Namespace


Contract Assemblies

A common pattern when building extensible applications with MEF is to deploy a contract assembly. A contract assembly is simply an assembly which contains contract types that extenders can use for extending your app. Commonly these will be interfaces, but they may be abstract classes. Additonally contract assemblies will likely contain metadata view interfaces that importers will use, as well as any custom MEF export attributes.
Note: You must specify the specific interface type (IMessageSender) being exported otherwise the type (EmailSender) itself will be exported.


Declaring Imports

Composable Parts declare imports [System.ComponentModel.Composition.ImportAttribute] attribute. Similar to exports, there are several different methods namely through Fields, Properties and Constructor Parameters.

Property Imports

To import a value to a property, decorate the property with the [System.ComponentModel.Composition.ImportAttribute]. For example the snippet below imports an IMessageSender

class Program
  {
    [Import]
    public IMessageSender MessageSender { get; set; }
  }
Class Program
    <Import()>
    Public Property MessageSender() As IMessageSender
End Class


Constructor Parameters

You can also specify imports through constructor parameters. This means that instead of adding properties for each import, you add parameters to a constructor for each import. To use this, follow the following steps.

1. Add a [System.ComponentModel.Composition.ImportingConstructorAttribute] attribute to the constructor that should be used by MEF.
2. Add parameters to the constructor for each import.

For example the code below imports a message sender in the constructor of the Program class.

class Program
  {
    [ImportingConstructor]
    public Program(IMessageSender messageSender) 
    {
       ...
    }
  }
Class Program
    <ImportingConstructor()>
    Public Sub New(ByVal messageSender As IMessageSender) 
      ... 
    End Sub
End Class

Parameter imports

There are several different different ways to define imports on the constructor.

1. Implied import - By default the container will use the type of the parameter to identify the contract. For example in the code below, the IMessageSender contract will be used.

class Program
  {
    [ImportingConstructor]
    public Program(IMessageSender messageSender) 
    {
    }
  }
Class Program
    <ImportingConstructor()>
    Public Sub New(ByVal messageSender As IMessageSender) 
    End Sub
End Class

2. Explicit import - If you want to specify the contract to be imported add an [System.ComponentModel.Composition.ImportAttribute] attribute to the parameter.

Field Imports

MEF also supports importing values directly to fields.

class Program
  {
    [Import]
    private IMessageSender _messageSender;
  }
Class Program
    <Import()>
    Private _messageSender As IMessageSender
End Class

Note: note that importing or exporting private members (fields, properties and methods) while supported in full trust is likely to be problematic on medium/partial trust.

Importing collections

In addition to single imports, you can import collections with the ImportMany attribute. This means that all instances of the specific contract will be imported from the container.

MEF parts can also support recomposition. This means that as new exports become available in the container, collections are automatically updated with the new set. For example below the Notifier class imports a collection of IMessageSender. This means if there are 3 exports of IMessageSender available in the container, they will be pushed in to the Senders property during compositon.

public class Notifier 
 {
    [ImportMany(AllowRecomposition=true)]
    public IEnumerable<IMessageSender> Senders {get; set;}

    public void Notify(string message) 
    {
      foreach(IMessageSender sender in Senders)
      {
        sender.Send(message);
      }
    } 
  }
Public Class Notifier
    <ImportMany(AllowRecomposition:=True)> 
    Public Property Senders() As IEnumerable(Of IMessageSender) 

    Public Sub Notify(ByVal message As String) 
        For Each sender As IMessageSender In Senders
            sender.Send(message) 
        Next sender
    End Sub
End Class
EXAMPLE:
 
using.JPG
 
We implement two classes in our namespace MEFIntro. They are as follows:
 
  1. Program (Listing 1)
  2. SimpeHello (Listing 2)
Dependencies in MEF are provided using attributes. There are two basic attributes.
They are Import and Export. If you look at Program class in Listing 1, 
you can figure out that, its string Property message should be importing 
some string. It doesn’t specify what would be the source of this import. 
Now in Listing 2, SimpleHello exports some string property. 
Some other component might need this property. In our example, this is 
Program class. So it is apparent that both these classes depend on each other. 
Now if we just follow cowboy coding, we would directly instantiate 
MyHello in Program class and use MyHello.Message property to populate 
its own Message property. But, with MEF, we don’t need to do that. 
This is because MEF takes care of injecting the dependencies.
To determine the dependencies between software components, 
catalogs are defined (Run method in Program class). 
Here we have used AssemblyCatalog. 
There may be more than one catalog of same or different types. 
There might be other catalogs too, like DirectoryCatalog, etc. 
After adding these catalogs in CompositionContainer, when we call ComposeParts 
method of the container, all dependencies are resolved. 
As you can see that when we call ComposeParts, 
string property Message in MyHello class (specified with Export attribute) 
is copied to the string property Message in Program class 
(specified with Import attribute).

Listing 1

Listing 2

Wednesday, August 3, 2011

Designing the Components of an Application or Service


Component Types

An examination of most business solutions based on a layered component model
reveals several common component types. Figure 2.1 shows these component types
in one comprehensive illustration.
Note: The term component is used in the sense of a piece or part of the overall solution. This
includes compiled software components, such as Microsoft .NET assemblies, and other
software artifacts such as Web pages and Microsoft® BizTalk® Server Orchestration schedules.
Although the list of component types shown in Figure 2.1 is not exhaustive, it
represents the common kinds of software components found in most distributed
solutions. These component types are described in depth throughout the remainder
of this chapter.


Figure 2.1

The component types identified in the sample scenario design are:
1. User interface (UI) components. Most solutions need to provide a way for users
to interact with the application. In the retail application example, a Web site lets
customers view products and submit orders, and an application based on the
Microsoft Windows® operating system lets sales representatives enter order data
for customers who have telephoned the company. User interfaces are implemented
using Windows Forms, Microsoft ASP.NET pages, controls, or any other
technology you use to render and format data for users and to acquire and
validate data coming in from them.

2. User process components. In many cases, a user interaction with the system
follows a predictable process. For example, in the retail application you could
implement a procedure for viewing product data that has the user select a
category from a list of available product categories and then select an individual
product in the chosen category to view its details. Similarly, when the user
makes a purchase, the interaction follows a predictable process of gathering data
from the user, in which the user first supplies details of the products to be purchased,
then provides payment details, and then enters delivery details. To help
synchronize and orchestrate these user interactions, it can be useful to drive the
process using separate user process components. This way the process flow and
state management logic is not hard-coded in the user interface elements themselves,
and the same basic user interaction “engine” can be reused by multiple
user interfaces.

3. Business workflows. After the required data is collected by a user process, the
data can be used to perform a business process. For example, after the product,
payment, and delivery details are submitted to the retail application, the process
of taking payment and arranging delivery can begin. Many business processes
involve multiple steps that must be performed in the correct order and orchestrated.
For example, the retail system would need to calculate the total value of
the order, validate the credit card details, process the credit card payment, and
arrange delivery of the goods. This process could take an indeterminate amount
of time to complete, so the required tasks and the data required to perform them
would have to be managed. Business workflows define and coordinate longrunning,
multi-step business processes, and they can be implemented using
business process management tools such as BizTalk Server Orchestration.

4. Business components. Regardless of whether a business process consists of a
single step or an orchestrated workflow, your application will probably require
components that implement business rules and perform business tasks. For
example, in the retail application, you would need to implement the functionality
that calculates the total price of the goods ordered and adds the appropriate
delivery charge. Business components implement the business logic of the
application.

5. Service agents. When a business component needs to use functionality provided
in an external service, you may need to provide some code to manage the semantics
of communicating with that particular service. For example, the business
components of the retail application described earlier could use a service agent
to manage communication with the credit card authorization service, and use a
second service agent to handle conversations with the courier service. Service
agents isolate the idiosyncrasies of calling diverse services from your application,
and can provide additional services, such as basic mapping between the
format of the data exposed by the service and the format your application
requires.

6. Service interfaces. To expose business logic as a service, you must create service
interfaces that support the communication contracts (message-based communication,
formats, protocols, security, exceptions, and so on) its different consumers
require. For example, the credit card authorization service must expose a service
interface that describes the functionality offered by the service and the required
communication semantics for calling it. Service interfaces are sometimes referred
to as business facades.

7. Data access logic components. Most applications and services will need to
access a data store at some point during a business process. For example, the
retail application needs to retrieve product data from a database to display
product details to the user, and it needs to insert order details into the database
when a user places an order. It makes sense to abstract the logic necessary to
access data in a separate layer of data access logic components. Doing so centralizes
data access functionality and makes it easier to configure and maintain.

8. Business entity components: Most applications require data to be passed between
components. For example, in the retail application a list of products must
be passed from the data access logic components to the user interface components
so that the product list can be displayed to the users. The data is used to
represent real-world business entities, such as products or orders. The business
entities that are used internally in the application are usually data structures,
such as DataSets, DataReaders, or Extensible Markup Language (XML) streams,
but they can also be implemented using custom object-oriented classes that
represent the real-world entities your application has to work with, such as a
product or an order.

9. Components for security, operational management, and communication: Your
application will probably also use components to perform exception management,
to authorize users to perform certain tasks, and to communicate with other
services and applications. These components are discussed in detail in Chapter 3,
“Security, Operational Management, and Communications Policies.”