- 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 MVC Pattern? | Explain the Elements of model-view-controller | Design Patterns Programmer Guide
Brief about SOLID Principle? | SOLID Principle Tutorial | SOLID Principle Programmer Guide
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
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
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
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.
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
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 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
The Dependency Injection (DI) Design Pattern
- 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
UserId=ninja,IP=192.78.68.90
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:
- 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.
- 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:
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:
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:
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
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
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
Popular Tutorials
- Creating Cookie in ASP.NET MVC Action | Handling Cookies in ASP.NET MVC | Set Cookie Expiry in ASP.NET MVC | ASP.NET MVC Tutorial
- Generating Multiline TextBox or TextArea with @Html.EditorFor in ASP.NET MVC
- Generating Unique Token in C# | Generating Unique Token that Expires after 24 Hours in C# | C# Tutorial
- Drag & Drop File Upload In ASP.NET MVC Using dropzone js with Fallback Browser Support | ASP.NET MVC Tutorial
- Loading PartialView Via JQuery In ASP.NET MVC | Returning PartialView From ASP.NET MVC Action | ASP.NET MVC Tutorial
- How To Enable Role Manager Feature In ASP.NET MVC? | ASP.NET MVC Interview Question
- How To Add CSS Class And Custom Property in Html.TextBoxFor? | ASP.NET MVC | RAZOR
- Send and Receive SMS and MMS Messages Using Android 4.4 SMS API | Android Video Tutorial
- How to Get Browser Agent from ASP.NET Web API Controller? | ASP.NET Web API Tutorial
- How to Override the Common Route Prefix? | ASP.Net MVC Interview Question