Tuesday, July 15, 2014

ASP.NET MVC Notes

What is the difference between ViewData, ViewBag and TempData?

  • In order to pass data from controller to view and in next subsequent request, ASP.NET MVC framework provides different options i.e., ViewDataViewBag and TempData. Both ViewBag and ViewData are used to communicate between controller and corresponding view. But this communication is only for server call, it becomes null if redirect occurs. So, in short, it's a mechanism to maintain state between controller and corresponding view.
  • ViewData is a dictionary object while ViewBag is a dynamic property (a new C# 4.0 feature). ViewData being a dictionary object is accessible using strings as keys and also requires typecasting for complex types. On the other hand, ViewBag doesn't have typecasting and null checks.
  • TempData is also a dictionary object that stays for the time of an HTTP Request. So, Tempdata can be used to maintain data between redirects, i.e., from one controller to the other controller.
What are the different ways of passing information from the controller to view ?
  1. As a strongly typed model object. @Model IEnumerable<type>
  2. As a dynamic type (using @model dynamic)
  3. Using the ViewBag
How to return/post JSON from Controller ?
// set up a click handler for the button to get the list of old things
$("#get-oldthings").click(function () {
    $.post('<%= Url.Action("GetOldThings") %>', { minAge: 10 }, ParseThingList);
});

[HttpPost]
public ActionResult GetOldThings(int minAge)
{
    IOldThingRepository repository = new OldThingRepository();
    return Json(repository.GetOldThings(minAge));
}

[HttpGet]
public JsonResult GetOldThings(int minAge)
{
    IOldThingRepository repository = new OldThingRepository();
    return Json(repository.GetOldThings(minAge), JsonRequestBehavior.AllowGet);

Explain ASP.NET MVC application life cycle ? 



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.

Whats the difference between Html.RenderPartial() and Html.Partial() ? 
@Html.RenderPartial("~/Views/Shared/_Product.cshtml", product);

RenderPartial renders the HTML O/P directly in the HttpOutputStream while Partial() can be retreived into a variable

Difference between Html.RenderPartial(), Html.Partial(), Html.RenderAction(), Html.Action()

  • There is a big difference between RenderAction and RenderPartialRenderPartial will render a View on the same controller (or a shared one), while RenderAction will actually perform an entire cycle of MVC, 
  • it will instantiate the controller (any controller you mention, not just the current one), it will execute the action, and it will then return and render the result. 
  • RenderPartial is more like an include 
How can we do validations in MVC ?

  • MVC is by using data annotations. Data annotations are nothing but attributes which can be applied on model properties

public class Customer
{
    [Required(ErrorMessage="Customer code is required")]
    public string CustomerCode
    {
        set;
        get;
    } 
}  

//Displaying Messages
<% using (Html.BeginForm("PostCustomer", "Home", FormMethod.Post))
{ %>
<%=Html.TextBoxFor(m => m.CustomerCode)%>
<%=Html.ValidationMessageFor(m => m.CustomerCode)%>
<input type="submit" value="Submit customer data" />

<%}%> 

What are the other data annotation attributes for validation in MVC?

//If you want to check string length, you can use StringLength.
[StringLength(160)]
public string FirstName { get; set; }

//In case you want to use a regular expression, you can use the RegularExpression attribute.
[RegularExpression(@"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}")]public string Email { get; set; }

//If you want to check whether the numbers are in range, you can use the Range attribute.
[Range(10,25)]public int Age { get; set; }

//compare the value of one field with another field, we can use the Compare attribute.
public string Password { get; set; }[Compare("Password")]public string ConfirmPass { get; set; }

//To get a particular error message , you can use the Errors collection.
var ErrMessage = ModelState["Email"].Errors[0].ErrorMessage;

//If you have created the model object yourself you can explicitly call TryUpdateModel in your controller to //check if the object is valid or not.

TryUpdateModel(NewCustomer);

//In case you want add errors in the controller you can use the AddModelError function.
ModelState.AddModelError("FirstName", "This is my server-side error.");

Difference between Web Services / Web API
SOAPWEB API
SizeHeavy weight because of complicated WSDL structure.Light weight, only the necessary information is transferred.
ProtocolIndependent of protocols.Only for HTTP protocol
FormatsTo parse SOAP message, the client needs to understand WSDL format. Writing custom code for parsing WSDL is a heavy duty task. If your client is smart enough to create proxy objects like how we have in .NET (add reference) then SOAP is easier to consume and call.Output of WebAPI are simple string messages, JSON, simple XML format, etc. So writing parsing logic for that is very easy.
PrinciplesSOAP follows WS-* specification.WebAPI follows REST principles. 


What is Bundling and Minification ? 
Bundling
ASP.NET is adding a feature that makes it easy to “bundle” or “combine” multiple CSS and JavaScript files into fewer HTTP requests. This causes the browser to request a lot fewer files and in turn reduces the time it takes to fetch them. 

Minification 
This is a process that removes whitespace, comments and other unneeded characters from both CSS and JavaScript. The result is smaller files, which will download and load in a browser faster. 

How to implement Bundling in ASP.NET MVC ? 

1) 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.
bundles.Add(new ScriptBundle("~/Scripts/MyScripts").Include(
"~/Scripts/*.js")); 

public  class BundleConfig
{
    public static void RegisterBundles(BundleCollection bundles)
    {
        bundles.Add(new ScriptBundle("~/Scripts/MyScripts").Include(
           "~/Scripts/*.js"));
        BundleTable.EnableOptimizations = true;
    }

2) Once you have combined your scripts into one single unit we then to include all the JS files into the view using the below code. The below code needs to be put in the ASPX or Razor view.

 <%= Scripts.Render("~/Scripts/MyScripts")  %>

7/16 =>
Creating Route/Custom Routes?
When a user enters this request, you want to return the blog entry that corresponds to the date 12/25/2009. In order to handle this type of request, you need to create a custom route.

E.g. /Archive/12-25-2009

routes.MapRoute( "Blog", // Route name "Archive/{entryDate}", // URL with parameters new { controller = "Archive", action = "Entry" } // Parameter defaults );

public class ArchiveController : Controller { public string Entry(DateTime entryDate) { return "You requested the entry from " + entryDate.ToString(); } }
The MVC framework is smart enough to convert the entry date from the URL into a DateTime value automatically. If the entry date parameter from the URL cannot be converted to a DateTime

Creating Route Constraint
route constraints to restrict the browser requests that match a particular route. You can use a regular expression to specify a route constraint.

routes.MapRoute( "Product", "Product/{productId}", new {controller="Product", action="Details"}, new {productId = @"\d+" } );

Creating a Custom Route Constraint


  • A custom route constraint enables you to prevent a route from being matched unless some custom condition is matched.
  • You implement a custom route constraint by implementing the IRouteConstraint interface.bool Match( HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection )
  • Usage 
  • routes.MapRoute(
"Admin", "Admin/{action}", new {controller="Admin"}, new {isLocal=new LocalhostConstraint()} );

How Requests are processed by the Thread Pool

  • In the web server, the .NET Framework maintains a pool of threads that are used to service ASP.NET requests. When a request arrives, a thread from the pool is dispatched to process that request. If the request is processed synchronously, the thread that processes the request is busy while the request is being processed, and that thread cannot service another request. T
  • The number of threads in the thread pool is limited (the default maximum for .NET 4.5 is 5,000). 
  • In large applications with high concurrency of  long-running requests, all available threads might be busy. This condition is known as thread starvation. When this condition is reached, the web server queues requests. If the request queue becomes full, the web server rejects requests with an HTTP 503 status (Server Too Busy). 
  • Each new thread added to the thread pool has overhead (such as 1 MB of stack memory).
  • When you’re doing asynchronous work, you’re not always using a thread. For example, when you make an asynchronous web service request, ASP.NET will not be using any threads between the async method call and the await.  

Choice Synchronous vs Asynchronous Method 


Use synchronous methods for the following conditions:
  • The operations are simple or short-running.
  • 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.
Use asynchronous methods for the following conditions:
  • You're calling services that can be consumed through asynchronous methods, and you're using .NET 4.5 or higher. UI threads are not blocked.
  • The operations are network-bound or I/O-bound instead of CPU-bound.
  • Parallelism is more important.
  • You want to provide a mechanism that lets users cancel a long-running request.
  • When the benefit of switching threads out weighs 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.
Using Aysnchronous Methods in ASP.NET MVC

  • 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<ActionResult>
  • The .NET Framework 4.5 builds on this asynchronous support with  the await and async keywords that make working with Task objects.
  • 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
E.g.
//Service Provider
public class DbHelper
{
    public async Task<List<Customer>> GetCustomerDataAsync()
    {
        NorthwindEntities db = new NorthwindEntities();
        var query = from c in db.Customers
                    orderby c.CustomerID ascending
                    select c;
        List<Customer> data = await query.ToListAsync();
        return data;
    }
}

//asynch Controller Methods
public async Task<ActionResult> IndexAsync()
{
    DbHelper helper = new DbHelper();
    List<Customer> data = await helper.GetCustomerDataAsync();
    return View(data);
}

Test Driven Development
ASP.NET MVC application provide a very good support for TDD because we can write unit test directly against our controllers without needing any web server

[TestClass]
    public class GroupControllerTest
    {

        [TestMethod]
        public void Index()
        {
            // Arrange
            var controller = new GroupController();

            // Act
            var result = (ViewResult)controller.Index();
        
            // Assert
            Assert.IsInstanceOfType(result.ViewData.Model, typeof(IEnumerable));
        }
    }

How to integrate JQuery and ASP.NET MVC ?
How to invoke Controller Methods from JQuery ?
CRUD base operations on a datagrid ?
What is WebAPI  ?
Brief Overview of WebAPI

No comments:

Post a Comment