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
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.
Model: The business entity on which the overall application operates. Many applications use a persistent storage mechanism (such as a database) to store data. MVC does not specifically mention the data access layer because it is understood to be encapsulated by the Model. (or) Model represents shape of the data and business logic. It maintains the data of the application. Model objects retrieve and store model state in a database.
View: The user interface that renders the Model into a form of interaction. View is a user interface. View display data using model to the user and also enables them to modify the data
Controller: Handles a request from a View and updates the Model that results in a change of the Model's state. Controller handles the user request. Typically, user interact with View, which in-tern raises appropriate URL request, this request will be handled by a controller. The controller renders the appropriate view with the model data as a response. Controller is a request handler.
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.
Authorization filters – Implements the IAuthorizationFilter attribute.
Action filters – Implements the IActionFilter attribute.
Result filters – Implements the IResultFilter attribute.
Exception filters – Implements the IExceptionFilter attribute.
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.
OutputCache – This action filter caches the output of a controller action for a specified amount of time.
HandleError – This action filter handles errors raised when a controller action executes.
Authorize – This action filter enables you to restrict access to a particular user or role.
[OverrideAuthorization]
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 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:
The Razor view engine.
Support for .NET 4 Data Annotations.
Improved model validation
Greater control and flexibility with support for dependency resolution and global action filters.
Better JavaScript support with unobtrusive JavaScript, jQuery Validation, and JSON binding.
Use of NuGet to deliver software and manage dependencies throughout the platform.
What are the new features of MVC 4?
The following are the top features of MVC 4:
ASP.NET Web API.
Enhancements to default project templates.
Mobile project template using jQuery Mobile.
Display Modes.
Task support for Asynchronous Controllers.
Bundling and minification.
Explain "page lifecycle" of ASP.NET MVC
The following processes are performed by ASP.NET MVC page::
App initialization
Routing
Instantiate and execute controller
Locate and invoke controller action
Instantiate and render view
Advantages of MVC Framework
Provides a clean separation of concerns among UI (Presentation layer), model (Transfer objects/Domain Objects/Entities) and Business Logic (Controller).
Easy to UNIT Test.
Improved reusability of views/model. One can have multiple views that can point to the same model and vice versa.
Improved structuring of the code.
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:
The Internet Application template: This contains the beginnings of an MVC web application, enough that you can run the application immediately after creating it
and see a few pages. This template also includes some basic account management functions that run against the ASP.NET Membership.
The Intranet Application template: The Intranet Application template was added as part of the ASP.NET MVC 3 Tools Update. It is similar to the Internet Application template, but the account management functions run against Windows accounts rather than the ASP.NET Membership system.
The Basic template: This template is pretty minimal. It still has the basic folders, CSS, and MVC application infrastructure in place, but no more. Running an application created using the Empty template just gives you an error message.
Why use Basic template? The Basic template is intended for experienced MVC developers who want to set up and configure things exactly how they want them.
The Empty template: The Basic Template was previously called the Empty Template, but developers complained that it wasn't quite empty enough. With MVC 4, the previous Empty
Template was renamed Basic, and the new Empty Template is about as empty as possible.
It has the assemblies and basic folder structure in place, but that's about it.
The Mobile Application template: The Mobile Application template is preconfigured with jQuery Mobile to jump-start creating a mobile only website. It includes mobile visual themes, a touch-optimized UI, and support for Ajax navigation.
The Web API template: The ASP.NET Web API is a framework for creating HTTP services.
The Web API template is similar to the Internet Application template but is streamlined for Web API development. For instance, there is no user account management functionality, since Web API account management is often significantly different from standard MVC account management. Web API functionality is also available in the other MVC project templates, and even in non-MVC project types.
What are the default Top-level directories created when adding a MVC 4 application?
The default Top-level directories are:
/Controllers: For Controller classes that handle URL requests
/Models: For classes that represent and manipulate data and business objects
/Views: For UI template files that are responsible for rendering output like HTML
/Scripts: For JavaScript library files and scripts (.js)
/Images: For images used in your site
/Content: For CSS and other site content, other than scripts and images
/Filters: For code filters
/App_Data: To store data files you want to read/write
/App_Start: For configuration code of features like Routing, Bundling, Web API.
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.
The operations are simple or short-running.
Simplicity is more important than efficiency.
The operations are primarily CPU operations instead of operations that involve extensive disk or network overhead. Using asynchronous action methods on CPU-bound operations provides no benefits and results in more overhead.
For asynchronous approach some of the guidelines are
You’re calling services that can be consumed through asynchronous methods, and you’re using .NET 4.5 or higher.
The operations are network-bound or I/O-bound instead of CPU-bound.
Parallelism is more important than simplicity of code.
You want to provide a mechanism that lets users cancel a long-running request.
When the benefit of switching threads out weights the cost of the context switch. In general, you should make a method asynchronous if the synchronous method waits on the ASP.NET request thread while doing no work. By making the call asynchronous, the ASP.NET request thread is not stalled doing no work while it waits for the web service request to complete.
Testing shows that the blocking operations are a bottleneck in site performance and that IIS can service more requests by using asynchronous methods for these blocking calls.
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.
1. An OAuth client makes a request to the OAuth service provider using a request token (plain and secret).
2. The service provider then prompts the user to provide the authentication credentials.
3. Once the authentication is successful the service provider generates an Access Token (this access token is defined with specific authorization) and provided to the client.
4. The client can then make use of the access token to query for the service providers resources, which it is entitled to.
5. The access token expires after a time span.
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.
1. No need to implement your application level authentication and can be delegated to the OAuth service provider.
2. Your application users can use their pre-existing OAuth service provider (Facebook, Twitter, etc.) credentials instead of creating a separate one for your application.
3. Your Asp.Net MVC application can access the resources of the OAuth service providers (Facebook, Twitter, etc.) using the access token issued to it at any point of time before expiry.
4. In case if you are striving to bring a single sign on for all the applications in your enterprise architecture.
$.ajax({
url: 'api/authors?authenticationToken=abcxyz',
type: 'POST',
data: JSON.stringify(author),
dataType: 'json',
success: function (data) {
alert(data);
}});
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.