menu

Sunday, August 28, 2016

Sunday, July 24, 2016

IOC (Inversion of Control)

An entity must concern to its own logic and all unconcerned logic should put inside any other external logic.

Design Patterns

Factory Pattern - Creational Pattern - Remove lots of scattered new keywords by introducing a factory class, and stop exposing our concrete classes by introducing a base interface type.

Abstract Factory Pattern - Creational Pattern – It is an extension of factory pattern, in case we have lots of similar kind of factory pattern classes in to one interface.

Builder Pattern - Creational Pattern - Helps if construction process of an object (Invoice) is complex and do I need to separate construction from its representation. It has 3 component.
Builder - Defines the construction of individual parts.
Director - Takes those individual part from builder and define the sequence to build the product.
Product - is the final object. Ex. construction of Tea object like Tea without sugar and tea without milk.

Prototype Pattern - Creational Pattern - Helps us to give a way to create a clone object from existing object. There are 2 type of cloning.
1.  Shallow cloning - When only parent object is being cloned.
2.  Deep cloning - When with parent, its aggregated child objects are also need to be cloned.
Adaptor Pattern - Structural Pattern - Helps us in case of 2 class types are incompatible because of its incompatible interface. These are of 2 type.
1.   Class Adaptor Pattern –
2.  Object Adaptor Pattern –
Collection classes have Add() and Stack class have Push(), here both are doing same thing but Add and Push are not compatible.

Bridge Pattern - Structural Pattern - Helps to decouple abstraction from its implementation.
Composite Pattern - Structural Pattern - Helps to treat different type of objects in uniform manner.
Decorator Pattern – Structural Pattern – Are nothing but the inheritance.

Proxy Pattern – Structural Pattern – Helps in making available heavy object or sensitive object throughout network by sharing parent interface ref object rather than actual object (Web & WCF Service Client).

Template Pattern – Structural Pattern – Helps in generalising something by using abstract class and make specific type by inheriting abstract class. Here abstract class will be like template for all its derived class.

Mediator Pattern – Behavioural Pattern – Helps in communicating component (purchase, payment, checkout etc.) in a loosely coupled manner. Move communication logic from component to mediator.


Iterator Pattern – Behavioural Pattern – Helps by allowing sequential access of element without exposing the inside code.

SOLID Principles

Is first five object oriented design (OOD) principle given by Robert C. Martin.

S – Single responsibility principle – A class should have one reason to change. Means a class must have only responsibilities related to it.

O – Open-closed principle – Extension should be preferred over modifications. Classes & functions should be open for extension but close for modifications (by sub classing & virtual functions).

L – Liskov substitution principle – Parent type should easily replace its child types (Polymorphism).

I – Interface segregation principle – Means, share only those functionality to clients whichever they want and introduce another more functionalities for new client without affecting old clients.

D – Dependency Inversion Principle – Depending on abstraction not on concretion.
• High-level modules should not depend on low-level modules. Both should depend on abstractions.
• Abstractions should not depend on details. Details should depend on abstractions. 

Sunday, June 19, 2016

Async Function in WCF Service

Below are the classes and interface to host a service

ICalc.cs
using System;
using System.ServiceModel;
namespace ConsoleService
{
    [ServiceContract]
    interface ICalc
    {
        [OperationContract(AsyncPattern = true)]
        IAsyncResult BeginAdd(int a, int b, AsyncCallback callback, object asyncState);
        int EndAdd(IAsyncResult result);

        [OperationContract]
        int Sub(int a, int b);
    }

}

Calc.cs
using System;
namespace ConsoleService
{
    class Calc : ICalc
    {
        Func<int, int, int> add = (n1, n2) => n1 + n2;
        public IAsyncResult BeginAdd(int a, int b, AsyncCallback callback, object asyncState)
        {
            return add.BeginInvoke(a, b, callback, asyncState);
        }

        public int EndAdd(IAsyncResult result)
        {
            return add.EndInvoke(result);
        }

        public int Sub(int a, int b)
        {
            return a - b;
        }
    }

}

Service.cs
using System;
using System.ServiceModel;
using System.ServiceModel.Description;
namespace ConsoleService
{
    class Service
    {
        static void Main(string[] args)
        {
            ServiceHost host = new ServiceHost(typeof(Calc), new Uri("http://localhost:8888/async"));
            host.Description.Behaviors.Add(new ServiceMetadataBehavior() { HttpGetEnabled = true });
            host.Open();
            Console.Title = "Async Service";
            Console.ReadKey();
        }
    }
}

Below is the class which have the code to access the service

Client.cs
using System;
namespace ConsoleClient
{
    class Client
    {
        static void Main(string[] args)
        {
            ServiceAsync.CalcClient client = new ServiceAsync.CalcClient();
            Console.WriteLine(client.Add(2, 5));
            Console.ReadKey();
        }
    }

}

Saturday, June 11, 2016

WCF Service Console Host and Console Client

Below are the classes and interface to host a service

ICalculator.cs
using System;
using System.ServiceModel;
namespace Interface
{
    [ServiceContract]
    public interface ICalculator
    {
        [OperationContract]
        double Add(double num1, double num2);
        [OperationContract]
        double Subtract(double num1, double num2);
        [OperationContract]
        double Multiply(double num1, double num2);
        [OperationContract]
        double Devide(double num1, double num2);
    }
}

CalculatorService.cs
using System;
namespace Service
{
    public class CalculatorService : Interface.ICalculator
    {
        public double Add(double num1, double num2)
        {
            return num1 + num2;
        }
        public double Subtract(double num1, double num2)
        {
            return num1 - num2;
        }
        public double Multiply(double num1, double num2)
        {
            return num1 * num2;
        }
        public double Devide(double num1, double num2)
        {
            return num1 / num2;
        }
    }

}

Host.cs
using Interface;
using Service;
using System;
using System.ServiceModel;
namespace ConsoleHost
{
    class Host
    {
        static void Main(string[] args)
        {
            //ServiceHost host = new ServiceHost(typeof(CalculatorService));
            ServiceHost host = new ServiceHost(typeof(CalculatorService), new Uri("http://localhost:8888/test"));
            host.AddServiceEndpoint(typeof(ICalculator), new NetTcpBinding(), "net.tcp://localhost:8889/test");
            //host.AddServiceEndpoint(typeof(ICalculator), new WSHttpBinding(), "http://localhost:8888/test1");
            host.AddDefaultEndpoints();
            host.Open();

            Console.WriteLine("Listening at ...");
            int i = 0;
            foreach (var ep in host.Description.Endpoints)
            {
                Console.WriteLine("({0}) A: {1}, \tB: {2}, \tC: {3}", i, ep.Address, ep.Binding.Name, ep.Contract.Name);
                i++;
            }
            Console.WriteLine("Service is running ... Press any key to stop service.");
            Console.ReadKey();
            host.Close();
        }
    }
}

Below are the classes and configuration to access the above hosted service.

App.config
<xml version="1.0" encoding="utf-8" ?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <system.serviceModel>
    <client>
      <endpoint name="basicEP" address="http://localhost:8888/test" binding="basicHttpBinding" contract="Interface.ICalculator" />
      <endpoint name="netTcpEP" address="net.tcp://localhost:8889/test" binding="netTcpBinding" contract="Interface.ICalculator" />
    </client>
  </system.serviceModel>
</configuration>

Client.cs
using Interface;
using System;
using System.ServiceModel;
using System.ServiceModel.Description;
namespace ConsoleClient
{
    class Client
    {
        static void Main(string[] args)
        {
            /*
            ChannelFactory factory = new ChannelFactory();
            factory.Endpoint.Address = new EndpointAddress("http://localhost:8888/test");
            factory.Endpoint.Binding = new BasicHttpBinding();
            factory.Endpoint.Contract = ContractDescription.GetContract(typeof(ICalculator));
            */

            ChannelFactory<ICalculator> factory = new ChannelFactory<ICalculator>("netTcpEP"); //provide endpoint name defined in App.config
           
            ICalculator proxy = factory.CreateChannel();
            Console.WriteLine(proxy.Add(12, 22));
            Console.ReadKey();
        }
    }
}

Sunday, February 28, 2016

Monolithic vs Microservices Application Development Architecture

If we are developing a server side enterprise application for
  • Variety of client like Desktop Browser, Mobile Browser and Native Mobile Applications.
  • Exposing APIs for 3rd parties to consume.
  • It might also be able to integrate to other application via web services.
  • Application handles HTTP request and messages by executing business logic, accessing database exchanging data with other system and returning a HTML/XML/JSON response.
  • The application has a layered architecture and consists of different types of components like
    • Presentation components - responsible for handling HTTP requests and responding with either HTML or JSON/XML (for web services APIS)
    • Business logic - the application’s business logic
    • Database access logic - data access objects responsible for access the database
    • Application integration logic - messaging layer, e.g. based on Spring integration.


We have two kind of architecture to manage applications.

Monolithic Application 

When the application becomes larger then this approach many number of drawbacks …
  •  The application can be difficult to understand and modify resulting development goes slows down.
  • Larger the code base will slow down the IDE resulting the less productive developers.
  •  Overloaded web container, longer it takes to respond.
  • Continuous deployment is difficult because a minor update in any component resulting re-deploy whole application.
  • Scaling the application in terms of transaction volume is bit easy by running same code on multiple servers but scale with an increasing data volume is too difficult because all app instance will be accessing the same database.
  • Scaling the application in terms of development is also difficult, even if we divide team with their responsibilities. Because it prevent teams working independently, teams have to coordinate their development effort to each other.
  • Requires a long-term commitment to a technology stack - a monolithic architecture forces you to be married to the technology stack (and in some cases, to a particular version of that technology)


The microservices architecture is an alternative pattern that addresses the limitations of the monolithic architecture.

Microservices Application
Architect the application by applying the Scale Cube (specifically y-axis scaling)


X-axis scaling – consists of running multiple copies of an application behind a load balancer.

Y-axis scaling – splits the application into multiple, different services. Each service is responsible for one or more closely related functions. There are different ways of decomposing the application into services.
Use verb-based decomposition and define services that implement a single use case such as checkout.
Use noun-based decomposition and define services responsible for all operations related to a particular entity such as customer management.
An application might use a combination of verb-based and noun-based decomposition.

Z-axis scaling – splits are commonly used to scale databases. Data is partitioned across some servers. Like primary key of the table is used to partition the rows between two different database servers.

Benefits
  • Each server only deals with a subset of the data.
  • This improves cache utilization and reduces memory usage and I/O traffic.
  • It also improves transaction scalability since requests are typically distributed across multiple servers.
  • Z-axis scaling improves fault isolation since a failure only makes part of the data in accessible.

Drawbacks
  • It increases application complexity.


Benefits
  • Each microservice is relatively small
    • Easier for a developer to understand
    • The IDE is faster making developers more productive
    •  The web container starts faster, which makes developers more productive, and speeds up deployments
  • Each service can be deployed independently of other services and easier to deploy new versions of services frequently also.
  • Easier to scale development. Suppose there are multiple team working on different services then each team can develop, deploy and scale their service independently of all of the other teams.
  • Improved fault isolation. If there is a memory leak in one service then only that service will be affected. The other services will continue to handle requests.
  • Eliminates any long-term commitment to a technology stack. Because for new service we are free to be upgrade technology.

Drawbacks
  • Developers must deal with some complexities of creating a distributed system.
    • Testing is more difficult.
    • Developers must implement the inter-service communication mechanism.
  • Deployment complexity. In production, there is also the operational complexity of deploying and managing a system comprised of many different service types.
  • Increased memory consumption. The microservices architecture replaces N monolithic application instances with NxM services instances.