Wednesday, July 31, 2013

MVC -Performance Improvement-Removed unused ViewEngine-WebFormViewEngine Or RazorViewEngine

Nicely explained..
https://www.simple-talk.com/blogs/2013/02/27/tip-2-expanded-remove-unused-view-engines//

Just to tell long story short...

Sometimes we referenced View that may not exist in such case MVC framework throws error and specify that it tried to search view in different possible location but they do not exist,

Say--http://localhost/home
So View engine will try to search View\Home\index.chtml for source file but if the file don't exists it throws exception listing possible extension and location seach
 WebFormViewEngine
~views/home/index.aspx
~views/home/index.ascx
~views/Shared/index.aspx
~views/Shared/index.ascx

 RazorViewEngine
~views/home/index.chtml
~views/home/index.chtml
~views/Shared/index.chtml
so on.
~views/Shared/index.VBhtml

If we're using only RazorViewEngine then we can get rid of rest of ViewEngine just by adding below lines of code in Global.asax

ViewEngines.Engines.Clear();
 ViewEngines.Engines.Add(new RazorViewEngine());
 

MVC -HandleUnknownAction -Avoid Redundant Code Action Method in Controller

HandleUnknownAction:

Just overirde Controller Method HandleUnknownAction- Now we can merge redundant method which does the same thing of loading view .Such view does nothing just rendering view. There can be scenario when the action is called but there is no relevant action defined in controller in such case we can override this method to handle unknown calls.

public class CustomerController : Controller
{
    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Details()
    {
        return View();
    }
   
    public ActionResult Help()
    {
        return View();
    }
}

Just overirde Controller Method HandleUnknownAction- Now we can merge redundant method which does the same thing of loading view .Such view does nothing just rendering view. There can be scenario when the action is called but there is no relevant action defined in controller in such case we can override this method to handle unknown calls.

public class CustomerController : Controller
{
    protected override void HandleUnknownAction(string actionName)
    {
        this.View(actionName).ExecuteResult(this.ControllerContext);
    }
}

MVC Internal Controller Action Method with No View with No direct Browser Access

Sometimes we would like to call controller action method from View without the method completely tied to view. What I mean is direct browser access such as http://localhost/Home/GetCustomer/2
Now we have scenario where we want such action method to rendered partial view using html.action() that in turns calls Action method in controller. For such cases we have [ChildOnlyAction]attribute.

View-> html.action -> Calls Action Controller -> loads partial view

[ChildOnlyAction]
public ActionResult CanOnlyBeCalledInternalByView()
{

    return PartialView();
}

Avoid MVC Open Redirection attack

Open Redirection attack


Sample URL.
Scenario 1: Normal Login process
The first address, redirects users to the Home/Index after successful Login

1. http://www.codingtips.net/Account/login?ReturnUrl=/Home/Index

Scenario 2: Hacked /Tampered URL.
The second address redirects users to the Unknown website, it means the second address is manipulated by the hackers.

2. http://www.codingtips.net/Account/login?ReturnUrl=www.UnknownSite.com

Remedy: Prevent URL redirection to unknown site. If URL tampered it will always return to home page.

private ActionResult Redirect(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

 

Tuesday, July 30, 2013

Glimpse A cool profiling Tool for MVC by Nuget Package.

Next time you want a quick profiling tool with trendy looks ,indeed a useful snoop watch dog, then your search ends here. We've Glimpse to give more ...all you need to do is

1. Go to VS2012

2. Click on tools-Library Package Manager

3. Console Appears-Type Install-package Glimpse.MVC4

4. Profiler is installed for you.

Get Started: How?

Use website url say for e.g http://sample/Glimpse.axd

Click on Glimpse enable button.

Browse your site as usual http://sample and you will find small icon of Glimpse tool tip appears.

Click on icon you see the petty performance profiler stats. Isn't that cool!

Here is the Hub...

http://www.nuget.org/packages/Glimpse.Mvc4/1.3.0



 

Thursday, July 25, 2013

Customize MVC Folder Structure


MVC Architecture comes with its own predefined folder structure and its engine operates only when class is added in respective folder such as controller, model or View. Sometimes it becomes unmanageable  when we’ve large set of source files and views that are required to be maintained. We’ve a workaround by which we can defined our own folder structure. Here I demonstrated partial view scenario where we can have our designed folder for partial view .chtml in place of Shared folder view. To achieve this, just extend [RazorviewEngine] class and add this class file in{ Model/ACARazorViewEngine }and instantiate it in Global.asax- application_start event.

 

Step 1- Add ACARazorViewEngine in Model

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

namespace SampleWeb

{

  

    public class ExtentRazorViewEngine : RazorViewEngine

    {

        public ExtentRazorViewEngine ()   

        {       

            var newLocationFormat = new[]                                   

            {      "~/Views/PartialViews/StaticUCS/{0}.cshtml",

"~/Views/PartialViews/Dialoq/{0}.cshtml"          

            };       

            PartialViewLocationFormats = PartialViewLocationFormats.Union(newLocationFormat).ToArray();   

        }

   

    }

 

}

Step 2: Instantiate the View Engine

  public class MvcApplication : System.Web.HttpApplication

    {

        protected void Application_Start()

        {

            ViewEngines.Engines.Add(new ACARazorViewEngine());

        }

    }

 

Wednesday, July 3, 2013

Cross orgin Resource Sharing CORS now is dynamic MVC5 and VS2013 review release.

The enhancement to decisively include CORS configuration dynamically will prove to be good move in new release of .net framework. Yes, the resource sharing across different services such twitter, facebook and many more. Its a way to allow resource across domain depending upon the level of interaction. The point is not to narrate many things here. To keep discussion short and up to point. VS2013 and MVC5 preview release has gotten into new innovation to configure CORS dynamically.

Highlights we can have:
Now we can configure CORS via database . No require to restart service. Client access can be configured at runtime.


public interface ICorsPolicyProvider
   7:      {
   8:          /// 
   9:          /// Gets the .
  10:          /// 
  11:          /// The request.
  12:          /// The cancellation token.
  13:          /// The .
  14:          Task GetCorsPolicyAsync(HttpRequestMessage request, CancellationToken cancellationToken);
  15:      }
 
Important Attributes that can be applied to controller methods.
 
 
[EnableCors("*", "*", "*")]
[DisableCors]
 
For more details check this out. MSDN Blog