Thursday, March 6, 2014

What is an interface and why do we need it?

This is a quite common interview question. Many a time candidates escape this question by giving the definition of an interface. “Interface is a contract which mandates implementation of the contractual methods”. Some also say “Interface is the way by which we can realize multiple inheritances”.
The above said definitions and explanation stands true; but interfaces are not just that. It plays a major role in design of systems.  Let us see what is it capable of.
Interface is a contract
This statement is directly taken from the above mentioned definition. But the question to be asked is “Why should we abide to that contract?” or “Why should we implement an interface.
Let us take an example. We are familiar with the interface “IEnumerable”. We also know that this interface needs to be implemented if a class has to qualify as a custom collection or collection iteratable by “foreach” statement. Thus the contract is enforced by the “foreach” statement and if we have to use foreach against our custom collection; we have to implement IEnumerable.
By this the “foreach” is acting against abstracts and it would look for the methods/properties in the candidate class to go ahead with the “iterate” operation. Thus other functionalities of the custom class is really not a concern for “foreach”.
As an example let us build a simple validation engine. Let us assume that the validation engine runs on multiple rules
The validation Engine will perform the following operations on the rules
  1. Execute validation rules in particular order
  2. Collate all failures and throw error.
Let us define the validation rule contract as follows
  public interface IValidationRule  
   {  
     short Order { get; }  
     string ErrorMessage { get; }  
     bool Validate(Entity subject);  
   }  

And Validation Engine as
 public class ValidationEngine  
   {  
     private readonly IEnumerable<IValidationRule> _validationRules;  
     public ValidationEngine(IEnumerable<IValidationRule> validationRules)  
     {  
       _validationRules = validationRules;  
     }  
     public void Validate(Entity subject)  
     {  
       var failedMessages = new List<string>();  
       foreach (var rule in _validationRules.OrderBy(ru => ru.Order))  
       {  
         var validationResult = rule.Validate(subject);  
         if (validationResult) continue;  
         failedMessages.Add(rule.ErrorMessage);  
       }  
       if (failedMessages.Any())  
       {  
         throw new ValidationFailedException(failedMessages);  
       }  
     }  
   }  

Validation engine expects the rules to be injected as collections and on invoking the Validate method with the “Entity”payload, it iterates through all rules and executes each of them. On failure the message is added to a collection. In the end of iteration, if there are any failure an exception is thrown.
Entity (Validation payload) defined as
  public class Entity  
   {  
     public string Property1 { get; set; }  
     public int NumericProperty { get; set; }  
   }  

Let us define the exception as .
 public class ValidationFailedException:Exception  
   {      
     public ValidationFailedException( IList<string> failedRules)  
     {  
       Failures = failedRules;  
     }  
     public IList<string> Failures { get; private set; }  
     public override string Message  
     {  
       get  
       {  
         return "Validation failed. See Failures property for details";  
       }  
     }  
   }  

Sample rules as
1. A rule to validate Property1
 public class Property1RequiredRule :IValidationRule  
   {  
     public Property1RequiredRule()  
     {  
       Order = 1;  
       ErrorMessage = "Property1 is a required field";  
     }  
     public short Order  
     {  
       get;  
       private set;  
     }  
     public string ErrorMessage  
     {  
       get;  
       private set;  
     }  
     public bool Validate(Entity subject)  
     {        
       return !string.IsNullOrEmpty(subject.Property1);        
     }      
   }  

2. A rule to validate NumericProperty
 public class NumericPropertyShouldBePostiveRule:IValidationRule  
   {  
     public NumericPropertyShouldBePostiveRule()  
     {  
       Order = 2;  
       ErrorMessage = "NumericProperty should be positive";  
     }  
     public short Order  
     {  
       get;  
       private set;  
     }  
     public string ErrorMessage  
     {  
       get;  
       private set;  
     }  
     public bool Validate(Entity subject)  
     {  
       return subject.NumericProperty >= 0;        
     }      
   }  

And we shall invoke the engine as
 class Program  
   {  
     static void Main(string[] args)  
     {  
       var validationRules = new List<IValidationRule> { new Property1RequiredRule(), new NumericPropertyShouldBePostiveRule() };  
       var subjectEntity = new Entity { NumericProperty = -3 };  
       try  
       {  
         var validationEngine = new ValidationEngine(validationRules);  
         validationEngine.Validate(subjectEntity);  
       }  
       catch (ValidationFailedException ex)  
       {  
         Console.WriteLine(ex.Message);  
         foreach (var failureMessage in ex.Failures)  
         {  
           Console.WriteLine(failureMessage);  
         }  
       }  
       Console.Read();  
     }  
   }  

Validation engine works against abstracts which implements IValidationRule. Validation engine or the validation altogether does not change for adding or altering rules. Adding a new rule is as simple as create a new class and make it implement IValidationRule and add the new class to the engine. Thus the validation engine is extensible.
Multiple Inheritances is supported by interfaces.
Let us change the validation engine a bit. We would ask the engine to execute some action before and after validation. There will be only certain rules which would requires either post or pre operations. Some rule may require both these actions implemented.
Let us call these methods as PreAction and PostAction. We cannot add these methods to IValidationRule because only certain rules need these operations. We shall segregate these methods into two different contracts viz; IPreActionRule and IPostActionRule.
 public interface IPreActionRule  
   {  
     void Action();  
   }  
 public interface IPostActionRule  
   {  
     void Action();  
   }  

Validation engine after introducing pre and post action
 public class ValidationEngine  
   {  
     private readonly IEnumerable _validationRules;  
     public ValidationEngine(IEnumerable validationRules)  
     {  
       _validationRules = validationRules;  
     }  
     public void Validate(Entity subject)  
     {  
       var failedMessages = new List<string>();  
       foreach (var rule in _validationRules.OrderBy(ru => ru.Order))  
       {  
         var preActionable = rule as IPreActionRule;          
         if (null != preActionable) preActionable.Action();  

         var validationResult = rule.Validate(subject);  
         var postActionable = rule as IPostActionRule;  

         if (null != postActionable) postActionable.Action();  
         if (validationResult) continue;  
         failedMessages.Add(rule.ErrorMessage);  
       }  
       if (failedMessages.Any())  
       {  
         throw new ValidationFailedException(failedMessages);  
       }  
     }  
   }  

Every rule has to implement IValidationRule and optionally if the rule has to operate Pre/Post action then those rules has to implement IPreActionRule/IPostActionRule.
Let us modify the rules to accommodate pre and post operation.
1. Property1RequiredRule requires only post operation to be performed
 public class Property1RequiredRule :IValidationRule,IPostActionRule  
   {  
     public Property1RequiredRule()  
     {  
       Order = 1;  
       ErrorMessage = "Property1 is a required field";  
     }  
     public short Order  
     {  
       get;  
       private set;  
     }  
     public string ErrorMessage  
     {  
       get;  
       private set;  
     }  
     public bool Validate(Entity subject)  
     {  
       Console.WriteLine("Validating Property1RequiredRule");  
       return !string.IsNullOrEmpty(subject.Property1);        
     }  
     public void PostAction()  
     {  
       Console.WriteLine("Executing Post Action within Property1RequiredRule");  
     }  
   }  

2. NumericPropertyShouldBePositiveRule requires only pre-action
 public class NumericPropertyShouldBePostiveRule:IValidationRule,IPreActionRule  
   {  
     public NumericPropertyShouldBePostiveRule()  
     {  
       Order = 2;  
       ErrorMessage = "NumericProperty should be positive";  
     }  
     public short Order  
     {  
       get;  
       private set;  
     }  
     public string ErrorMessage  
     {  
       get;  
       private set;  
     }  
     public bool Validate(Entity subject)  
     {  
       Console.WriteLine("Validating NumericPropertyShouldBePostiveRule");  
       return subject.NumericProperty >= 0;        
     }  
     public void PreAction()  
     {  
       Console.WriteLine("Executing PreAction with in NumericPropertyShouldBePositiveRule");  
     }  
   }  

In the end Validation engine uses contracts IValidationRule, IPreActionRule and IPostActionRule for validation. Who ever want to use validation engine should abide to those above mentioned contracts.

Hope the post helps in understanding how interfaces are used to program against abstracts and the role it plays in building frameworks.

Monday, August 24, 2009

Using MVC pattern in Javascript

In this Web 2.0 world, Javascripts plays a major role. We used to write heavy codes using JavaScript's and most of the time the JavaScripts slips from our hand out of control. We are much excited with the new web frame work from Mircosoft, the 'ASP.NET MVC'. The ASP.NET MVC provides us much better control on the code and the behaviours.

How about implementing 'Separation of Concerns' in JavaScript file also. Mattias Jakobsson has written a wonderful post on implementing MVC in JavaScript. Read it here. Am gonna use it in my projects.

Friday, August 21, 2009

WCF a Developers look

Service Orientation has changed the way the software is being developed now. It's not just the change in the development; it has brought out an out change in the way the applications are used. Now we can communicate with any system in any island using the Service Oriented Communication…well well if the applications are SOA complaint

What is a Service?

Services are autonomous applications which can expose some functionality to other systems through standard protocols. A service can be consumed in a host application by abiding the contract provided by the service.

Lets try to understand what it is.

What do we do if we have to subscribe to a Mobile communication service?

We abide a contract with the service provider. The contract may include

  1. Type of the service
  2. The usage plan
  3. The extra usage plan
  4. The defaulting penalty
Once we sign the contract, we start getting the service and it continues until we follow the contract. We use the service, but are not known with the intricacies of the operation of the service provider.

Like this in Service Orientation, if we are in need of a particular service; we agree with the contract provided by the service. The service might be running at a remote location, but still it would be the part of our system and the actions are hidden from the host.

Service Orientation is implemented using public standards if the applications are in different platforms or proprietary standards if the applications are of the same platforms. Web Service implemented using SOAP protocol is an example for public standards. And Remoting, CORBA etc are examples for proprietary standards.

The concepts are the same, but based on our choice we have to opt among public / proprietary techniques. The implementation and the development are different for both the techniques. How would it be, if we are given with single development method but multiple options (public / proprietary) for implementation? Windows Communication Foundation does exactly that. The development for the services is unified but WCF provides us the multiple options for consumption using the configuration.

The service oriented application development goes this way

  1. Service Contract Creation
  2. Service Implementation
  3. Service Hosting
  4. Service Consumption
Let's now write a WCF service. The steps to be followed are

  1. Define a service Contract
  2. Implement the service contract
  3. A host process to run the services
  4. Endpoint configuration in the client to access the service
We are going to create a simple arithmetic operation service, which would be hosted as normal webservice

The Service Contract






using System;
using System.Runtime.Serialization;
using System.ServiceModel;
namespace SampleService
{
    [ServiceContract]
    public interface IArithematicOperation
    {
        [OperationContract]
        int add(int first, int second);
        [OperationContract]
        int Substract(int first, int second);
    }
}



In Object Orientated programming, the Interfaces are used for defining the contracts. The contract definition using the interfaces and the implementation using the concrete classes is referred to as contact-first style.

When we mark a class with 'ServiceContract' and the methods as 'OperationContract', the service contract definitions is automatically generated in WSDL.

Now we have to implement the contract.

The Service Implementation







using System;
using System.ServiceModel;
namespace SampleService
{
    public class ArithematicOperationService : IArithematicOperation
    {
        public int add(int first, int second)
        {
            return first + second;
        }
        public int Substract(int first, int second)
        {
            return first - second;
        }
    }
}

The service implementation is straight forward and the class implements all the methods mentioned in the service contract

Hosting Options in WCF

Windows Communication Foundation again gives us choices for hosting the services. The services could be hosted in any of these

  1. IIS
  2. Windows Process Activation Services (WAS) – In Windows Vista or Windows Server 2008
  3. Self Hosting (Any managed .NET application, including WWF, winForm application, Windows Process, Console Applications)
We are now going to host our service in IIS. The IIS hosting is quite simple.

We need to have a virtual directory created in the IIS. Copy the dlls to the virtual directory (Bin folder). We now have to create the host. Open note pad and type the following

<%@ServiceHost language=c# Service="SampleService.ArithematicOperationService" %>

Save the file as ArithematicOperation.svc in the virtual directory

The hosted services have to be exposed through the endpoints in the configuration file. The endpoints are referred as the ABC of the WCF. The endpoint defines

The Address: URLs that identify the machine and the endpoint

The Binding: Determines how these endpoints are accessed. Depending upon the binding the schema of the URL also would be changed.

The Contract: The name of the class/interface which this endpoint exposes. The class/interface should be the one which is decorated with ServiceContract attribute.

In the beginning I mentioned, WCF provides single way of development and multiple ways for hosting and accessing. The endpoint bindings allows us to consume the same service in different protocols viz, webservices, Message Queues and Remoting. Moreover we could also develop our own custom bindings.

Among the WCF bindings most important are the following:

  • BasicHttpBinding: Conforms to the Web Services Interoperability Organization (WS-I) Basic Profile 1.0, which specifies SOAP over HTTP. This binding can also be configured to use HTTPS as specified by the WS-I Basic Security Profile 1.0. It can also be configured to send either standard text or the optimized form defined by MTOM.
  • WsHttpBinding: Uses SOAP over HTTP, like BasicProfileBinding, but also supports reliable message transfer with WS-ReliableMessaging, security with WS-Security, and transactions with WS-AtomicTransaction. This binding allows interoperability with other Web services implementations that also support these specifications.
  • NetTcpBinding: Sends binary-encoded SOAP, including support for reliable message transfer, security, and transactions, directly over TCP. This binding can be used only for WCF-to-WCF communication.
  • WebHttpBinding: Sends information directly over HTTP or HTTPS—no SOAP envelope is created. This binding is new with the .NET Framework 3.5 version of WCF, and it's the right choice for RESTful communication and other situations where SOAP isn't required. The binding offers three options for representing content: text-based XML encoding, JavaScript Object Notation (JSON) encoding, and opaque binary encoding.
  • NetNamedPipesBinding: Sends binary-encoded SOAP over named pipes. This binding is only usable for WCF-to-WCF communication between processes on the same Windows-based machine.
  • NetMsmqBinding: Sends binary-encoded SOAP over MSMQ, as described later in this paper. This binding can only be used for WCF-to-WCF communication.
Lets define the endpoints in the web.config file



<?xml version="1.0"?>
<configuration>
  <system.serviceModel>
    <services>
      <service  name="SampleService.ArithematicOperationService" behaviorConfiguration="MyServiceTypeBehaviors">
        <endpoint
          contract="SampleService.IArithematicOperation"
          binding="basicHttpBinding"
          address=
            "http://localhost/wcfSampleService/ArithematicOperation.svc"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="MyServiceTypeBehaviors" >
          <serviceMetadata httpGetEnabled="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

We have developed the service and hosted it in IIS with required endpoint access. Now we will develop a client to consume the service.

Create a console application, add the service reference as http://localhost/wcfSampleService/ArithematicOperation.svc and specify the service namespace as 'ArithematicOperation'. This activity would create the necessary proxy classes for the service. In the Main() method write the following code






namespace ServiceTest
{
    class Program
    {
        static void Main(string[] args)
        {
            ArithematicOperations.ArithematicOperationClient obj = new ServiceTest.ArithematicOperations.ArithematicOperationClient();
            Console.WriteLine("The Service result for Add={0}" ,obj.add(10, 20));
            Console.WriteLine("The Service result for Substarction={0}",obj.Substract(20, 10));
            Console.Read();
        }
    }
}

Voilaaa!!! We've done with our service consumption also.

We just covered the basics of the WCF services. In the future post I would cover the some more basics and advanced topics related to the WCF services.