Monday, May 25, 2015

What is CSRF attack and how can we prevent the same in MVC?

CSRF (Cross site request forgery) is a method of attacking a website where the attacker imitates a.k.a forges as a trusted source and sends data to the site. Genuine site processes the information innocently thinking that data is coming from a trusted source.

For example conside the below screen of a online bank. End user’s uses this screen to transfer money.

Below is a forged site created by an attacker which looks a game site from outside, but internally it hits the bank site for money transfer.

The internal HTML of the forged site has those hidden fields which have the account number and amount to do money transfer.

Now let’s say the user has logged in to the genuine bank site and the attacker sent this forged game link to his email. The end user thinking that it’s a game site clicks on the “Play the Ultimate Game” button and internally the malicious code does the money transfer process.

So a proper solution to this issue can be solved by using tokens: -

  • End user browses to the screen of the money transfer. Before the screen is served server injects a secret token inside the HTML screen in form a hidden field.
  • Now hence forth when the end user sends request back he has to always send the secret token. This token is validated on the server.

Implementing token is a two-step process in MVC: -

First apply “ValidateAntiForgeryToken” attribute on the action.

[ValidateAntiForgeryToken]
public ActionResult Transfer()
{
            // password sending logic will be here
            return Content(Request.Form["amount"] + 
                " has been transferred to account " 
                + Request.Form["account"]);
}

Second in the HTML UI screen call “@Html.AntiForgeryToken()” to generate the token.

So now henceforth when any untrusted source send a request to the server it would give the below forgery error.

If you do a view source of the HTML you would find the below verification token hidden field with the secret key.

Tuesday, May 19, 2015

How to handle multiple Submit button issues in ASP.NET MVC? (MVC Interview Questions)

How to handle multiple Submit button issues in ASP.NET MVC? (MVC Interview Questions)

Let us understand the above problem in more detail.

Take a scenario where you have a view with two submit buttons as shown in the below code.

In the above code when the end user clicks on any of the submit buttons it will make a HTTP POST to “Action1”.

The question from the interviewer is: -

“What if we have want that on “Submit1” button click it should invoke “Action1” and on the “Submit2” button click it should invoke “Action2”.”

There are three basic approaches to solve the above problem scenario.

HTML way: -

In the HTML way we need to create two forms and place the “Submit” button inside each of the forms. And every form’s action will point to different / respective actions. You can see the below code the first form is posting to “Action1” and the second form will post to “Action2” depending on which “Submit” button is clicked.

AJAX way: -

In case you are an AJAX lover this second option would excite you more. In the Ajax way we can create two different functions “Fun1” and “Fun1”, see the below code. These functions will make Ajax calls by using JQUERY or any other framework. Each of these functions is binded with the “Submit” button’s “OnClick” events. Each of these function make call to respective action names.

Using “ActionNameSelectorAttribute”: -

This is a great and a clean option. The “ActionNameSelectorAttribute” is a simple attribute class where we can write decision making logic which will decide which action can be executed.

So the first thing is in HTML we need to put proper name’s to the submit buttons for identifying them on the server.

You can see we have put “Save” and “Delete” to the button names. Also you can notice in the action we have just put controller name “Customer” and not a particular action name. We expect the action name will be decide by “ActionNameSelectorAttribute”.

So when the submit button is clicked, it first hits the “ActionNameSelector” attribute and then depending on which submit is fired it invokes the appropriate action.

So the first step is to create a class which inherits from “ActionNameSelectorAttribute” class. In this class we have created a simple property “Name”.

We also need to override the “IsValidName” function which returns true or flase. This function is where we write the logic whether an action has to be executed or not. So if this function returns true then the action is executed or else it is not.

public class SubmitButtonSelector : ActionNameSelectorAttribute
    {
        public string Name { get; set; }
        public override bool IsValidName(ControllerContext controllerContext, string actionName, System.Reflection.MethodInfo methodInfo)
        {
            // Try to find out if the name exists in the data sent from form
var value = controllerContext.Controller.ValueProvider.GetValue(Name);
            if (value != null)
            {
                return true;
            }
            return false;

        }
    }

The main heart of the above function is in the below code. The “ValueProvider” collection has all the data that has been posted from the form. So it first looks up the “Name” value and if its found in the HTTP request it returns true or else it returns false.

var value = controllerContext.Controller.ValueProvider.GetValue(Name);
if (value != null)
      {
 return true;
      }
      return false;

This attribute class can then decorated on the respective action and the respective “Name” value can be provided. So if the submit is hitting this action and if the name matches of the HTML submit button name it then executes the action further or else it does not.

public class CustomerController : Controller
{
        [SubmitButtonSelector(Name="Save")]
        public ActionResult Save()
        {
            return Content("Save Called");
        }
        [SubmitButtonSelector(Name = "Delete")]
        public ActionResult Delete()
        {
            return Content("Delete Called");
        }
}

Monday, May 11, 2015

Validation’s using C# “DataAnnotation”

Introduction
How to use “DataAnnotations” ?
Step 1:- Refer System.ComponentModel.DataAnnotations
Step 2:- Decorate the class with attributes
Step 3:- Call the “Validator” for validation.

Introduction

Validations are one of the most important aspects of any software application. Normally as a best practice we put these validation’s in the business class , model etc. So if you normally see the trend, developers end up writing these validations in the “set” method of the class property.

 
public class Customer
    {

        private string _CustomerName;
        public string CustomerName
        {
            get { return _CustomerName; }
            set 
            {
                if (value.Length == 0)
                {
                    throw new Exception("Customer Name is required");
                }
                _CustomerName = value; 
            }
        }    
    }

“DataAnnotation” gives you ready made attributes which you can decorate on the class properties and the validation will be applied accordingly.

[Required]
public string CustomerName
{
            get { return _CustomerName; }
            set {_CustomerName = value; }
}

How to use “DataAnnotations” ?


Step 1:- Refer System.ComponentModel.DataAnnotations

The first step is to add reference to “System.ComponentModel.DataAnnotations” assembly to your class library project.

Step 2:- Decorate the class with attributes

The next step is to decorate the class with validation attributes. For instance on the “CustomerName” property we have decorated the “Required” attribute.

public class Customer
{
        private string _CustomerName;

        [Required]
        public string CustomerName
        {
            get { return _CustomerName; }
            set {_CustomerName = value; }
        }
        
}

Step 3:- Call the “Validator” for validation.

Once the validation attributes are decorated we need to call the “Validator” class to do the validations. Create the customer object and set the “CustomerName” property to nothing , so validation errors fire up.

Customer obj = new Customer();
obj.CustomerName = "";

Use the above created object to create the “ValidationContext” object.

var context = new ValidationContext(obj,null,null);

Use “Validator” to call  “TryValidateObject” method to run the validations. The validation errors get collected in the “ValidationResult” collection.

var result = new List();
var isValid = Validator.TryValidateObject(obj, context, result,true);

If you wish to loop through the error results you can run a “foreach” on the “result” collection.

foreach (var str in result)
{
Console.WriteLine(str.ErrorMessage.ToString());
}

Below is a pictorial representation of the above code. In simple words the object to be validated is passed to the “validator” class with the context and the error results come out in “ValidationResult” collection.

FYI :- If you have multiple validation do not forget to make the last property true.

var isValid = Validator.TryValidateObject(obj, context, result,true);

Monday, April 27, 2015

What is Automapper?

Contents

What is Automapper ?

I have not specified mapping how does it work ?

How can we map different property names in Automapper ?

Can you give some real time scenarios of the use of Automapper ?

From where to get AutoMapper ?


What is Automapper ?


Automapper is a simple reusable component which helps you to copy data from object type to other. If you wish to get automapper read this.

For example below is a simple employee class loaded with some dummy data.
class Employee 
{
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public decimal Salary { get; set; }
}
// Loaded with some data
Employee emp = new Employee();
emp.FirstName = "Shiv";
emp.LastName = "Koirala";
emp.Salary = 100;
Now let’s say we want to load the above employee data in to a “Person” class object.
class Person
{
        public string FirstName { get; set; }
        public string LastName { get; set; }
}
So normally developers end up writing mapping code as shown in the below snippet.
Person per = new Person();
per.FirstName = emp.FirstName;
per.LastName = emp.LastName;

At the first glance this does not look much of a problem but wait…think, what if you want to use this mapping code again and again.

So as a best practice you would like to centralize this mapping code and reuse this mapping code again and again. This is where our super hero “AutoMapper” comes for rescue.“Automapper” sits in between both the objects like a bridge and maps the property data of both objects.


Using Automapper is a two-stepprocess:-
  • Create the Map.
  • Use the Map so that objects can communicate.
Mapper.CreateMap(); // Create Map
Person per =  Mapper.Map(emp); // Use the map

I have not specified mapping how does it work ?


In the above example property names of both classes are same so the mapping happens automatically.

How can we map different property names in Automapper ?


If the classes have different property names then we need to use “ForMember” function to specify the mapping.
Mapper.CreateMap()
.ForMember(dest => dest.FName , opt => opt.MapFrom(src => src.FirstName))
.ForMember(dest => dest.LName , opt => opt.MapFrom(src => src.LastName));

Can you give some real time scenarios of the use of Automapper ?

  • When you are moving data from ViewModel to Model in projects like MVC.
  • When you are moving data from DTO to Model or entity objects and vice versa.

From where to get AutoMapper ?


The easiest way is to use nugget. In case you are new to nuget see this YouTube video





Or you can download the component form their main site http://automapper.org/

Monday, November 24, 2014

Can we overload MVC controller action methods? (MVC Polymorphism)

This Saturday and Sunday when i was taking MVC class in Mumbai one of the participants asked this weird question, Can we overload MVC action methods?. This question was asked to him during a MVC interview recently.

For moment I wondered why interviewer such kind of questions which does not test anything about programmer's ability. But let's leave that argument from some other day and lets answer this question.

Well the answer is YES and NO depending on your expectation. Now before you turn me in to a politician who answers from both side's let me explain you why i have given such kind of a dubious answer.

Overloading or in other words polymorphism is a feature of object oriented programming. So if you have some kind of a below controller code which has methods overloaded with same name and different argument's it would compile very well.
public class CustomerController : Controller
    {
        //
        // GET: /Customer/

publicActionResultLoadCustomer()
        {
return Content("LoadCustomer");
        }
publicActionResultLoadCustomer(string str)
        {
return Content("LoadCustomer with a string");
        }
    }
But now if you are thinking that when you call "http://localhost:3450/Customer/LoadCustomer/" it should invoke "LoadCustomer" and when you call "http://localhost:3450/Customer/LoadCustomer/test" it should invoke "LoadCustomer(string str)" you are WRONG.

If you try to this you will end with a below error. Read the word "Ambiguous" in the error , does something click. Ok , let me explain in more detail what the below error means.










Polymorphism is a part of C# programming while HTTP is a protocol. HTTP does not understand polymorphism it works on the concept's or URL and URL can only have unique name's. So HTTP does not implement polymorphism.

And i know if you answer with the above argument MVC interviewer would still press that he wants to implement polymorphism , so how do we go about doing it.

If you wish to keep polymorphism and also want the HTTP request to work you can decorate one of the methods with "ActionName" as shown in the below code.
public class CustomerController : Controller
    {
        //
        // GET: /Customer/

publicActionResultLoadCustomer()
        {
return Content("LoadCustomer");
        }

        [ActionName("LoadCustomerbyName")]
publicActionResultLoadCustomer(string str)
        {
return Content("LoadCustomer with a string");
        }
    }
So now you can invoke with URL structure "Customer/LoadCustomer" the "LoadCustomer" action and with URL structure "Customer/LoadCustomerByName" the "LoadCustomer(string str)" will be invoked.























In case you want to start learning MVC , below is a nice MVC step by step video series which will help you to learn MVC in 16 hours i.e. 2 day's. Give a try.



Friday, October 31, 2014

Difference Between ViewResult() and ActionResult() in MVC ?

So you have hit this blog note because you are confused about the difference between “ViewResult” and “ActionResult” and I hope that your confusion ends here.

So without wasting time let’s get the difference in one sentence:-

“ActionResult is an abstract parent class from which ViewResult class has been derived”.


So when you see MVC controller and action codes as shownbelow :-
public ActionResult Index()
{
      return View(); // this is a view result class
}
The above code means that you are returning a “ViewResult” object and due to polymorphism this object is automatically type casted to the parent class type i.e “ActionResult”.

In case you are newbie to polymorphism , let’s do a quick revision. In polymorphism parent class object can point towards any one of its child class objects on runtime. For example in the below code snippet we have parent “Customer” class which is inherited by “GoldCustomer” and “SilverCustomer” class.

public class Customer
{}

public class GoldCustomer : Customer
{}

public class SilverCustomer : Customer
{}
So down the line later during runtime your parent “Customer” object can point to any one of the child object i.e “GoldCustomer” or “SilverCustomer”.
Customer obj = new Customer();
obj = new GoldCustomer();
obj = new SilverCustomer();
How does this polymorphism benefit for MVC results?

MVC applications are used to create web sites or web application. Web applications work in a request and response structure because they follow HTTP protocol.


So the end user using theUI sends a HTTP POST or a GET request and the web application depending on scenarios sends a response. Now the request is quiet standard but the response types differ due to different kind of devices.


For example if its a browser you expect HTMLresponse, if its jquery you expect JSON format or for some other client types you just want simple text contents and so on.

So what the MVC team did is they created a base general class called “ActionResult” which was further inherited to create different types of results.


So in the action result code you can pass some parameter from the UI and depending on this parameter you can send different response types. For instance in the below example we are passing a boolean flag whether it’s a HTML view or not and depending on the same we are streaming different views.
public ActionResult DynamicView(bool IsHtmlView)
{
   if (IsHtmlView)
     return View(); // returns simple ViewResult
   else
     return Json(); // returns JsonResult view
}
Cool isn’t it rather than writing different methods for each response you just have one method with dynamic polymorphic response.

There are 11 different response types which can be sent to the end user :-
  1. ViewResult - Renders a specified view to the response stream
  2. PartialViewResult - Renders a specified partial view to the response stream
  3. EmptyResult - An empty response is returned
  4. RedirectResult - Performs an HTTP redirection to a specified URL
  5. RedirectToRouteResult - Performs an HTTP redirection to a URL that is determined by the routing engine, based on given route data
  6. JsonResult - Serializes a given object to JSON format
  7. JavaScriptResult - Returns a piece of JavaScript code that can be executed on the client
  8. ContentResult - Writes content to the response stream without requiring a view
  9. FileContentResult - Returns a file to the client
  10. FileStreamResult - Returns a file to the client, which is provided by a Stream
  11. FilePathResult - Returns a file to the client
Are you struggling to learn ASP.NET MVC start with the below video




Sunday, September 14, 2014

MVC Tempdata , Peek and Keep confusion

This blog assumes you have idea on MVC in case not I would suggest starting from thisyoutube video Learn MVC.

Recently I was taking MVC class in Mumbai and I saw there was lot of confusion among participantson how MVC tempdata , Peek and Keep works. I think the confusion stems because most of the MVC developers know only thehalf truth.

So the half thing which most of MVC developer know is:-

“Tempdata helps to preserve values for a single request”.

The other half-truth which developers do not know is or I will say which confuses developer is:-

“TempData CAN ALSO preserve values for the next request depending on 4 conditions”.

So let us try to understand the above two statements. When an end user send’s a request to a MVC application “TempData” is maintained throughout the complete request. This request can traverse through multiple actions or controllers until it displays the view on the browser.


Now in the same session (without closing the browser) if a new / second request is initiated then “TempData” will be persisted depending on 4 CONDITIONS:-

  • Not Read.
  • Normal Read.
  • Read and Keep.
  • Peek and Read.


So let’s discuss these four conditions in more detail ( Do see the below diagram for better understanding ):-

Condition 1 (Not read):- If you set a “TempData” inside your action and if you do not read it in your view then “TempData” will be persisted for the next request.

Condition 2  ( Normal Read) :- If you read the “TempData” normally like the below code it will not persist for the next request.

stringstr = TempData[“MyData”];

Even if you are displaying it’s a normal read like the code below.

@TempData[“MyData”];

Condition 3 (Read and Keep) :- If you read the “TempData” and call the “Keep” method it will be persisted.

@TempData[“MyData”];
TempData.Keep(“MyData”);

Condition 4 ( Peek and Read) :- If you read “TempData” by using the “Peek” method it will persist for the next request.

stringstr = TempData.Peek("Td").ToString();


So if you register these four condition’s in your mind you should not have any confusion’s around TempData:) .