All posts by Thiyagu

Running Web Application in Multiple Browser Simultaneously

As a web Developer we need to perform cross browser testing in different browser from Visual Studio. In common, we will run the application(pressing F5) after selecting the specific browser from the menu. To test more than one browser simultaneously, VS have an option to set “multiple browser” option. Let we discuss, how to enable multiple browser as a default browser in visual studio.

Why it’s needed?

It is difficult for the developer who working on the browser compatibility because they need to run the solution for every time with different browser. To overcome, in VS has a specific feature that will run the application in many browsers at simultaneously. This feature will be a productivity enhancer for web developers who all working on the browser compatibility.

Step:1

As below image, click the run to show the list of browsers as shown below. As default, we will able to see all added browser and with default browser as checked

Enable Multiple borwser option in visual studio

Step:2

Click on the “Browse With” option to open a new wizard as shown below. From this screen, we can choose a browser that needs run simultaneously for our application. Select required browsers by pressing the control key (for multiple selection) and click “Set as Default” button.

Step: 3

Now we can see the “Multiple Browsers” item present as default in the menu. Now run the application without debugging(Ctrl+F5) mode to launch in all browser at the same time.

Note :

If we run the application in the debugging mode (F5) then it will show popup for choosing the single browser.

Happy Codding !!!

ValidateInput Attribute in ASP.NET MVC

In some scenario, we need to send HTML value/content as input to our application from the view to the controller. In some time we use HTML Editors to save the HTML content if the end user accept. By default, ASP.NET MVC framework prevents you from submitting the HTML content/potentially malicious content to the controller, for avoiding the cross site scripting attack. This feature is called request validation.

Used Version Detail : Visual studio 2013, Version 4.5, MVC 5

Controller:

This is the simple ValideInput controller and it will render the view as output. And in the form submission, it will redirect to GetDescription() action and bind the view. In default, ValidateInput attribute parameter is true (ValidateInput(true)).

public ActionResult ValideInput()
{
return View();
}
public ActionResult GetDescription(FormCollection _inputDescription)
{
 //your logic
 return View();
}

View:

Here it is the view for getting the form data from the user, which contain one textbox and submit button inside the BeginForm. After user submission it will redirect to the GetDescription action method inside the dotnethelpers controller.

<!DOCTYPE html>
<html>
<head>
<title>Index</title>
</head>
<body>
<div>
@{
using (Html.BeginForm("GetDescription", "dotnethelpers"))
{
<input type="txtDescription" name="description" /> <br />
<input type="submit" value="Submit Form" />
}
}
</div>
</body>
</html>

Output :

As per below screen, we are entering a content with HTML elements. And once we click on the submit button, then it will throw the error as like below because, in default ASP.NET MVC prevents the HTML element as form data. In simple, ASP.NET MVC cannot send HTML values to the controller.

Note:

This is not an issue, it is default security validation handling by the ASP.NET MVC. In some scenario we need to override this  security by using the ValidateInput attribute to prevent HTML explicitly.

Implementing ValidateInput attribute:

In default, ValidateInput parameter is true (ValidateInput(true).

[ValidateInput(false)] public ActionResult GetDescription(FormCollection _inputDescription) { return View(); }

GetDescription View:

<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>GetDescription</title>
</head>
<body>
<div> 
<h1>GetDescription View : Making validation using ValidateInput(false) attribute</h1>
</div>
</body>
</html>

Run the application and apply the Html element as input (Ex : http://localhost:62536/dotnethelpers/ValideInput).
Now its redirect to the “GetDescription View” instead of throwing the potential error as shown below.

 

Make Note Before Use:

  • XSS (Cross site scripting) is a security attack where this can inject malicious code while input the entry.
  • In ASP.NET MVC, it prevented the above attract by default.
  • ValidateInput attribute is unsafe because it still allows others to inject malicious code.
  • It can be applied on the controller/action level, but not for model property.
  • Model level can be handle by using [AllowHtml] attribute
  • public class UserDetails
    {
    [AllowHtml]
    public string userDescription { get; set; }
    }

 

Happy codding !!!

Error Handling in ASP.Net MVC Using HandleError Attribute

Exception handling plays an important role in any application, whether it is a web application or a Windows Forms application.Implementing a proper exception handling in our application is important. In most scenario, after we caughtthe exception, we have to log the exception details or show a friendly message to the user. ASP.NET MVC provides built-in features for exception handling through exception filters. The HandleError is the default built-in exception filter which is used to handle the exception. In this post, we are going to discuss about the HandleError filter.

What HandleError filter do?

ASP.Net MVC HandleError attribute provides a built-in exception filter. The HandleError attribute in ASP.NET MVC can be applied over the action method as well as a controller or at the global level for handle the exception in controller and action level. While creating our application, the HandleError attribute is automatically included within the Global.asax.cs and registered in FilterConfig.cs as shown below.

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}

It can applied at the global level as well. The HandleError attribute is the default implementation of IExceptionFilter. The HandleError filter handles the exceptions which been raised at the controller/actions. Then it return a custom error view. Let we discuss detail about with example.

Limitation of HandleError Filter:

  • It catch only 500 Http error and not catch HTTP errors like 404,401 ..
  • It has no support to log the exceptions. We can log the exception by create custom error filter by implementing HandleError class.
  • It doesn’t catch the errors that occur outside the controllers and also not catch the ajax calls error too.

Properties in HandleError Attribute

The HandleError Error attribute has a few properties for handling the exception.

ExceptionType: It is used to specify the type of exception to be catch. If this property is not set then it will handles all type exceptions.

TypeId: Set the unique identifier for this attribute

View: Need to specify the name of view. It will redirect to particular view when exception occur.

Master: Master View for displaying the exception.

Example:

Used Version Detail : Visual studio 2013, Version 4.5, MVC 5

While creating ASP.NET MVC application the error.cshtml view is created automatically under the shared folder. Creating our own CustomError.cshtml view for displaying error with custom content for the user.

Controller:

HandleErrorAttribute controller has an index action method. From the below code, When the NullReferenceException error happens in the action Index, then the ASP.NET MVC HandleError attribute will find in a view called “CustomError”, in the shared folder and renders it to the user. (Placing in the “Shared” Folder, will be shared with all controllers).

public class HandleErrorAttributeController : Controller
{
[HandleError(View = "CustomError")]
public ActionResult Index()
{
throw new NullReferenceException();
}
}

Sample Attribute :

  1. [HandleError(ExceptionType = typeof(System.Data.DataException), View = “DatabaseError”)]
  2. [HandleError(ExceptionType = typeof(NullReferenceException), View = “NullReferenceError”)]

Web.config

The HandleError filter works only if the <customErrors> section is turned on in web.config.

<system.web>
<customErrors mode="On"></customErrors>
</system.web>

Output :

Note:

  • The HandleError filter works only if the <customErrors> section is turned on in web.config.
  • We can use HandleError Attribute for the entire application by registering it as a global error handler.

 

LowercaseRoutes – ASP.NET MVC routes to lowercase URLs

About this Article

We aware of that our Asp .Net MVC application generate mixed-case URLs like https://dotnet-helpers.com/Home/About or https://dotnet-helpers.com/home/about. So if we type URLs then it wont consider the upper case or lower case. In ASP.NET MVC, route generates outgoing URLs based on the casing of our controller and action names. By default, ASP.NET MVC controllers are classes and actions are methods,so these outgoing URLs are likely be camel-case.

Having Two URLs make problem in Search Rankings:

In ASP.NET MVC, the URLs generated by the routing mechanism are based on the controller and action names. Technically be considered , this will lead to duplicate pages with the same content. Most SEOs will recommend sticking to have only one version.

Solution :

LowercaseUrls property on the RouteCollection class has introduced in ASP .NET 4.5. Using this property we can lowercase all of our URLs.

Eg : routes.LowercaseUrls = true;

Example :

RouteConfig.cs

Include below pieace of code in the RouteConfig.cs file to convert all the URLs in to lowercase.

public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

routes.LowercaseUrls = true;

routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });

}
}

Controller:

A simple controller which has two action method namely LowerCaseUrls and LoadUserDetails.

public class dotnethelpersController : Controller
{
   public ActionResult LowerCaseUrls()
   {
      return View();
   }

   public ActionResult LoadUserDetails()
   {
       return View();
   }
}

LowerCaseUrls.cshtml :

<!DOCTYPE html>

<html>
<head>
<title>LowerCaseUrls</title>
</head>
<body>
<div>
      @Html.ActionLink("Home", "LoadUserDetails", "Dotnethelpers")
</div>
</body>
</html>

Output:

After clicking the HOME Link it redirecting to the dotnethelpers/loaduserdetails instead of Dotnethelpers/LoadUserDetails

 

Keep Happy Coding !!!

 

Donut Hole Caching in ASP.NET MVC

Donut Hole Caching is the inverse of Donut cache. As the previous statement, the Donut Caching is used to cache a maximum portion of the view/page, but Donut Hole Caching is used to cache only small portion of the view/page. More about Donut Caching refer here . Donut Hole caching procure by OutputCache and ChildActionOnly attribute.

What is in Mind?

Q1 : What is different type of caching in MVC
We can use OutputCache, DonutCache and Donut Hole Cache to cache the content.

Q2 : When can we implement?
OutputCache – Use when need to cache Whole page/View
DonutCache – Use to cache Whole page expect small portion of it.
Donut Hole Cache – Need to cache small portion instead of caching whole page

When to use ?

Let consider the scenario, having a website which contains the home page with dynamic content(maximum of the page) which load the content based on the user login. And also it has News feed section which contain small portion of the page(static content for all user).

In this scenario, we need to cache the common portion of the page for all the users. So here we cache News feed section instead of dynamic content.

How to Implement ?

In ASP.NET MVC, we can cache whole action with OutputCache Attribute. In mean while if we do not want to cache the entire action, we just want to cache the small portion of page/view. Then this can be achieved by using combination of ChildActionExtensions and OutputCache Attribute.

Controller:

From the below code, the LoadNewsFeed content (ie., loading partial view) in the Index view has cached for 60 seconds for all users expect static content which is specified inside the view.The ChildActionOnly attribute ensures that an action method can be called only as a child method from within a view. In simple, ChildActionOnly attribute are treated as non-action method (It treated as normal method). More about ChildActionOnly

public class DonutCacheController : Controller
{
public ActionResult Index()
{
ViewBag.CurrentDataTimeMessage = DateTime.Now.ToString();
return View();
}

[ChildActionOnly] [OutputCache(Duration = 60)] public ActionResult LoadNewsFeed() { ViewBag.CurrentDataTimeMessage = DateTime.Now.ToString(); return View(); } }

View

Creating a view with displaying current time and render LoadNewsFeed partial view in it.

<h2>Index</h2>
<h3>Message from DonutCache -> Index </h3>
<h3>@ViewBag.CurrentDataTimeMessage</h3>

@Html.Action("LoadNewsFeed")

Output:

Run the application, when we browse DonutCache controller then it will load the index view. If we refresh the page before 60 seconds, then the index view will refresh because it has not cached . But LoadNewsFeed has not refreshed every time because it has been cached by using Donut Hole caching.

 

Keep Happy coding…

 

 

Donut Caching with Asp.Net MVC

Donut caching used to cache an entire web page except for one or more small portion of the page. In other words, suppose we want to cache a maximum portion of the view except the minimum portion then we can finalize to use DonutCache. I know while start reading this, many questions will arise. Let us discuss this in “What is in Mind”  section.

What is in Mind?

Q1 : At meantime, we think what will  happen when we use Output Caching ?
The output cache will cache the entire web page.

Q2 : However, what can we do when we want to do the inverse of the Donut Caching?
we want to use Donut hole cache instead of the DonutCache to cache the small portion of the view instead of maximum portion (inverse of DonutCache)

When to use Donut Cache?

Let we assume, having a web site which contains the home page with displaying login user name (small portion will be in dynamic) , and the remaining are static content.

Bad Approach:

If you want to cache users by using OutputCache with VaryByParam User ID, then the entire page will be cached every time for each user with a different user name. This is a bad approach because if 5000 users logged into the site, then there will be 5000 pages have been cached.

Good Approach :

In this scenario, we can use DonutCaching. It is useful when page containing most of the information is rarely Changed and few items changing dynamically( based on the parameter).

Including MVCDonutCaching using NuGet Package:

We can install MVCDonutCaching using NuGet or using Package Manager Console Go to Tools -> Library Package Manager -> Package Manager Console, then type the command “Install-package MvcDonutCaching” in the console as shown below image.

Example :

Once we installed MvcDonutCaching package, we can add the DonutOutputCache attribute to the action or to the controller. Most of the parameter type of OutputCache attribute are also available in the DonutCache as shown below.

 

Controller :

From the below code, the static content in the Index view has cached for 30 seconds for all users expect dynamic content which is specified inside the view(ie., loading partial view).

public class DonutCacheController : Controller
 {
 [DonutOutputCache(Duration = 30)]
 public ActionResult Index()
 {
 ViewBag.CurrentDataTimeMessage = DateTime.Now.ToString();
 return View();
 }

 public ActionResult LoadUserDetail()
 {
 ViewBag.CurrentDataTimeMessage = DateTime.Now.ToString();
 return View();
 }
 }

Partial view :

Create LoadUserDetail.cshtml partial view and display the time from ViewBag. This partial view has been called in the DonutCache ->Index(view)

<h2> Message from Partial View - LoadUserDetail</h2> 
@ViewBag.CurrentDataTimeMessage<br>

View :

Here i am creating view with displaying current time and render LoadUserDetail partial view in it.

<h2>Index</h2>
<h2>Message from DonutCache -> Index </h2>
@ViewBag.CurrentDataTimeMessage

@Html.Action("LoadUserDetail", "DonutCache", new { name = "test" }, true)

OUTPUT :

While running the application, when we browse DonutCache controller then it will load the index view. If we refresh the page before 30 seconds, then index view will not refresh because it has been cached by the DonutCache (Time remain the same in the view, but time from the partial view had been updated for every refresh as shown below) . But LoadUserDetail has been refreshed every time because it hasn’t caught in cache as show below.

For more detail on caching and output caching.

Keep Happy Coding !!!

Enable Errors of Our ASP.NET MVC Views at Compile Time

In this post, we are going to discuss about how to capture “view” errors at compile time. By default, ASP.NET MVC projects won’t compile the views on the building process of our application. But don’t think Visual studio not handle this. As per below screen shot, it’s showing views error as warning in the Error List window, but we won’t consider the warning while running the application. 

All things are handling her. But many of us really won’t check this warning, as shown above. What we can do here is a fairly simple action to get this blow up on compile time. Let we discuss details about this.

STEP 1:

Right-click on your project’s  solution explorer and click Unload Project as shown in below image

STEP 2: After project unloaded,

After the project unloaded, right-click the project and choose Edit “Your project name” (. csproj) and MvcBuildViews node from false to true (for handlingthe error in compile time) and save the file.

STEP 3:

Reload the project and build the solution. Now we can see the “0 succeed , 1 failed” in the output window.

Handle multiple submit buttons on an ASP.NET MVC

In this post, we will discuss how to handle the multiple submit button event in ASP .NET MVC without using javascript. The form could contain more than one submit button issuing a form post to a different controller action. We can achieve this situation by using ActionNameSelectorAttribute.

Implementing View :

<div>
<form action="" method="post">
<input type="submit" value="Save" name="action:Save" />
<input type="submit" value="Edit" name="action:Edit" />
</form>
</div>

Implement ActionNameSelectorAttribute

Here i am creating a class that inherits from ActionMethodSelectorAttribute. The first parameter is ControllerContext, this parameter will contain the FormValueProvider object. This contains values posted in the form in a NameValueCollection object. Using this parameter we can identify which button clicked/submitted in the form.

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] public class HandleMultipleSubmitAttribute : ActionNameSelectorAttribute { public string FormKey { get; set; } public string FormName { get; set; } public override bool IsValidName(ControllerContext ctrContext, string actionName, MethodInfo methodInfo) { var isValidEvent = false; var keyValue = string.Format("{0}:{1}", FormKey, FormName); var value = ctrContext.Controller.ValueProvider.GetValue(keyValue); if (value != null) { ctrContext.Controller.ControllerContext.RouteData.Values[FormKey] = FormName; isValidEvent = true; } return isValidEvent; } }

Action Method

The next step is to create two action methods, which containing the Save and Edit functionality. To ensure that either of these actions will be invoked, I’m going to decorate them with the HandleMultipleSubmit attribute class.

public class MultipleSubmitController : Controller
{

[HttpPost]
[HandleMultipleSubmit(FormKey = "action", FormName = "Save")]
public ActionResult Save() 
{
return null;
}

[HttpPost]
[HandleMultipleSubmit(FormKey = "action", FormName = "Edit")]
public ActionResult Edit( )
{ return null; }
}

Execution :

  • After Save/Edit button is clicked, the input named Save will be injected into the form and that will be sent in the forms collection. Before executing the action method, attribute will be executed and it will check the values in the FormValueProvider and find the match value specified on the attribute.
  • If posted form contains a value that matches the value in HandleMultipleSubmit then IsValidForRequest method will returns true, so then it will start executing the proper action.

 

Keep Cool Coding…

 

Output Caching Attribute in ASP.NET MVC

The main goal of this post is to explain how we can improve the performance of an ASP.NET MVC web application by using the advantage of the output cache. The output cache enables us to cache the information which is returned by an action. So it will not need to re-generated the action content every when the same action method is invoked. Caching play the main part of the web application, as it improves the performance and load on the server. ASP.NET MVC make is, very simply by adding the OutputCache attribute on the action method to our application.

Why Caching is needed ?

Lest we think of this, if we need to display a record from the database in a view. So if a user tries to view the same page repeatedly, then each and every time that a user invokes the controller action so it hit the database to fetch the record and returns to the user.

By using output cache, we can avoid executing a database every time when user request the same controller action. At that time, it did retrieve the content from the cache instead of fetch them from the controller action. So the main advantage has enabled us to avoid server overload that is performing redundant work on the server.

Required Namespace :

For configuring the cache location, we need to include the below namespace in our controller.
namespace : System.Web.UI

Set Cache Location

We can control the caching location by using the location parameter like following values Any, Client, Downstream, None, Server, or ServerAndClient. By default, the parameter will have the Any parameter for caching the content.

OutputCache parameters

Enabling Output Caching

We can enable output caching by adding an OutputCache attribute to either an action or an entire controller class.

Controller Level Caching

Here in controller level caching, it’s cached all the action content under the control.

[OutputCache(Duration = 10, VaryByParam = “none” , Location = OutputCacheLocation.Client )] public class OutputCacheController : Controller { public ActionResult Index() { return View(); } }

 Action Level Caching

In action level caching, the content has cached alone for that particular action method.

[OutputCache(Duration = 10, VaryByParam = “none” , Location = OutputCacheLocation.Client )] public ActionResult Index() { ViewBag.CurrentDataTimeMessage = DateTime.Now.ToString(); return View(); }

Here I had specified the cache duration as 10 seconds, so the cache content will be maintained up to duration which we specified in the Duration parameter. When we run the application, the Date Time will not change/update up to 10 seconds because it’s already cached from the action and maintain up to 10 seconds. So it won’t hit the action method.

 

Keep Cool Coding…

 

ASP.Net MVC Request Life Cycle / MVC Application Execution Process

Introduction

In this post, we are going to discuss about the each step in the life of an ASP.NET MVC from request to response. Here we will walk through the steps involved in a life of ASP.NET MVC request.There are mainly five main steps that happen when you make a request from an ASP.NET MVC website.

Flow Of MVC Request :

Step 1 – Request

Receive first request for the application. In the Global.asax file, route objects are added to the Route table object. 

  protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);

            RouteConfig.RegisterRoutes(RouteTable.Routes);

            BundleConfig.RegisterBundles(BundleTable.Bundles);    
        }

Step 2 – The Route 

The entry point for every MVC Application begins with Routing. After the application receives the request from the user, it uses URL Routing Module to handle the request. The RouteTable maps URLs to handlers.  Basically routing is a pattern matching system that matches the request’s URL against the URL patterns which is present in the Route Table. The Routing engine redirect the request to the corresponding IRouteHandler when the match found in the pattern. If corresponding requested URL not found in route table then it will return a 404 HTTP status code.

Step 3 – The MvcHandler Executes

It is the responsibility of the RouteHandler to determine the HTTP handler that will serve the request, by looking at the received RequestContext. The RouteHandler object creates an instance of the MvcHandler class and passes the RequestContext instance to the handler.

RequestContext instance is used to identify the IControllerFactory object to create the controller instance.
The MvcHandler method calls the controller’s Execute method.

Step 4 – The Controller Executes

The controller determines which action method to execute. MvcHandler uses IControllerFactory instance and to get IController object. Mvc controllers implement IController interface to execute the method which actually execute your action method.

Step 5 – Action Invoked

After controller gets instantiated ActionInvoker will determines which Action method need to execute. ActionNameSelectorAttribute and ActionMethodSelectorAttribute methods used to select action method. The action method receives user input then executes the result and returning a result type to view. 

The result type can be ViewResult, RedirectToRouteResult, RedirectResult, ContentResult, JsonResult, FileResult, and EmptyResult. At last the view has been render to the browser as response.

Keep Cool Coding…