Search This Blog

Wednesday, 11 April 2018

Microservices Architecture vs Monolithic Architecture


Difficulties with monolithic application, when it grow 

  • Large monolithic code base makes complicated to understand, especially for new developer
  • Scaling become challenging
  • Continuously integration / deployment become complex and time consuming. You may require dedicated team for build and deploy
  • Overloaded IDE, Large code base makes IDE slow, build time increase.
  • Extremely difficult to change technology or language or framework because everything is tightly coupled and depend up on each other.
Privilege with Microservice architecture, when it grow 
  • Each microservice is small and focused on a specific feature / business requirement.
  • Microservice can be developed independently by small team of developers (normally 2 to 5 developers).
  • Microservice is loosely coupled, means services are independent, in terms of development and deployment both.
  • Microservice can be developed using different programming language (Personally I don't suggest to do it).
  • Microservice allows easy and flexible way to integrate automatic deployment with Continuous Integration tools (for e.g: Jenkins, Hudson, bamboo etc..). The productivity of a new team member will be quick enough.
  • Microservice allows you to take advantage of emerging and latest technologies (framework, programming language, programming practice, etc.).
  • Microservice is easy to scale based on demand. In a nutshell, monolithic vs microservice architecture is like elephant vs ant approach. What you wants to build a giant system like elephant or army of ant, small, fast and effective.

SOA vs Microservices Architecture



SOA MSA
Built on the idea of “share-as-much-as-possible” architecture approach Built on the idea of “share-as-little-as-possible” architecture approach
More importance on business functionality reuse More importance on the concept of “bounded context”
Common governance and standards Relaxed governance, with more focus on people collaboration and freedom of choice
Uses enterprise service bus (ESB) for communication Uses less elaborate and simple messaging system
Supports multiple message protocols Uses lightweight protocols such as HTTP/REST & AMQP
Common platform for all services deployed to it Application Servers not really used. Platforms such as Node.JS could be used
Multi-threaded with more overheads to handle I/O Single-threaded usually with use of Event Loop features for non-locking I/O handling
Use of containers (Dockers, Linux Containers) less popular Containers work very well in MSA
Maximizes application service reusability More focused on decoupling
Uses traditional relational databases more often Uses modern, non-relational databases
A systematic change requires modifying the monolith A systematic change is to create a new service
DevOps / Continuous Delivery is becoming popular, but not yet mainstream Strong focus on DevOps / Continuous Delivery

Friday, 11 December 2015

Dependency Injection

People are often confused about what Dependency Injection is and when they might need or want to use it. Some time ago I wrote an article Managing Dependency Injection in C# with Autofac which explains how to manage DI in C#, but today I want to show by simple code sample what actually Dependency Injection is.
Imaging situation where you have a class, let's say Employee, and two or more different loggers for that class. Each logger prints messages in his own particular way and you want to have control of which logger to use for Employee during its instantiation.
Just take a look at this code and I'm sure you will get the idea of Dependency Injection:

public class Employee
{
    public Employee(ILogger logger)
    {
        logger.WriteToLog("New employee created");
    }
}
public interface ILogger
{
    void WriteToLog(string text);
}
public class LoggerOne : ILogger
{
    public void WriteToLog(string text)
    {
        Console.WriteLine(text);
    }
}
public class LoggerTwo : ILogger
{
    public void WriteToLog(string text)
    {
        Console.WriteLine("***********\n {0}\n***********", text);
    }
}
Now let's instantiate an Employee with two different loggers:

Employee employee1 = new Employee(new LoggerOne());
Employee employee2 = new Employee(new LoggerTwo());
And the output:
New employee created
*******************
New employee created
*******************

The advantages of using Dependency Injection pattern and Inversion of Control are the following:

•Reduces class coupling

•Increases code reusing

•Improves code maintainability

•Improves application testing

Thursday, 10 December 2015

When interface and when abstract class

If you anticipate creating multiple versions of your component, create an abstract class. Abstract classes provide a simple and easy way to version your components. By updating the base class, all inheriting classes are automatically updated with the change. Interfaces, on the other hand, cannot be changed once created. If a new version of an interface is required, you must create a whole new interface.
    If the functionality you are creating will be useful across a wide range of disparate objects, use an interface. Abstract classes should be used primarily for objects that are closely related, whereas interfaces are best suited for providing common functionality to unrelated classes.
If you are designing small, concise bits of functionality, use interfaces. If you are designing large functional units, use an abstract class.
If you want to provide common, implemented functionality among all implementations of your component, use an abstract class. Abstract classes allow you to partially implement your class, whereas interfaces contain no implementation for any members.


Example(a very rudimentary one!):Consider a base class called Customer which has abstract methods like CalculatePayment(), CalculateRewardPoints() and some non-abstract methods like GetName(), SavePaymentDetails().

Specialized classes like RegularCustomer and GoldCustomer will inherit from the Customer base class and implement their own CalculatePayment() and CalculateRewardPoints() method logic, but re-use the GetName() and SavePaymentDetails() methods.

You can add more functionality to an abstract class(non abstract methods that is) without affecting child classes which were using an older version. Whereas adding methods to an interface would affect all classes implementing it as they would now need to implement the newly added interface members.

http://javarevisited.blogspot.in/2013/05/difference-between-abstract-class-vs-interface-java-when-prefer-over-design-oops.html

Method Overloading in c#.net

Method Overloading means to have two or more methods with same name in the same class with different arguments. The benefit of method overloading is that it allows you to implement methods that support the same semantic operation but differ by argument number or type.

Important Points

    Overloaded methods MUST change the argument list
    Overloaded methods CAN change the return type
    Overloaded methods CAN change the access modifier
    Overloaded methods CAN declare new or broader checked exceptions
    A method can be overloaded in the same class or in a subclass


You can not overload the function by differ only their return type . You can only overload the function in following ways

    Parameter types
    Number of parameters
    Order of the parameters declared in the method

You can not come to know which function is actually called (if it was possible).

One more thing I would like to add is function overloading is providing a function with the same name, but with a different signature. but the return type of a method is not considered as a part of method's signature.

using System;

namespace ProgramCall
{

    class Class1
    {

        public int Sum(int A, int B)
        {
            return A + B;
        }

        public float Sum(int A, float B)
        {
            return A + B;
        }
    }

    class Class2 : Class1
    {
        public int Sum(int A, int B, int C)
        {
            return A + B + C;

        }
    }

    class MainClass
    {
        static void Main()
        {

            Class2 obj = new Class2();

            Console.WriteLine(obj.Sum(10, 20));

            Console.WriteLine(obj.Sum(10, 15.70f));

            Console.WriteLine(obj.Sum(10, 20, 30));

            Console.Read();
        }

    }
}

Facade Pattern

Facade Pattern:
Facade pattern falls under Structural Pattern of Gang of Four (GOF) Design Patterns in .Net. The Facade design pattern is particularly used when a system is very complex or difficult to understand because system has a large number of interdependent classes or its source code is unavailable. In this article, I would like share what is facade pattern and how is it work?

What is facade Pattern:
Facade pattern hides the complexities of the system and provides an interface to the client using which the client can access the system.
This pattern involves a single wrapper class which contains a set of members which are required by client. These members access the system on behalf of the facade client and hide the implementation details.
The facade design pattern is particularly used when a system is very complex or difficult to understand because system has a large number of interdependent classes or its source code is unavailable.


In Factory pattern, we create object without exposing the creation logic. In this pattern, an interface is used for creating an object, but let subclass decide which class to instantiate. The creation of object is done when it is required. The Factory method allows a class later instantiation to subclasses.

Abstract factory pattern

Design patterns:

Design patterns are general reusable solutions to common problems that occurred in software designing. There are broadly 3 categories of design patterns, i.e., Creational, Behavioral and Structural.

Abstract factory pattern in very useful in GUI based applications where we need to create related GUI components. My example here is solely for the purpose of understanding and there is no way the "Cell-phone-information-system" be designed this way (otherwise we will end up adding new classes every week). Please do let me know if I missed something. Perhaps for the experienced guys this article is not very useful but it could really be useful for beginners.

It is used to create a set of related objects, or dependent objects. Internally, Abstract Factory use Factory design pattern for creating objects. It may also use Builder design pattern and prototype design pattern for creating objects. It completely depends upon your implementation for creating objects. 


What is Abstract Factory Pattern?
Abstract Factory patterns acts a super-factory which creates other factories. This pattern is also called as Factory of factories. In Abstract Factory pattern an interface is responsible for creating a set of related objects, or dependent objects without specifying their concrete classes.


When to use it?

    Create a set of related objects, or dependent objects which must be used together.
    System should be configured to work with multiple families of products.
    The creation of objects should be independent from the utilizing system.
    Concrete classes should be decoupled from clients.

Note:

    Internally, Abstract Factory use Factory design pattern for creating objects. But it can also use Builder design pattern and prototype design pattern for creating objects. It completely depends upon your implementation for creating objects.
    Abstract Factory can be used as an alternative to Facade to hide platform-specific classes.
    When Abstract Factory, Builder, and Prototype define a factory for creating the objects, we should consider the following points :
        Abstract Factory use the factory for creating objects of several classes.
        Builder use the factory for creating a complex object by using simple objects and a step by step approach.
        Prototype use the factory for building a object by copying an existing object.

Factory Method pattern

In Factory Method pattern, we create object without exposing the creation logic. In this pattern, an interface is used for creating an object, but let subclass decide which class to instantiate. The creation of object is done when it is required. The Factory method allows a class later instantiation to subclasses.



C# - Implementation Code

    interface Product
    {
    
    }
    
    class ConcreteProductA : Product
    {
    }
    
    class ConcreteProductB : Product
    {
    }
    
    abstract class Creator
    {
     public abstract Product FactoryMethod(string type);
    }
    
    class ConcreteCreator : Creator
    {
     public override Product FactoryMethod(string type)
     {
     switch (type)
     {
     case "A": return new ConcreteProductA();
     case "B": return new ConcreteProductB();
     default: throw new ArgumentException("Invalid type", "type");
     }
     }
    }

***************************************************************************************************************
Another C# - Implementation for FactoryMethod design pattern:

interface IIceCream


{


    string Functionality();


}


class ChocolateIceCream : IIceCream


{


    public string Functionality()


    {


        return "Chocolate Ice cream";


    }


}


class VanillaIceCream : IIceCream


{


    public string Functionality()


    {


        return "Vanilla Ice cream";


    }


}


class StrawberryIceCream : IIceCream { public string Functionality()


    {


        return "Strawberry Ice cream";


    }


}

This is the basic structure
of our program. Now we need to implement the "Factory Method", which
will create the instance of our desired ice-cream at run-time. So we
will create this method now.

This is how I’m going to do this.



static class Factory


{


   /// <summary>    /// This is the Factory method   

/// </summary>   

public static IIceCream Get(int id)


   {


       switch (id)


       {


           case 0:


                return new ChocolateIceCream();


           case 1:


                return new VanillaIceCream();


           case 2:


                return new StrawberryIceCream(); default:


                return null;


        }
   }
}



The Repository Pattern

The Repository Pattern

Context

In many applications, the business logic accesses data from data stores such as databases, SharePoint lists, or Web services. Directly accessing the data can result in the following:
  • Duplicated code
  • A higher potential for programming errors
  • Weak typing of the business data
  • Difficulty in centralizing data-related policies such as caching
  • An inability to easily test the business logic in isolation from external dependencies

Objectives

Use the Repository pattern to achieve one or more of the following objectives:
  • You want to maximize the amount of code that can be tested with automation and to isolate the data layer to support unit testing.
  • You access the data source from many locations and want to apply centrally managed, consistent access rules and logic.
  • You want to implement and centralize a caching strategy for the data source.
  • You want to improve the code's maintainability and readability by separating business logic from data or service access logic.
  • You want to use business entities that are strongly typed so that you can identify problems at compile time instead of at run time.
  • You want to associate a behavior with the related data. For example, you want to calculate fields or enforce complex relationships or business rules between the data elements within an entity.
  • You want to apply a domain model to simplify complex business logic.

Solution

Use a repository to separate the logic that retrieves the data and maps it to the entity model from the business logic that acts on the model. The business logic should be agnostic to the type of data that comprises the data source layer. For example, the data source layer can be a database, a SharePoint list, or a Web service.
The repository mediates between the data source layer and the business layers of the application. It queries the data source for the data, maps the data from the data source to a business entity, and persists changes in the business entity to the data source. A repository separates the business logic from the interactions with the underlying data source or Web service. The separation between the data and business tiers has three benefits:
  • It centralizes the data logic or Web service access logic.
  • It provides a substitution point for the unit tests.
  • It provides a flexible architecture that can be adapted as the overall design of the application evolves.

Monday, 19 May 2014

Build Vs Rebuild Vs Clean

Build means compile and link only the source files that have changed since the last build.
If they have not changed those files will not be touched.

while Rebuild means compile and link all source files regardless of whether they changed or not.
Rebuild will build everything from scratch, irrespective of if there is code change in the file or not.
Rebuild solution will clean and then build the solution from scratch.
Rebuild = Clean + Build

Clean Solution will delete all compiled files (i.e., EXE’s and DLL’s) from the bin/obj directory

Monday, 5 May 2014

Custom exception in sql server

RAISERROR can either reference a user-defined message stored in the sys.messages catalog view or build a message dynamically. The message is returned as a server error message to the calling application or to an associated CATCH block of a TRY…CATCH construct.

RAISERROR (N'This is message %s %d.', -- Message text.
           10, -- Severity,
           1, -- State,
           N'number', -- First argument.
           5); -- Second argument.
-- The message text returned is: This is message number 5.
GO

Monday, 28 April 2014

Razor View Engine

The Razor View Engine

ASP.NET MVC 3 comes with a new view engine named Razor that offers the following benefits:
  • Razor syntax is clean and concise, requiring a minimum number of keystrokes.
  • Razor is easy to learn, in part because it's based on existing languages like C# and Visual Basic.
  • Visual Studio includes IntelliSense and code colorization for Razor syntax.
  • Razor views can be unit tested without requiring that you run the application or launch a web server.
Some new Razor features include the following:
  • @model syntax for specifying the type being passed to the view.
  • @* *@ comment syntax.
  • The ability to specify defaults (such as layoutpage) once for an entire site.
  • The Html.Raw method for displaying text without HTML-encoding it.
  • Support for sharing code among multiple views (_viewstart.cshtml or _viewstart.vbhtml files).
Razor also includes new HTML helpers, such as the following:
  • Chart. Renders a chart, offering the same features as the chart control in ASP.NET 4.
  • WebGrid. Renders a data grid, complete with paging and sorting functionality.
  • Crypto. Uses hashing algorithms to create properly salted and hashed passwords.
  • WebImage. Renders an image.
  • WebMail. Sends an email message.

Thursday, 24 April 2014

WCF Self Hosting

Windows Communication Foundation (WCF) is a programming interface as part of .NET Framework.
Using three types we can host service in WCF:
  1. Self-Hosting
  2. IIS Hosting
  3. WAS

1. What is Self Hosting

WCF comes with System.ServiceModel.ServiceHost class that makes you can host your services in your own application easily. With Self Hosting what you need to do is just configuring your service endpoint and calling the .open() method of ServiceHost. To host WCF service you need WCF runtime and .NET application where you want to host your service.

2. What are the advantages and Disadvantages of Self hosting

Advantages of Self Hosting:
  • It is Easy: This way of hosting don’t need many lines of code to successfully run.
  • It is Flexible: You can easily decide when your service active by calling the .open() and .close() method.
Disadvantage of Self Hosting
This self-hosting service is reachable only when the application that hosts the service is running. So, self-hosting is only suitable when the development and demonstration phase of your system.
There are two main advantages of using IIS over self-hosting:
  • Automatic activation
  • Process recycling

3. What is ServiceHost in Self Hosting

  • A Service Host basically provides you everything you need to host a WCF service in a non-IIS or WAS setting. A common place for a ServiceHost would be in a console app or Windows service.
  • You can either instantiate a Service-Host class yourself in a console app, a Windows service, or even a Win-forms app, and thus make your WCF service class available to the outside world or you can delegate that work to IIS or WAS.
  • Even IIS or WAS will use a ServiceHost to host your WCF service - they just do it automatically behind the scenes, and "on demand" - whenever a request for your WCF service comes in.

Calling WCF Services asynchronously using async and await

 

In my previous post, I covered how to use async and await keywords in C# 5 to create asynchronous methods. This post is a continuation of asynchronous programming, in which I will cover how to call WCF services from a client program using async and await.

Response of an application will be slower when it includes heavy weight operations like running complex queries against database, reading a piece of data from a file, calling a service to get some data or any remote operation. When such operations are performed synchronously, the application will be halted till the operation gets over. If we assign the slower operation to a separate task, the thread will be free to perform some other operation till the operation responds.

When a WCF service is called synchronously, the thread associated with the operation is idle till the response is obtained from the server. To avoid this in earlier versions of .NET framework (4.0 or earlier), we had an option to create asynchronous methods with an associated event. Using .NET 4.5, we can create task-based proxies while adding service reference to an application. This can be done using by clicking on the Advanced button in the Add Service Reference dialog.


To call a WCF service synchronously, you can simply use the proxy method created by the Visual Studio, similar to calling a local method.
  • To call a WCF service asynchronously, you will need to first create an "AsyncCallback" "delegate" and pass this delegate to the asynchronous proxy method generated by the Visual Studio. Since the "AsyncCallback" "delegate" is executed in a worker thread different from the UI thread, any access to the "UI elements" needs to be "Dispatched".
  • From the application point of view, either way has its advantages and disadvantages. For most applications, after the calling of a WCF service, the application will be in an intermediate state until the response from the service is received. During this time, it may be ideal to block the UI thread to prevent user actions to get into any un-predictable results. In this case, a synchronous call may be appropriate. In some other scenarios, particularly when we work on some "SOA" applications, we may need to make multiple service calls at the same time and let the services to work in parallel. In this case, asynchronous WCF calls will be the ideal.
  • One thing just came to my mind. To make an asynchronous call, you probably do not need to have the asynchronous proxies. You can well fork a worker thread by yourself and let the thread to do a synchronous call. You will achieve the same effect as using the asynchronous proxies.
  • If you are not familiar with WCF services, this link is a good place to get you started.
  • Dependency Injection (DI) in EF

    Dependency Injection (DI) is a software design pattern that allow us to develop loosely coupled code. DI is a great way to reduce tight coupling between software components. DI also enables us to better manage future changes and other complexity in our software. The purpose of DI is to make code maintainable.
    The Dependency Injection pattern uses a builder object to initialize objects and provide the required dependencies to the object means it allows you to "inject" a dependency from outside the class.
    For example, Suppose your Client class needs to use a Service class component, then the best you can do is to make your Client class aware of an IService interface rather than a Service class. In this way, you can change the implementation of the Service class at any time (and for how many times you want) without breaking the host code.

    Key points about DI

    1. Reduces class coupling
    2. Increases code reusing
    3. Improves code maintainability
    4. Improves application testing
    Dependency Injection’ as a design pattern that helps develop maintainable and de-coupled code. DI is also a way to implement the ‘D’ in SOLID principles. (SOLID as stated by Uncle Bob stands for: Single responsibility, Open closed principle, Liskov substitution principle, Interface segregation principle and Dependency Inversion). Often the association of 'Design Pattern' to anything that we have not dealt with before, typically means it goes into our 'To Do' bucket which becomes very dusty over time. Time to blow the dust away! 

    What is SOLID?

     

    SOLID are five basic principles whichhelp to create good software architecture. SOLID is an acronym where:-
    • S stands for SRP (Single responsibility principle)
    • O stands for OCP (Open closed principle)
    • L stands for LSP (Liskov substitution principle)
    • I stands for ISP ( Interface segregation principle)
    • D stands for DIP ( Dependency inversion principle)

    WebAPI service and WCF service calling in client application

    WCF service details

    class TestService : ITestService
    {
        public Stream TestGet()
        {
            return new MemoryStream(Encoding.UTF8.GetBytes("Hello World. Time is: " + DateTime.Now));
        }
     
        public async Task<Stream> TestStream(Stream requestStream)
        {
            using (var reader = new StreamReader(requestStream))
            {
                var body = await reader.ReadToEndAsync();
     
                return new MemoryStream(Encoding.UTF8.GetBytes(body));
            }
     
        }
     
    }



    WebAPI service details

     
    public class TestController : ApiController
    {
        public HttpResponseMessage Get()
        {
            return new HttpResponseMessage() { Content = new StringContent("Hello World. Time is: " + DateTime.Now, Encoding.UTF8, "text/plain") };
        }
     
        public async Task<HttpResponseMessage> Post(HttpRequestMessage inputMessage)
        {
            var content = await inputMessage.Content.ReadAsByteArrayAsync();
            var response = new HttpResponseMessage { Content = new ByteArrayContent(content) };
            return response;
        }
     
        public async Task<HttpResponseMessage> Put(HttpRequestMessage inputMessage)
        {
            var content = await inputMessage.Content.ReadAsStreamAsync();
            var response = new HttpResponseMessage { Content = new StreamContent(content) };
            return response;
        }
     
     
    }

    Asp.Net Web API Vs Asp.Net MVC

    Asp.Net Web API  Vs  Asp.Net MVC

    1. Asp.Net MVC is used to create web applications that returns both views and data but Asp.Net Web API is used to create full blown HTTP services with easy and simple way that returns only data not view.
    2. Web API helps to build REST-ful services over the .NET Framework and it also support content-negotiation(it's about deciding the best response format data that could be acceptable by the client. it could be JSON,XML,ATOM or other formatted data), self hosting which are not in MVC.
    3. Web API also takes care of returning data in particular format like JSON,XML or any other based upon the Accept header in the request and you don't worry about that. MVC only return data in JSON format using JsonResult.
    4. In Web API the request are mapped to the actions based on HTTP verbs but in MVC it is mapped to actions name.
    5. Asp.Net Web API is new framework and part of the core ASP.NET framework. The model binding, filters, routing and others MVC features exist in Web API are different from MVC and exists in the new System.Web.Http assembly. In MVC, these featues exist with in System.Web.Mvc. Hence Web API can also be used with Asp.Net and as a stand alone service layer.
    6. You can mix Web API and MVC controller in a single project to handle advanced AJAX requests which may return data in JSON, XML or any others format and building a full blown HTTP service. Typically, this will be called Web API self hosting.
    7. When you have mixed MVC and Web API controller and you want to implement the authorization then you have to create two filters one for MVC and another for Web API since boths are different.
    8. Moreover, Web API is light weight architecture and except the web application it can also be used with smart phone apps.

    Web API

    What is Web API and why to use it ?
    Web API is a framework for building HTTP services that can be consume by a broad range of clients including browsers, mobiles, iphone and tablets. It is very similar to ASP.NET MVC since it contains the MVC features such as routing, controllers, action results, filter, model binders, IOC container or dependency injection. But it is not a part of the MVC Framework.

    Sunday, 10 November 2013

    Embed Flash content in asp pages

    Hi,

    Here is i will provide you a way to insert flash content in ASP pages 


    A. Collection of the Abstract (Incomplete) and Concrete (complete) methods is called as the Abstract class. If there is at least one abstract method in a class, the class must be abstract class.
    When there is the similar behavior, we can use the abstract class.
    e.g. We want to calculate the area of few component. As this is not generic to the application. We have only few component- like Circle, Ellipse, parabola, Hyperbola, Triangle etc.
    So we can create an abstract class and implement it like below:
    public abstract class MyAbstractClass
    {
     // some other concrete members
     public abstract void Area();// abstract member
    }
    Now in the child class, let’s say i have a circle class and want to calculate the area of the circle:
    public class Cicle: MyAbstractClass
    {
     public override void Area()
     {
      // calculate the area of the circle
     }
    }
    In the similar fashion, we can calcite the area of other shapes.
    Collection of abstract members is called as the Interface. When the behavior is not similar, we need to use the interface. All the members of the interface 
    must be overrides in the child class.
    e.g. Print functionality of the application can have an interface like:
    interface Inf
    {
     void Print();
    }
    Now as this is the generic functionality and can be implemented in any of the page so we have taken it as interface. Now we can implement this functionality in to any page like:
    class MyClass:Inf
    {
     public void print
     {
      // write details about the print
     }
    // Here we can implement any kind of print-like print to excel, xml, word all depends on the our decision.
    }