MVC

Agile 

http://geekswithblogs.net/dlussier/archive/2009/11/21/136454.aspx

http://www.codeproject.com/Articles/126249/MVVM-Pattern-in-WPF-A-Simple-Tutorial-for-Absolute

Technology Digestified - ASP.net MVC 3 Interview Questions

ASP.NET MVC OVERVIEW LINK

What is MVC?

MVC is a framework pattern that splits an application's implementation logic into three component roles: models, views, and controllers. The ASP.NET MVC framework is a lightweight, highly testable presentation framework that (as with Web Forms-based applications) is integrated with existing ASP.NET features, such as master pages and membership-based authentication. 

To implement MVC in .NET we need mainly three classes (View, Controller and the Model). 

Explain MVC Architecture?

The architecture is self-explanatory. The browser (as usual) sends a request to IIS, IIS searches for the route defined in the MVC application and passes the request to the controller as specified by the route, the controller communicates with the model and passes the populated model (entity) to View (front end), Views are populated with model properties, and are rendered on the browser, passing the response to the browser through IIS via controllers that invoked the specified View.

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

Image Courtesy: - http://www.dotnetinterviewquestions.in/article_explain-mvc-application-life-cycle_210.html

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.

Authentication Filter LINK

Authorization filters are used to implement authentication and authorization for controller actions. For example, the Authorize filter is an example of an Authorization filter.

Authorization filters allow you to perform authorization tasks for an authenticated user. A good example is Role based authorization.

Action filters contain logic that is executed before and after a controller action executes. You can use an action filter, for instance, to modify the view data that a controller action returns.

Result filters contain logic that is executed before and after a view result is executed. For example, you might want to modify a view result right before the view is rendered to the browser.

Exception filters are the last type of filter to run. You can use an exception filter to handle errors raised by either your controller actions or controller action results. You also can use exception filters to log errors. [  Example ]

For that we will use overloaded version of HandleErrorAttribute constructor as follows.

Prior to authentication filters, developers used the Authorization filters to drive some of the authentication tasks for the current request. It was convenient because the Authorization filters were executed prior to any other action filters.  For example, before the request routes to action execution, we would use an Authorization filter to redirect an unauthenticated user to a login page. Another example would be to use the Authorization filter to set a new authentication principal, which is different from the application’s original principal in context.

So it is basically about separating of concerns, while giving developers more flexibility to drive authentication using ASP.NET MVC infrastructure.

A practical example would be where your entire site runs on Forms based authentication using cookies, but you have a special requirement to support certain Controllers/Actions that should be transparent to a different authentication provider. This authentication provider would issue tokens along with the claim based authentication. Certain Controllers would have access to these claims principals. You can use a custom Authentication filter to set the new principal (i.e claims based), for the current request, just for the Controllers/Actions we need. The rest of the site will continue to work with the existing forms based authentication.

public interface IAuthenticationFilter

{

    void OnAuthentication(AuthenticationContext filterContext);

    void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext);

}

MVC 5 has a new feature called Filter Overrides, which allows you to clear or replace certain filter types created in higher scopes. For example, if you created a global action filter or controller action filter, you could override those filters on a case-by-case basis at the controller action level. This allows you to set global or controller filters that apply in almost all cases and just override them in the few, specific places where those filters don't apply.

[RoutePrefix("products")][RequireHttps]public class ProductsController : Controller {     private readonly IProductCatalog _productCatalog;      public ProductsController(IProductCatalog productCatalog) {         _productCatalog = productCatalog;     }      [Route]     [OverrideAuthorization]     public ActionResult Index() {         var products = _productCatalog.FetchAll();         return View(products);     }

 I can decorate the Index Controller Action with an [OverrideAuthorization] Attribute, which essentially clears all IAuthorization Filters in the upper scopes ( controller, global, etc. ). Hence, the [RequireHttps] Attribute does not apply to this controller action and the Index Action can be invoked either with HTTP or HTTPS.

Attribute Routing in ASP.NET MVC 5

AntiForgeryToken() helper

AntiForgeryToken() helper example

What are the new features of MVC 3?

ASP.NET MVC 3 shipped just 10 months after MVC 2 in Jan 2011. Some of the top features in MVC 3 included:

What are the new features of MVC 4?

The following are the top features of MVC 4:

Explain "page lifecycle" of ASP.NET MVC

The following processes are performed by ASP.NET MVC page::

Advantages of MVC Framework

What is meant by Separation of Concerns?

As per Wikipedia 'the process of breaking a computer program into distinct features that overlap in functionality as little as possible'. The MVC design pattern aims to separate content from presentation and data-processing from content. 

Where do we see Separation of Concerns in MVC?

Between the data-processing (Model) and the rest of the application.

When we talk about Views and Controllers, their ownership itself explains separate. The views are just the presentation form of an application, it does not need to know specifically about the requests coming from the controller. The Model is independent of View and Controllers, it only holds business entities that can be passed to any View by the controller as required for exposing them to the end user. The controller is independent of Views and Models, its sole purpose is to handle requests and pass it on as per the routes defined and as per the need of rendering the views. Thus our business entities (model), business logic (controllers) and presentation logic (views) lie in logical/physical layers independent of each other.

What is Razor View Engine?

Razor is the first major update to render HTML in MVC 3. Razor was designed specifically as a view engine syntax. It has one main focus: code-focused templating for HTML generation. Here's how that same markup would be generated using Razor:

@model MvcMusicStore.Models.Genre

@{ViewBag.Title = "Browse Albums";}

<div class="genre">

<h3><em>@Model.Name</em> Albums</h3>

<ul id="album-list">

@foreach (var album in Model.Albums)

{

<li>

<a href="@Url.Action("Details", new { id = album.AlbumId })">

<img alt="@album.Title" src="@album.AlbumArtUrl" />

<span>@album.Title</span>

</a>

</li>

}

</ul>

</div>

The Razor syntax is easier to type, and easier to read. Razor doesn't have the XML-like heavy syntax of the Web Forms view engine.

What is AuthConfig.cs in MVC 4?

"AuthConfig.cs" configures security settings, including sites for OAuth login.

What is BundleConfig.cs in MVC 4?

"BundleConfig.cs" in MVC4 registers bundles used by the bundling and minification system. Several bundles are added by default, including jQuery, jQueryUI, jQuery validation, Modernizr, and default CSS references.

What is FilterConfig.cs in MVC 4?

This is used to register global MVC filters. The only filter registered by default is the HandleErrorAttribute, but this is a great place to put other filter registrations.

What is RouteConfig.cs in MVC 4?

"RouteConfig.cs" holds the granddaddy of the MVC config statements and Route configuration. 

What is WebApiConfig.cs in MVC 4?

Used to register Web API routes, as well as set any additional Web API configuration setting

The various templates are as follows:

What are the default Top-level directories created when adding a MVC 4 application?

The default Top-level directories are:

What is namespace of ASP.NET MVC?

ASP.NET MVC namespaces as well as classes are located in assembly System.Web.Mvc.

Note: Some of the content has been taken from various books/articles.

What is System.Web.Mvc namespace?

This namespace contains classes and interfaces that support the MVC pattern for ASP.NET Web applications. This namespace includes classes that represent controllers, controller

factories, action results, views, partial views, and model binders.

What is System.Web.Mvc.Ajax namespace?

The System.Web.Mvc.Ajax namespace contains classes that support Ajax scripting in an ASP.NET MVC application. The namespace includes support for Ajax scripts and Ajax option settings as well.

What is System.Web.Mvc.Async namespace?

The System.Web.Mvc.Async namespace contains classes and interfaces that support asynchronous actions in an ASP.NET MVC application.

What is System.Web.Mvc.Html namespace?

The System.Web.Mvc.Html namespace contains classes that help render HTML controls in an MVC application. This namespace includes classes that support forms, input controls, links, partial views, and validation.

Razor 

@foreach (var item in items) {

<span>Item @item.Name.</span>

}

Web Forms 

<% foreach (var item in items) { %>

<span>Item <%: item.Name %>.</span>

<% } %>

override an action in mvc controller

[HttpGet][ActionName("AnyAction")]ActionResult YourAction(firstModel model1) { ... }[HttpPost][ActionName("AnyAction")]FileContentResult YourAction(secondModel model1) { ... }

1. What is main focus of ASP.NET MVC 4?

Ans. The main focus of ASP.NET MVC 4 is making it easier to develop mobile web applications. Other than mobile web applications it’s focus is also on better HTML5 support and making ASP.NET MVC web application cloud ready. Using new features of ASP.NET MVC 4 you can develop web applications that can work well across different mobile devices and desktop web browsers.

2. What is ASP.NET Web API?

Ans. ASP.NET Web API is a framework for building and consuming HTTP Services. It supports wide range of clients including browsers and mobile devices. It is a great platform for developing RESTful services since it talks HTTP.

3. You can also develop RESTful services using WCF, then why this new framework Web API?

Ans. Yes we can still develop RESTful services with WCF, but there are two things that prompt users to use ASP.NET Web API over WCF for development of RESTful services. First one is ASP.NET Web API is included in ASP.NET MVC which obviously increases TDD approach in the development of RESTful services. Second one is for developing RESTful services in WCF you still needs lot of configurations, URI templates, contracts and endpoints which developing RESTful services using ASP.NET Web API is simple.

4. What are the enhancements done in default project template of ASP.NET MVC 4?

Ans. The enhanced default project template is modern-looking. Along with cosmetic enhancements, it also employs adaptive rendering to look nice in both desktop and mobile browsers without need of any kind of additional customization.

5. Why separate mobile project template while you can render your web application in mobile without additional customization?

Ans. The mobile project template touch-optimized UI using jQuery.Mobile.MVC NuGet Package for smart phones and tablets.

6. What is Display Modes?

Ans. Display Modes is new feature provided in ASP.NET MVC 4. It lets an application select views depending on the browser which is making request. For example, if a desktop browser requests home page of an application it will return Views\Home\Index.cshtml view and if a mobile browser requests home page it will return Views\Home\Index.mobile.cshtml view.

7. Does ASP.NET MVC 4 supports Windows Azure SDK?

Ans. Yes, ASP.NET MVC 4 supports Windows Azure SDK version 1.6 or higher.

8. What is Bundling and Minification feature provided in ASP.NET MVC 4?

Ans. It reduces number of HTTP requests that a web page needs to make. Bundling and Minification combines individual files into single, bundled file for scripts and CSS and then reduce the overall size by minifying the contents of the bundle.

9. While developing application using ASP.NET MVC 4, I want to provide authentication using popular sites like Facebook or twitter into my web application, is it possible in ASP.NET MVC 4?

Ans. Yes, using DotNetOpenAuth library we can provide authentication using OAuth or OpenID providers. In ASP.NET MVC 4 Internet project template includes this library.

10. What’s the difference between Empty MVC Project template in ASP.NET MVC 3 and ASP.NET MVC 4?

Ans. The ASP.NET MVC 4 Empty project template is really empty. It does not contain any css and js files as compared to previous Empty project template, which contains all these files.

11. What are the main features of ASP.NET MVC used by ASP.NET Web API?

Ans.

Routing: ASP.NET Web API uses same convention for configuration mapping that ASP.NET MVC provides.

Model Binding and Validation: ASP.NET Web API uses same model binding functionality, but tailored to HTTP specific context related operations only.

Filters: The ASP.NET Web API uses lots of filters built-in MVC.

Unit Testing: Now it’s based on MVC, truly unit testable.

12. If I want to create resource oriented services that can use full features of HTTP like cache control for browsers, use URI templates to include Task URIs in your responses, versioning and concurrancy using ETags, pass various content types such as images, documents, HTML pages etc. then which is preferred for development of services, WCF or Web API?

Ans. In such scenario Web API would be preferred choice. Using Web APIs we can develop services which utilizes full features of HTTP.

13. Suppose I want to develop services which supports special scenarios like one way messaging, duplex communication, message queues, ete then which is the best way to develop services, WCF or Web API?

Ans. In this scenario WCF suits the requirement. WCF provides all kine of messaging facility.

14. Now, if I want to create services which are exposed over various transport channels like TCP, Named Pipe or even UDP. I also want the support of HTTP transport channel when other transport channels are unavailable then which is the preferred way, WCF or Web API and why?

Ans. For such scenario WCF is preferred way for development of services because WCF support almost all kind of transport mechanism and we need to expose SOAP-based and WebHTTP-based bindings.

15. What is the difference between asynchronous controller implementation between ASP.NET MVC 3 and ASP.NET MVC 4? Can you explain in detail?

Ans. There is large difference between the working and implementation mechanism between ASP.NET MVC 3 and ASP.NET MVC 4.

In ASP.NET MVC 3, to implement asynchronous controller/methods you need to derive controller from AsyncController rather than from plain Controller class. You need to create two action methods rather than one. Fist with suffix “Async” keyword and second with “Completed” suffix. The method which initiated asynchronous process must end with “Async” and the method which is invoked when the asynchronous process finishes must end with “Completed”. Following is example showing the same.

//Synchronous Implementation

public class SynchronousTestController : Controller

{

    public ActionResult Index()

    {

        method1();

        method2();

        return View();

    }

}

//Asynchronous Implementation in ASP.NET MVC 3

public class AsynchronousTestController : AsyncController

{

    public void IndexAsync()

    {

        method1();

        method2();

    }

    public ActionResult IndexCompleted()

    {

        return View("Index");

    }

}

The ASP.NET MVC 4 Controller class in combination .NET 4.5 enables you to write asynchronous action methods that return an object of type Task. The .NET Framework 4 introduced an asynchronous programming concept referred to as a Task and ASP.NET MVC 4 supports Task. The .NET Framework 4.5 builds on this asynchronous support with the await and async keywords that make working with Task objects much less complex than previous asynchronous approaches. The await keyword is syntactical shorthand for indicating that a piece of code should asynchronously wait on some other piece of code. The async keyword represents a hint that you can use to mark methods as task-based asynchronous methods. To implement asynchronous action method in ASP.NET MVC 4 we do no need to derive our controller class from AsyncController, async and await in cooperation with Task will do the magic. To mark the action method asynchronous use async in method signature. To wait for the other method to finish use await and to call multiple parallel methods use Task. The asynchronous method will return Task instead of plain ActionResult.

Asynchronous programming is writing code that allows several things to happen at the same time without "blocking", or waiting for other things to complete.

public class AsyncronousTestController : Controller

{

    public async Task<ActionResult> IndexAsync()

    {

        //if single method

        //await method();

        //if multiple methods

        await Task.WhenAll(method1(), method2());

        return View("Index");

    }

}

Here the await keyword does not block the thread execution until the task is complete. It signs up the rest of the method as a callback on the task, and immediately returns. When the awaited task eventually completes, it will invoke that callback and thus resume the execution of the method right where it left off.

16. Can you tell us some guidelines for when to use synchronous and when to use asynchronous approach?

Ans. In following situations synchronous approach is more suited.

For asynchronous approach some of the guidelines are

17. Which latest version of Entity Framework is included by ASP.NET MVC 4? What is the advantage of it?

Ans. ASP.NET MVC 4 is included Entity Framework 5. The main advantage of Entity Framework 5 is it’s new feature called database migration. It enables you to easily evolve your database schema using a code-focused migration while preserving the data in the database.

18. What is ASP.NET MVC 4 recipe? Can you explore something on recipes?

Ans. In technical language ASP.NET MVC 4 recipe is nothing but a dialog box that is delivered via NuGet with associated UI and code used to automate specific task. It’s like GUI for NuGet Package Manager. Recipes are set of assemblies which are loaded dynamically by Managed Extensibility Framework (MEF). MEF provides plugin model for applications. The main use of recipes are to automate development task, tasks that are encapsulated into recipes and used over and over again. For example, adding ajax grid to view or manipulating multiple areas of the application can be automated using ASP.NET MVC 4 recipes.

18. What are the provisions for real time communication in ASP.NET MVC 4?

Ans. ASP.NET MVC 4 supports WebSockets along with the new open source framework SignalR which allows to set up real time multi-user communication through open TCP sockets.

19. What is the enhancement provided related to custom controller in ASP.NET MVC 4?

Ans. In ASP.NET MVC 4 you can place custom controller to custom locations. In ASP.NET MVC 3 you can only place custom controllers inside the Controllers folder.

Explanation of OAuth

OAuth is an authentication protocol that allows the client application’s user to authenticate through an OAuth service provider along with appropriate authorization.

Basically the OAuth mechanism involves three parties and they are the user, client application and the OAuth services provider. The workflow mentioned below will explain things easily.

Advantage of using OAuth in Asp.Net MVC

As I said that Asp.Net MVC 4 is provided with the OAuth feature, it is also important for me to explain the advantage of enabling it. Following are the advantages of enabling OAuth in an Asp.Net MVC 4 application.

$.ajax({

 url: 'api/authors?authenticationToken=abcxyz',

 type: 'POST',

  data: JSON.stringify(author),

 dataType: 'json',

 success: function (data) {

   alert(data);

}});

Authentication and Authorization in ASP.NET Web API

SSL provides a complete secure channel, with authentication, message integrity, and message encryption.

Several common authentication schemes are not secure over plain HTTP. In particular, Basic Authentication and forms authentication send unencrypted credentials. To be secure, these authentication schemes must use SSL. In addition, SSL client certificates can be used to authenticate clients.