Brief about MVC Pattern? | Explain the Elements of model-view-controller | Design Patterns Programmer Guide

MVC stands for model-view-controller.  MVC is a pattern for developing applications that are well architected, testable  and easy to maintain. MVC-based applications contain:
  • Models: Classes that represent the data of the application  and that use validation logic to enforce business rules for that data.
  • Views: Template files that your application uses to dynamically  generate HTML responses.
  • Controllers: Classes that handle incoming browser requests,  retrieve model data, and then specify view templates that return a response  to the browser.

Brief about SOLID Principle? | SOLID Principle Tutorial | SOLID Principle Programmer Guide

SOLID (Single responsibility, Open-closed, Liskov substitution, Interface segregation and Dependency inversion) is a mnemonic acronym that stands for five basic principles of object-oriented programming and design. The principles, when applied together, intend to make it more likely that a programmer will create a system that is easy to maintain and extend over time. The principles of SOLID are guidelines that can be applied while working on software to remove code smells by causing the programmer to refactor the software's source code until it is both legible and extensible. It is part of an overall strategy of agile and adaptive programming.

Single responsibility principle
a class should have only a single responsibility (i.e. only one potential change in the software's specification should be able to affect the specification of the class)

Open/closed principle
software entities should be open for extension, but closed for modification.

Liskov substitution principle
objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program.

Interface segregation principle
many client-specific interfaces are better than one general-purpose interface.

Dependency inversion principle
Depend upon Abstractions. Do not depend upon concretions. Dependency injection is one method of following this principle.

You aren't gonna need it (YAGNI) Design Principle | Design Principle Tutorial | Design Principle Programmer Guide

You aren't gonna need it (YAGNI) is a principle of extreme programming (XP) that states a programmer should not add functionality until deemed necessary. In other words, Always implement things when you actually need them, never when you just foresee that you need them. YAGNI is a simple principle that asks the programmer to do the simplest thing that could possibly work.

Advantage of Implementing Object Relational Mapping | Advantages of ORM

  • Data manipulation(CRUD) is handled without writing SQL queries
  • Data mapping between result set and entity collection/entity is one of the major features of ORM
  • Using UoW/Context, it can handle the transaction during data manipulation
  • Writing one Data Model in a single place for managing the model’s storage in DB.
  • It fits the natural way of coding with application’s language.
  • Programmers can think fully object oriented way to make any operation with business logic layer and data storage.

Unit Of Work Pattern Short Explanation | Unit Of Work Pattern Quick Reference | Design Patterns Tutorial

Unit of work is a pattern to handle the transaction during data manipulation using repository pattern. So we can say according to Martin Fowler, Maintains a list of objects affected by a business transaction and coordinates the writing out of changes and the resolution of concurrency problem.
Implementing these patterns can help insulate the application from changes in the data store and also gives advantages to automate unit testing. Though, these patterns are widely used for DDD but it facilitate for TDD also.

The Service Agent, Proxy, and Broker Patterns Quick Explanation | Design Patterns Quick Reference Guide

Various patterns exist that remove dependencies between a client and a service by using intermediate brokers. There are many different implementations of the basic pattern, some of which use an extra service-agent logic component to connect the client with the local proxy or gateway interface.

Figure 3 - The Service Agent, Proxy, and Broker Patterns

Figure 3 - The Service Agent, Proxy, and Broker Patterns

The aim of all these patterns is to allow remote connection to, and use of, a service without the client having to know how the service works. The service exposes a Contract that defines its interface, such as the Web Service Description Language (WSDL) document for a Web Service. A client-side proxy or gateway interface uses the Contract to create a suitably formatted request, and passes this to the service interface. The service sends the formatted response back through its gateway interface to the client proxy, which exposes it to the client. In effect, the client just calls the service methods on the client proxy, which returns the results just as if the service itself was a local component.

In the Service Agent pattern, an extra component on the client can perform additional processing and logic operations to further separate the client from the remote service. For example, the Service Agent may perform service address lookup, manipulate or format the client data to match the proxy requirements, or carry out any other kind of processing requirements common to different clients that use the service.

Repository Pattern Quick Explanation | Design Pattern Quick Reference Guide | Design Patterns Tutorial

The pattern virtualizes storage of entities in a persistent medium, such as a database or as XML. For example, a repository may expose data held in the tables of a database as strongly typed Customer and Order objects rather than data sets or data rows. It effectively hides the storage implementation from the application code, and allows the use of a common set of methods in the application without requiring knowledge of the storage mechanism or format. Often, the repository uses a series of providers to connect to the source data.

Figure 4 - The Repository Pattern

Provider Pattern and Adapter Pattern Quick Explanation | Design Pattern Reference Guide | Design Pattern Tutorial

The Provider and Adapter patterns allows otherwise incompatible classes to work together by converting the interface of one class into an interface expected by the other. In more practical terms, these patterns provide separation between components that allows behavioral changes to occur without prior knowledge of requirements. The application and any data sources it uses, outputs it generates, or classes it must interact with, can be created independently yet still work together (see Figure 2).

Figure 2 - The Provider and Adapter Patterns

Figure 2 - The Provider and Adapter Patterns

The Provider pattern separates the data processing objects, and the application, from the source data. It allows the code in the application to be independent of the type of data source and the format of the data. A Provider component or service exposes standard methods that the application can call to read and write data. Internally, it converts these calls to the equivalents that match the data source. This means that the application can work with any source data type (such as any kind of database, XML document, disk file, or data repository) for which a suitable provider is available.

The Adapter pattern has the same advantages, and works in a similar way. Often, the target of an Adapter is some kind of output. For example, a printer driver is an example of an Adapter. ASP.NET itself, and other frameworks such as Enterprise Library, make widespread use of the Provider and Adapter patterns.

Model-View-Controller and Model-View-Presenter Patterns Quick Comparison | MVC and MVP Short Explanation

The Model-View-Controller (MVC) and Model-View-Presenter (MVP) Patterns improve reusability of business logic by separating the three components required to generate and manage a specific user interface (such as a single Web page). The Model contains the data that the View (the Web page) will display and allow the user to manipulate. The Controller or Presenter links the Model and the View, and manages all interaction and processing of the data in the Model (see Figure 1).

Figure 1 - the MVC and MVP Patterns

Figure 1 - The Model-View-Controller and Model-View-Presenter Patterns

In the MVC pattern, user interaction with the View raises events in the Controller, which updates the Model. The Model then raises events to update the View. However, this introduces a dependency between the Model and the View. To avoid this, the MVP pattern uses a Presenter that both updates the Model and receives update events from it, using these updates to update the View. The MVP pattern improves testability, as all the logic and processing occurs within the Presenter, but it does add some complexity to the implementation because updates must pass from the Presenter to the View.

Usage Of Dependency Injection (DI) Design Pattern | Design Patterns Tutorial

In Object Oriented Programming paradigm, objects work together in a collaboration model where there are contributors and consumers. Naturally, this communication model generates dependencies between objects and components, becoming difficult to manage when complexity increases.
Class dependencies and model complexity
Class dependencies and model complexity
In Factory Pattern, the separation between the interface and the implementation using services, where the client objects are often responsible for service location.
The Dependency Injection pattern is a particular implementation of Inversion of Control. Inversion of Control (IoC) means that objects do not create other objects on which they rely to do their work. Instead, they get the objects that they need from an outside source (for example, an xml configuration file).
Dependency Injection (DI) means that this is done without the object intervention, usually by a framework component that passes constructor parameters and set properties.

The Dependency Injection (DI) Design Pattern

At a high level, the goal of Dependency Injection is that a client class (e.g. the golfer) needs something that satisfies an interface (e.g. IClub). It doesn't care what the concrete type is (e.g. WoodClub, IronClub, WedgeClub orPutterClub), it wants someone else to handle that (e.g. a good caddy). The Dependency Resolver in ASP.NET MVC can allow you to register your dependency logic somewhere else (e.g. a container or a bag of clubs).
Dependency Injection diagram
Dependency Injection - Golf analogy
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
Note: Dependency Injection is sometimes compared with Abstract Factory Design Pattern, but there is a slight difference between both approaches. DI has a Framework working behind to solve dependencies by calling the factories and the registered services.

Implementing Token Based Security Pattern | Design Patterns Tutorial

With HTTPS in place, its safe to request user to provide credentials through our front end. But first, lets establish a pattern for out security mechanism. There are various patterns which could be used to address your application specific security requirements. In this post, we will use a token based security pattern. Once the user is successfully authenticated, server will issue a token which needs to be passed by client with every subsequent requests as a proof of user identity.
The security token needs to be strongly encrypted to prevent forgery. The token will be issued and consumed by the same party – our server, so symmetric key encryption like Rijndael/AEC or DES would work fine. However, here I am using public-key cryptography for ease of managing the keys. Common use case of public-key cryptography/x.509 certificates involve sharing your public keys with the collaborating systems which could send data encrypted using your public key, which could be decrypted only using your private key. In our case, we don’t need to and shouldn’t share the public key with any other party as we are the issuer and consumer of the token. So, both keys needs to be protected religiously to prevent forgery of the token.
Another security risk is session hijacking, someone could get hold of the token and could pose as a user. In order to avoid hijacking, we will associate the token to the user machine’s IP address, while validating the token we will be comparing it with the IP address from which the request is being made. Following is the token in pain text, with just two key value pairs separated by comma.
UserId=ninja,IP=192.78.68.90

Following the class representing the token
public class Token
{
    public Token(string userId, string fromIP)
    {
        UserId = userId;
        IP = fromIP;
    }

    public string UserId { get; private set; }
    public string IP { get; private set; }

    public string Encrypt()
    {
        CryptographyHelper cryptographyHelper = new CryptographyHelper();
        X509Certificate2 certificate = cryptographyHelper.GetX509Certificate("CN=WebAPI-Token");
        return cryptographyHelper.Encrypt(certificate, this.ToString());
    }

    public override string ToString()
    {
        return String.Format("UserId={0};IP={1}", this.UserId, this.IP);
    }

    public static Token Decrypt(string encryptedToken)
    {
        CryptographyHelper cryptographyHelper = new CryptographyHelper();
        X509Certificate2 certificate = cryptographyHelper.GetX509Certificate("CN=WebAPI-Token");
        string decrypted = cryptographyHelper.Decrypt(certificate, encryptedToken);

        //Splitting it to dictionary
        Dictionary<string, string> dictionary = decrypted.ToDictionary();
        return new Token(dictionary["UserId"], dictionary["IP"]);
    }
}

Create the x.509 certificate by running following command on the Visual Studio command prompt while running as administrator
makecert -sr LocalMachine -ss My sha1 -n CN=WebAPI-Token -sk y exchange -pe
CryptographyHelper provides helper methods for encryption and decryption, code could be found here .

Inspecting Security Token

Lets create a message handler which will check for token in the header of every incoming requests.

public class TokenInspector : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
        const string TOKEN_NAME = "X-Token";

        if (request.Headers.Contains(TOKEN_NAME))
        {
            string encryptedToken = request.Headers.GetValues(TOKEN_NAME).First();
            try
            {
                Token token = Token.Decrypt(encryptedToken);
                bool isValidUserId = IdentityStore.IsValidUserId(token.UserId);
                bool requestIPMatchesTokenIP = token.IP.Equals(request.GetClientIP());

                if (!isValidUserId || !requestIPMatchesTokenIP)
                {
                    HttpResponseMessage reply = request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Invalid identity or client machine.");
                    return Task.FromResult(reply);
                }
            }
            catch (Exception ex)
            {
                HttpResponseMessage reply = request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Invalid token.");
                return Task.FromResult(reply);
            }
        }
        else
        {
            HttpResponseMessage reply = request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Request is missing authorization token.");
            return Task.FromResult(reply);
        }

        return base.SendAsync(request, cancellationToken);
    }

}

X-Token is the HTTP header in which we expect client to supply the token issued after authentication. Any request which doesn’t contain token is refused politely with HTTP 401 code. If the token is supplied, it is decrypted, user id is checked for validity against identity store. The IP address in the token is matched with the IP address of the request to prevent session hijacking. We need to register this message handler in out API config class as shown below.UsersController provides operations for authenticating the user, so of course we can’t demand token on that request, so the is excluded by explicitly specifying the route.

public static void Register(HttpConfiguration config)
{
    //Create and instance of TokenInspector setting the default inner handler
    TokenInspector tokenInspector = new TokenInspector() { InnerHandler = new HttpControllerDispatcher(config) };

  //Just exclude the users controllers from need to provide valid token, so they could authenticate
    config.Routes.MapHttpRoute(
        name: "Authentication",
        routeTemplate: "api/users/{id}",
        defaults: new { controller = "users" }
    );

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional },
        constraints: null,
        handler: tokenInspector
    );

    config.MessageHandlers.Add(new HTTPSGuard()); //Global handler - applicable to all the requests
}

The code for Web API Authentication Using Security Token along with unit tests could be found here

Template Design Pattern in C# | Design Pattern Tutorial

,

We will now explain the Template Method Pattern. Like the Strategy Pattern, this pattern is part of the behavioral design patterns. As the name Template suggests, we know a template is a kind of layout available for some kind of process, that we can modify as needed and use it. The case here is similar. We have some sub-tasks to complete a big task, that we can use as per our situation requirements. So technically speaking, we make the sub-tasks as abstract and implement them, as per our needs, in different cases. But one thing remains common;  the overall steps of the entire procedure or the algorithm, in other words first Step 1, then Step 2, then Step 3 and so on, that remain the same in their execution order.

Let's explain this concept in detail now.

What the Template Method Pattern is

According to the GoF's definition, this pattern:

Defines the skeleton of an algorithm in an operation, deferring some steps to sub-classes. The Template Method lets sub-classes redefine certain steps of an algorithm without changing the algorithm's structure.

A real-world example

An organization goes to colleges and hires beginner. They have a number of steps defined for the process of hiring in the following order:

Step 1: Take a test in the first round
Step 2: Group discussion in the second round
Step 3: Technical interview
Step 4: HR interview

They have a common process of group discussions and HR interviews for all the departments, but a different test and technical interview process, depending on whether it is for computer or electronics departments. So we create a hiring process template that can be used by the company for two different departments.

Let's convert the preceding real-world example into technical code.

We will be dividing the system into the following components for our implementation of this pattern:

  1. Abstract Class: This will be an abstract class, that will have the abstract methods of our technical and test rounds, that will be implemented in the sub-classes based on the departments and the non-abstract methods of the group discussion and the HR rounds.

    Most importantly, this class will contain a Non Abstract method that will be calling the abstract methods or any other method defined in this class, to outline the flow of the overall process in a step-wise call to these methods, or you can say, it will contain the sequence of an algorithm.
     
  2. Concrete Classes: These will be concrete implementations of our abstract steps of the tests and technical interviews, depending on the departments.

So our initial code setup for defining the template of the hiring process will be like the following:

Abstract Class in Csharp

We will next be implementing the template, to define the test and technical interview rounds, based on the type of department as in the following:

Abstract Class in Csharp

So now we have set up the complete process of hiring for two different departments, with a few common steps. Now we just need to start with the interview process for both the departments, using the client code. So we begin the process with the following code implementation:

Abstract Class in implementation in Csharp

Unit of Work in C# | Design Patterns | C#

, ,

The Unit of Work pattern is designed to maintain a list of business objects that have been changed by a business transaction, whether by adding, removing, or updating. The Unit of Work then coordinates the persistence of the changes and any concurrency problems flagged. The benefit of utilizing the Unit of Work in your DAL is to ensure data integrity; if an issue arises partway through persisting a series of business objects as part of a transaction, all changes should be rolled back to ensure that the data remains in a valid state.

Watch this space for more code level explanation

Facade Pattern in C# - Design Patterns

, ,

video courtesy DotNetIQ

Abstarct Factory in C# - Design Patterns

, ,

video courtesy DotNetIQ

Adapter Pattern in C# - Design Patterns

, ,

video courtesy DotNetIQ

Factory Method Pattern in C# - Design Patterns

, ,

Video courtesy DotNetIQ

Chain Of Responsibility - Design Patterns

, ,

Adapter Pattern - Design Patterns

, ,

When To Go for Adapter Pattern

  • A class that would be useful to your application does not implement the interface you require
  • You are designing a class or framework and you want to ensure it is usable by a wide variety of as yet unwritten classes and applicaations


Scenario for Adapter Pattern


Adapter Pattern Implemented


Intent of the Adapter Pattern

  • Convert the interface of a class into another interface clients expect
  • Allow classes to work together that couldn't otherwise due to incompatible interfaces
  • Future-proof client implementations by having them depend on Adapter Interfaces, rather than concrete classes directly


Use the Adapter Pattern when:

  • You want to use an existing class, but its interface does not match the one you require
  • You want to create a reusable class that cooperates with unrelated or unforeseen classes (i.e. classes that won't necessarily share the same interface)
  • You need to use several existing sub-classes, but it's impractical to adapt their interface by sub-classing everyone


Structure of Adapter Pattern


Other Patterns that use Adapter Pattern

  • Repository - Repository pattern is a very common use of the Adapter pattern
  • Strategy - Adapter pattern is often passed into a class that depends on it, thus implementing the strategy pattern
  • Facade - Adapter and Facade are both wrappers. The facade pattern attempts to simplify the interface and often wraps many classes, while the Adapter typically wraps a single Adaptee, and is not generally concerned with simplifying the interface