Friday, May 24, 2013

Understanding ASP.NET MVC (Model View Controller) Architecture

Introduction

This article is intended to provide basic concepts and fundamentals of ASP.NET MVC (Model View Controller) architecture workflow for beginners.
“M” “V” “C” stands for “MODEL” “VIEW” “CONTROLLER”. ASP.NET MVC is an architecture to develop ASP.NET web applications in a different manner than the traditional ASP.NET web development. Web applications developed with ASP.NET MVC are even more SEO (Search Engine) friendly.
Developing ASP.NET MVC application requires Microsoft .NET Framework 3.5 or higher.

MVC Interaction with Browser

Like a normal web server interaction, MVC application also accepts requests and responds to the web browser in the same way.

Inside MVC Architecture

The entire ASP.NET MVC architecture is based on Microsoft .NET Framework 3.5 and in addition uses LINQ to SQL Server.

What is a Model?

  1. MVC model is basically a C# or VB.NET class
  2. A model is accessible by both controller and view
  3. A model can be used to pass data from Controller to view
  4. A view can use model to display data in page.

What is a View?

  1. View is an ASPX page without having a code behind file
  2. All page specific HTML generation and formatting can be done inside view
  3. One can use Inline code (server tags ) to develop dynamic pages
  4. A request to view (ASPX page) can be made only from a controller’s action method
What is a Controller?
  1. Controller is basically a C# or VB.NET class which inherits system.mvc.controller
  2. Controller is a heart of the entire MVC architecture
  3. Inside Controller’s class action methods can be implemented which are responsible for responding to browser OR calling views.
  4. Controller can access and use model class to pass data to views
  5. Controller uses ViewData to pass any data to view

MVC File Structure & File Naming Standards

MVC uses a standard directory structure and file naming standards which are a very important part of MVC application development.
Inside the ROOT directory of the application, there must be 3 directories each for model, view and Controller.
Apart from 3 directories, there must have a Global.asax file in root folder, and a web.config like a traditional ASP.NET application.
  • Root [directory]
    • Controller [directory]
      • Controller CS files
    • Models [directory]
      • Model CS files
    • Views [directory]
      • View aspx/ascx files
    • Global.asax
    • Web.config

ASP.NET MVC Execution Life Cycle

Here is how MVC architecture executes the requests to browser and objects interactions with each other.
A step by step process is explained below [Refer to the figure as given below]:

Browser Request (Step 1)

Browser request happens with a specific URL. Let’s assume that the user enters URL like: [xyz.com]/home/index/

Job of Global.asax – MVC routing (Step 2)

The specified URL will first get parsed via application_start() method inside Global.asax file. From the requested URL, it will parse the Controller, Action and ID.
So for [xyz.com]/home/index/:
  • Controller = home
  • Action = index()
  • ID = empty — we have not specified ID in [xyz.com]/home/index/, so it will consider as empty string

Controller and Action methods (Step 3)

MVC now finds the home controller class in controller directory. A controller class contains different action methods,
There can be more than one action method, but MVC will only invoke the action method which has been parsed from the URL, its index() in our case.
So something like: homeController.index() will happen inside MVC controller class.
Invoking action method can return plain text string OR rendered HTML by using view.

Call to View (Step 4)

Invoking view will return view(). A call to view will access the particular ASPX page inside the view directory and generate the rendered HTML from the ASPX and will respond back to the browser.
In our case, controller was home and action was index(). So calling view() will return a rendered HTML from the ASPX page located at /views/home/index.aspx.

Web.config File - ASP.NET

ASP.NET Web.config allows you to define or revise the configuration settings at the time of developing the application or at the time of deployment or even after deployment. The following are brief points that can be understood about the Web.config file:
  • Web.config files are stored in XML format which makes us easier to work with.
  • You can have any number of Web.config files for an application. Each Web.config applies settings to its own directory and all the child directories below it.
  • All the Web.config files inherit the root Web.config file available at the following location systemroot\Microsoft.NET\Framework\versionNumber\CONFIG\Web.config location
  • IIS is configured in such a way that it prevents the Web.config file access from the browser.
  • The changes in Web.config don’t require the reboot of the web server.

Opps in .net

What is OOP?

 OOP is a design philosophy. It stands for Object Oriented Programming. Object-Oriented Programming (OOP) uses a different set of programming languages than old procedural programming languages (C, Pascal, etc.). Everything in OOP is grouped as self sustainable "objects". Hence, you gain re-usability by means of four main object-oriented programming concepts.
In order to clearly understand the object orientation, let’s take your “hand” as an example. The “hand” is a class. Your body has two objects of type hand, named left hand and right hand. Their main functions are controlled/ managed by a set of electrical signals sent through your shoulders (through an interface). So the shoulder is an interface which your body uses to interact with your hands. The hand is a well architected class. The hand is being re-used to create the left hand and the right hand by slightly changing the properties of it.

What is an Object?

An object can be considered a "thing" that can perform a set of related activities. The set of activities that the object performs defines the object's behavior. For example, the hand can grip something or a Student (object) can give the name or address.

In pure OOP terms an object is an instance of a class.

What is a Class?

A class is simply a representation of a type of object. It is the blueprint/ plan/ template that describe the details of an object. A class is the blueprint from which the individual objects are created. Class is composed of three things: a name, attributes, and operations.

public class Student
{
}
According to the sample given below we can say that the student object, named objectStudent, has created out of the Student class.
Student objectStudent = new Student();
 
In real world, you'll often find many individual objects all of the same kind. As an example, there may be thousands of other bicycles in existence, all of the same make and model. Each bicycle has built from the same blueprint. In object-oriented terms, we say that the bicycle is an instance of the class of objects known as bicycles. In the software world, though you may not have realized it, you have already used classes. For example, the TextBox control, you always used, is made out of the TextBox class, which defines its appearance and capabilities. Each time you drag a TextBox control, you are actually creating a new instance of the TextBox class.

What is Encapsulation (or information hiding)?

The encapsulation is the inclusion within a program object of all the resources need for the object to function - basically, the methods and the data. In OOP the encapsulation is mainly achieved by creating classes, the classes expose public methods and properties. The class is kind of a container or capsule or a cell, which encapsulate the set of methods, attribute and properties to provide its indented functionalities to other classes. In that sense, encapsulation also allows a class to change its internal implementation without hurting the overall functioning of the system. That idea of encapsulation is to hide how a class does it but to allow requesting what to do. 

What is Polymorphisms?

Polymorphisms is a generic term that means 'many shapes'. More precisely Polymorphisms means the ability to request that the same operations be performed by a wide range of different types of things.
At times, I used to think that understanding Object Oriented Programming concepts have made it difficult since they have grouped under four main concepts, while each concept is closely related with one another. Hence one has to be extremely careful to correctly understand each concept separately, while understanding the way each related with other concepts.
In OOP the polymorphisms is achieved by using many different techniques named method overloading, operator overloading and method overriding,

What is Inheritance?

Ability of a new class to be created, from an existing class by extending it, is called inheritance.
Inheritance.gif
public class Exception
{
}


public class IOException : Exception
{
} 
According to the above example the new class (IOException), which is called the derived class or subclass, inherits the members of an existing class (Exception), which is called the base class or super-class. The class IOException can extend the functionality of the class Exception by adding new types and methods and by overriding existing ones.
Just like abstraction is closely related with generalization, the inheritance is closely related with specialization. It is important to discuss those two concepts together with generalization to better understand and to reduce the complexity.
One of the most important relationships among objects in the real world is specialization, which can be described as the “is-a” relationship. When we say that a dog is a mammal, we mean that the dog is a specialized kind of mammal. It has all the characteristics of any mammal (it bears live young, nurses with milk, has hair), but it specializes these characteristics to the familiar characteristics of canis domesticus. A cat is also a mammal. As such, we expect it to share certain characteristics with the dog that are generalized in Mammal, but to differ in those characteristics that are specialized in cats.
The specialization and generalization relationships are both reciprocal and hierarchical. Specialization is just the other side of the generalization coin: Mammal generalizes what is common between dogs and cats, and dogs and cats specialize mammals to their own specific subtypes.
Similarly, as an example you can say that both IOException and SecurityException are of type Exception. They have all characteristics and behaviors of an Exception, That mean the IOException is a specialized kind of Exception. A SecurityException is also an Exception. As such, we expect it to share certain characteristic with IOException that are generalized in Exception, but to differ in those characteristics that are specialized in SecurityExceptions. In other words, Exception generalizes the shared characteristics of both IOException and SecurityException, while IOException and SecurityException specialize with their characteristics and behaviors.
In OOP, the specialization relationship is implemented using the principle called inheritance. This is the most common and most natural and widely accepted way of implement this relationship.

What is Method Overloading?

The method overloading is the ability to define several methods all with the same name.

public class MyLogger
{
    public void LogError(Exception e)
    {
        // Implementation goes here
    }

    public bool LogError(Exception e, string message)
    {
        // Implementation goes here
    }
}

 

What is Operator Overloading?

 The operator overloading (less commonly known as ad-hoc polymorphisms) is a specific case of polymorphisms in which some or all of operators like +, - or == are treated as polymorphic functions and as such have different behaviors depending on the types of its arguments.

public class Complex
{
    private int real;
    public int Real
    { get { return real; } }

    private int imaginary;
    public int Imaginary
    { get { return imaginary; } }

    public Complex(int real, int imaginary)
    {
        this.real = real;
        this.imaginary = imaginary;
    }

    public static Complex operator +(Complex c1, Complex c2)
    {
        return new Complex(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary);
    }
}

What is Method Overriding?

Method overriding is a language feature that allows a subclass to override a specific implementation of a method that is already provided by one of its super-classes.

A subclass can give its own definition of methods but need to have the same signature as the method in its super-class. This means that when overriding a method the subclass's method has to have the same name and parameter list as the super-class's overridden method.


using System;
public class Complex
{
    private int real;
    public int Real
    { get { return real; } }

    private int imaginary;
    public int Imaginary
    { get { return imaginary; } }

    public Complex(int real, int imaginary)
    {
        this.real = real;
        this.imaginary = imaginary;
    }

    public static Complex operator +(Complex c1, Complex c2)
    {
        return new Complex(c1.Real + c2.Real, c1.Imaginary + c2.Imaginary);
    }

    public override string ToString()
    {
        return (String.Format("{0} + {1}i", real, imaginary));
    }
}

What is an Interface? 

In summary the Interface separates the implementation and defines the structure, and this concept is very useful in cases where you need the implementation to be interchangeable. Apart from that an interface is very useful when the implementation changes frequently. Some say you should define all classes in terms of interfaces, but I think recommendation seems a bit extreme.

Interface can be used to define a generic template and then one or more abstract classes to define partial implementations of the interface. Interfaces just specify the method declaration (implicitly public and abstract) and can contain properties (which are also implicitly public and abstract). Interface definition begins with the keyword interface. An interface like that of an abstract class cannot be instantiated.
If a class that implements an interface does not define all the methods of the interface, then it must be declared abstract and the method definitions must be provided by the subclass that extends the abstract class. In addition to this an interfaces can inherit other interfaces.
The sample below will provide an interface for our LoggerBase abstract class.

public interface ILogger
{
    bool IsThisLogError { get; }
}

What is Implicit and Explicit Interface Implementations?

As mentioned before .Net support multiple implementations, the concept of implicit and explicit implementation provide safe way to implement methods of multiple interfaces by hiding, exposing or preserving identities of each of interface methods, even when the method signatures are the same.
Let's consider the interfaces defined below.

interface IDisposable
{
    void Dispose();
} 
 
Here you can see that the class Student has implicitly and explicitly implemented the method named Dispose() via Dispose and IDisposable.Dispose.
class Student : IDisposable
{
    public void Dispose()
    {
        Console.WriteLine("Student.Dispose");
    }

    void IDisposable.Dispose()
    {
        Console.WriteLine("IDisposable.Dispose");
    }
}  

 


 

 

 


 




 

Opps Part 1 : Abstraction

  Abstraction in C# is a fundamental concept of object-oriented programming (OOP) that allows developers t...