MVC

We are very familiar with the “ActionResult” class that is the base class of many classes and we can return an object of those classes. The class hierarchy is as in the following:(Return type of action)

System.Object
System.Web.Mvc.ActionResult


  • System.Web.Mvc.ContentResult
  • System.Web.Mvc.EmptyResult
  • System.Web.Mvc.FileResult
  • System.Web.Mvc.HttpStatusCodeResult
  • System.Web.Mvc.JavaScriptResult
  • System.Web.Mvc.JsonResult
  • System.Web.Mvc.RedirectResult
  • System.Web.Mvc.RedirectToRouteResult
  • System.Web.Mvc.ViewResultBase


You can use the classes found in the System.Json Namespace which were added in .NET 4.5
The JsonValue.Parse() Method parses JSON text and returns a JsonValue:

JsonValue value = JsonValue.Parse(@"{ ""name"":""Prince Charming"", ...");


Use a route with a catch-all parameter. An example is shown below. * is referred to as catch-all parameter.
controller/{action}/{*parametervalues}

Type of filters

Now taking this discussion further, Let us first discuss the various types of filters that can be implemented to inject custom processing logic.

Authorization filter
Action filter
Result filter
Exception filter

Custom Authorization Filter : This filter will be executed once after user is authenticated

In this step lets create a custom Authorization filter. For this create a class which inherits AuthorizeAttribute or implements IAuthorizationFilter interface. All we are doing here is just passing a message to View.


public class CustAuthFilter : AuthorizeAttribute
    {
        public override void OnAuthorization(AuthorizationContext filterContext)
        {            
            filterContext.Controller.ViewBag.AutherizationMessage = "Custom Authorization: Message from OnAuthorization method.";
        }        
    }

Action Filter : There are 4 events available in an action filter.

OnActionExecuting - Runs before execution of Action method.
OnActionExecuted - Runs after execution of Action method.
OnResultExecuting - Runs before content is rendered to View.
OnResultExecuted - Runs after content is rendered to view.
So lets create a CustomActionFilter. Create a class inherting ActionFilterAttribute class of implementing IActionFilter and IResultFilter interfaces.

Hide   Copy Code
public class CustomActionFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            filterContext.Controller.ViewBag.CustomActionMessage1 = "Custom Action Filter: Message from OnActionExecuting method.";
        }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            filterContext.Controller.ViewBag.CustomActionMessage2 = "Custom Action Filter: Message from OnActionExecuted method.";
        }

        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            filterContext.Controller.ViewBag.CustomActionMessage3 = "Custom Action Filter: Message from OnResultExecuting method.";
        }

        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            filterContext.Controller.ViewBag.CustomActionMessage4 = "Custom Action Filter: Message from OnResultExecuted method.";
        }        
    }

Repository and Unit of Work Patterns

The repository and unit of work patterns are intended to create an abstraction layer between the data access layer and the business logic layer of an application. Implementing these patterns can help insulate your application from changes in the data store and can facilitate automated unit testing or test-driven development (TDD).

In this tutorial you'll implement a repository class for each entity type. For the Student entity type you'll create a repository interface and a repository class. When you instantiate the repository in your controller, you'll use the interface so that the controller will accept a reference to any object that implements the repository interface. When the controller runs under a web server, it receives a repository that works with the Entity Framework. When the controller runs under a unit test class, it receives a repository that works with data stored in a way that you can easily manipulate for testing, such as an in-memory collection.

Later in the tutorial you'll use multiple repositories and a unit of work class for the Course and Department entity types in the Course controller. The unit of work class coordinates the work of multiple repositories by creating a single database context class shared by all of them. If you wanted to be able to perform automated unit testing, you'd create and use interfaces for these classes in the same way you did for the Student repository. However, to keep the tutorial simple, you'll create and use these classes without interfaces.


Implement a Generic Repository and a Unit of Work Class

Creating a repository class for each entity type could result in a lot of redundant code, and it could result in partial updates. For example, suppose you have to update two different entity types as part of the same transaction. If each uses a separate database context instance, one might succeed and the other might fail. One way to minimize redundant code is to use a generic repository, and one way to ensure that all repositories use the same database context (and thus coordinate all updates) is to use a unit of work class.+

In this section of the tutorial, you'll create a GenericRepository class and a UnitOfWork class, and use them in the Course controller to access both the Department and the Course entity sets. As explained earlier, to keep this part of the tutorial simple, you aren't creating interfaces for these classes. But if you were going to use them to facilitate TDD, you'd typically implement them with interfaces the same way you did the Student repository.

namespace ContosoUniversity.DAL
{
    public class GenericRepository<TEntity> where TEntity : class
    {
        internal SchoolContext context;
        internal DbSet<TEntity> dbSet;

        public GenericRepository(SchoolContext context)
        {
            this.context = context;
            this.dbSet = context.Set<TEntity>();
        }

        public virtual IEnumerable<TEntity> Get(
            Expression<Func<TEntity, bool>> filter = null,
            Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
            string includeProperties = "")
        {
            IQueryable<TEntity> query = dbSet;

            if (filter != null)
            {
                query = query.Where(filter);
            }

            foreach (var includeProperty in includeProperties.Split
                (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
            {
                query = query.Include(includeProperty);
            }

            if (orderBy != null)
            {
                return orderBy(query).ToList();
            }
            else
            {
                return query.ToList();
            }
        }

        public virtual TEntity GetByID(object id)
        {
            return dbSet.Find(id);
        }

        public virtual void Insert(TEntity entity)
        {
            dbSet.Add(entity);
        }

        public virtual void Delete(object id)
        {
            TEntity entityToDelete = dbSet.Find(id);
            Delete(entityToDelete);
        }

        public virtual void Delete(TEntity entityToDelete)
        {
            if (context.Entry(entityToDelete).State == EntityState.Detached)
            {
                dbSet.Attach(entityToDelete);
            }
            dbSet.Remove(entityToDelete);
        }

        public virtual void Update(TEntity entityToUpdate)
        {
            dbSet.Attach(entityToUpdate);
            context.Entry(entityToUpdate).State = EntityState.Modified;
        }
    }
}

What are Certificates?

Digital certificates are responsible for verifying the identity of the people in the cyber world, that is, is this person who they claim to be. They also secure the data that is being exchanged between the client and server from tampering or eavesdropping, this is done by encrypting the data which requires a unique private key for decryption. Digital certificates contain a variety of identification information such as serial numbers, thumbprints etc. In our scenario will create two certificates, one for the client and one for the server. The client and server will use the public keys inside our certificates to decode the digital certificates, and verify that the certificates are issued by a trusted certification authority, in this case our computers 'Root Agency'. For example once our client application is sure that the Server is who it says it is, it uses the servers public key and identification information inside the certificate to encrypt the messages. Ideally in a production environment (such as a website you expect users to access and provide personal details) you should not use self signed certificates, mainly because your users won’t be able to access your website in the first place as their browser tells them it doesn’t recognise the certification authority (CA) and shows them that terrifying red screen. In production scenarios you should look to purchase certificates issued by well knows CAs such as Verisign, Equifax etc. If you have a limited number of users accessing your service, and you know who they are and you are able to issue the self signed certificates to them, then you can use self signed certificates.

Explain MVC application life cycle?

There are six broader events which occur in MVC application life cycle below diagrams summarize it.



Any web application has two main execution steps first understanding the request and depending on the type of the request sending out appropriate response. MVC application life cycle is not different it has two main phases first creating the request object and second sending our response to the browser.

Creating the request object: -The request object creation has four major steps. Below is the detail explanation of the same.

Step 1 Fill route: - MVC requests are mapped to route tables which in turn specify which controller and action to be invoked. So if the request is the first request the first thing is to fill the route table with routes collection. This filling of route table happens in the global.asax file.

Step 2 Fetch route: - Depending on the URL sent “UrlRoutingModule” searches the route table to create “RouteData” object which has the details of which controller and action to invoke.

Step 3 Request context created: - The “RouteData” object is used to create the “RequestContext” object.

Step 4 Controller instance created: - This request object is sent to “MvcHandler” instance to create the controller class instance. Once the controller class object is created it calls the “Execute” method of the controller class.

Creating Response object: - This phase has two steps executing the action and finally sending the response as a result to the view.


What are HTML helpers in MVC?

HTML helpers help you to render HTML controls in the view. For instance if you want to display a HTML textbox on the view , below is the HTML helper code.

What is routing in MVC?

Routing helps you to define a URL structure and map the URL with the controller.

Attribute based routing in MVC


public class HomeController : Controller
{
       [Route("Users/about")]
       public ActionResult GotoAbout()
       {
           return View();
       }
}

 [Route("Users/about")]
       [Route("Users/WhoareWe")]
       [Route("Users/OurTeam")]
       [Route("Users/aboutCompany")]
       public ActionResult GotoAbout()
       {
           return View();
       }

How can we navigate from one view to another using a hyperlink?


<%= Html.ActionLink("Home","Gotohome") %>


What is the difference between tempdata, viewdata, and viewbag


Temp data - Helps to maintain data when you move from one controller to another controller or from one action to another action. In other words when you redirect, tempdata helps to maintain data between those redirects. It internally uses session variables.
View data - Helps to maintain data when you move from controller to view.
View Bag - It’s a dynamic wrapper around view data. When you use Viewbag type, casting is not required. It uses the dynamic keyword internally.

Session variables - By using session variables we can maintain data from any entity to any entity.
Hidden fields and HTML controls - Helps to maintain data from UI to controller only. So you can send data from HTML controls or hidden fields to the controller using POST or GET HTTP methods.

Maintains data betweenViewData/ViewBagTempDataHidden fieldsSession
Controller to ControllerNoYesNoYes
Controller to ViewYesNoNoYes
View to ControllerNoNoYesYes


How can we detect that an MVC controller is called by POST or GET?

To detect if the call on the controller is a POST action or a GET action we can use the Request.HttpMethod property as shown in the below code snippet.

Hide   Copy Code
public ActionResult SomeAction()
{
    if (Request.HttpMethod == "POST")
    {
        return View("SomePage");
    }
    else
    {
        return View("SomeOtherPage");
    }
}

What is bundling and minification in MVC?
Bundling and minification helps us improve request load times of a page thus increasing performance

How does bundling increase performance?
Web projects always need CSS and script files. Bundling helps us combine multiple JavaScript and CSS files in to a single entity thus minimizing multiple requests in to a single request.

For example consider the below web request to a page . This page consumes two JavaScript files Javascript1.js and Javascript2.js. So when this is page is requested it makes three request calls:

One for the Index page.
Two requests for the other two JavaScript files: Javascript1.js and Javascript2.js.

So how do we implement bundling in MVC?
In BundleConfig.cs, add the JS files you want bundle into a single entity in to the bundles collection. In the below code we are combining all the javascript JS files which exist in the Scripts folder as a single unit in to the bundle collection


Best practices MVC


Tip 1: Disable Request Validation
Request Validation is a feature that prevents potentially dangerous content from being submitted. This feature is enabled by default. However, at times you might need your application to post HTML markup tags to the server. You would then need this feature to be disabled. Here is how you can do it:
[ValidateInput(false)]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude="Id")]Employee empObj)
{

}
Tip 2: Cache Your Data
You can improve your application's performance to a considerable extent by caching relatively stale data. That way the network bandwidth between the client and the server is also reduced. It is great if you can also cache the rendered action of web pages that are relatively stale, i.e., don’t change much over time.
public class HomeController : Controller
{
    [OutputCache(Duration=3600,
VaryByParam="none")]
    public ActionResult Index()
    {
    
    }
}
Tip 3: Isolate Data Access Logic From the Controller
The Controller in an ASP.NET MVC application should never have the Data Access logic. The Controller in an ASP.NET MVC application is meant to render the appropriate view based on some user interface action. You should make use of Repository Pattern to isolate Data Access Logic from the Controller – you might need dependency injection to inject the appropriate Repository to your controller at runtime.
Tip 4: Using a Master View Model
We frequently use Master Pages in ASP.NET applications – the same Master Page would be extended by the Content Pages throughout the application to give a similarity as far as look and feel and functionality is concerned. How do we do that in an ASP.NET MVC application? Well, we need a MasterViewModel similar to what is shown in the code snippet below:
public class ViewModelBase
{
    public ViewModelBase()
    {

    }
//Other methods and properties
}
Tip 5: Use Strongly Typed Models
A strongly typed view is a view that defines its data model as a CLR type instead of a weakly typed dictionary that may contain potentially anything. To create a strongly typed view, check the "Create a strongly-typed view" checkbox while you are creating the view. If you plan to create a strongly typed view manually later, ensure that your view "Inherits" System.Web.Mvc.<Your Namespace>.<YourClass>
Tip 6: Use Data Annotations for Validation
You can make use of the System.ComponentModel.DataAnnotations assembly to validate your server - side code by simply decorating your model with the necessary attributes. Here is an example:
public class Employee
{
    [Required(ErrorMessage="Employee Name Cannot be Blank")]
    public string Name { get; set; }

    // ...
}
Tip 7: Take Advantage of Model Binding
Consider the following code snippet:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create()
{
    Employee employee = new Employee();
    employee.Name = Request.Form["Name"];
   
    // ...
   
    return View();
}
You can make use of model binder to save you from having to use the Request and HttpContext properties - just use FormsCollection instead. Here is an example:
public ActionResult Create(FormCollection values)
{
    Employee employee = new Employee();
    employee.Name = values["Name"];     
           
    // ...
           
    return View();
}
Tip 8: Cache Pages that Contain Shared Data or are Public and don't Require Authorization

You should not cache pages that need authorization in ASP.NET MVC. You should not cache pages that contain private data or need authorization. Caching pages in ASP.NET MVC is simple - just specify the OutputCache directive as shown in the code snippet below:
[OutputCache(Duration = 60)]
public ActionResult Index()
{
  return View("Index", somedata);
}
Tip 9: Use Extension Methods
You can make use of Extension Methods to simplifies use of LINQ queries that boost application performance too. This can dramatically reduce the amount of code that you would need to otherwise write when writing your LINQ queries, make your LINQ queries manageable and also improve the application's performance.
Tip 10: Take Advantage of Model Binding
You can take advantage of Microsoft Velocity - a distributed caching engine to boost the application performance of your ASP.NET MVC applications. You can learn more on Velocity from this link:

No comments:

Post a Comment