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:) .

Saturday, August 16, 2014

Things you will miss in ASP.NET MVC as an ASP.NET Webform developer

Introduction

No CodeBehind

No Server controls

No Page life cycle

No ViewState


Introduction


I have been a great fan of ASP.NET Webform development but for past 2 years ASP.NET MVC is the talk of the town. If you are new to MVC start here and if you want to learn MVC super-fast start here.

Note: - If ASP.NET MVC and ASP.NET WebForm vocabulary is confusing please read this before moving ahead :-http://computerauthor.blogspot.in/2014/08/aspnet-vs-mvc-vocabulary-confusion_15.html.

When I started ASP.NET MVC development it took lot of time as an ASP.NET webform developer to get adjusted and acquainted with ASP.NET MVC development thought. This article walks you through some important mind set changes you need to make when working with ASP.NET MVC.

 

No CodeBehind


The whole thought of MVC is to get rid of behind code. Because behind code is not reusable , not testable .So when you add a view / UI in MVC is you will be find no behind code. You will find “.ASPX” but there is no “ASPX.CS”. You will find CSHTML but there is no CSHTML.CS.


Now the time we say “No Behind code” this has a cascading effect. The remaining points are the after effect of “No code behind” concept.

No Server controls


ASP.NET webform Server controls was always a life savior. It was like a magic where you drag and drop and you are done.Now because we do not have any behind code server controls will not be seen in your tool box. You have to use HTML to create your MVC UI. The maximum support officially you have currently is HTML Helper classes , you can read about it from here.


You can use server controls on an ASPX view but it’s not advisable as it will generate inline code behind again defeating the purpose of MVC.

No Page life cycle


Because we do not have behind code there is no such thing as page life cycle in ASP.NETMVC.In ASP.NET Webform the first hit comes to the Page and then rest of the things happen. ASP.NET Webform is UI first approach while MVC is class first approach.

In MVC the first hit comes to the controller class and then to the UI. So all the logic of page life cycle goes in the controller.So no more discussion on page life cycle and which event what code needs to be written.

No ViewState


There are no automated generated hidden fields like viewstate. We have more robust and fine tuned way of session management viewdata , tempdata ,viewbag and session variables. You can read more about them from clicking here.

Want to Learn MVC in 2 days start from this video






Friday, August 15, 2014

ASP.NET VS MVC – Vocabulary confusion

If you have clicked on this article thinking that ASP.NET is the old thing and MVC is the new thing then you need to seriously read this article.


Recently I was taking Learn MVC in 2 days in Andheri Mumbai and I saw lot of participants thinking ASP.NET is different and MVC is different. During the MVC training many were referring ASP.NET as the old thing and MVC as the new thing. But actually they are one and the same thing.

ASP.NET is a web framework of Microsoft and MVC is a visual studio code template to  write code using MVC architecture style. The proper name of OLD ASP.NET is “ASP.NET webforms”. So ASP.NET webform is the old ASP.NET with behind code and MVC is the new thing.


This is also very much evident when you create an ASP.NET Web project using visual studio. In visual studio you will see two different templates one with the name “ASP.NET Webform” and the other with “ASP.NET MVC”.


Note :- Web and Webform are one and the same thing.

If you want to learn MVC step by step start from the below link

http://www.codeproject.com/Articles/207797/Learn-MVC-Model-View-Controller-step-by-step-in

Tuesday, July 8, 2014

What is CodeLens?

Code lens is a new feature in visual studio 2013 which helps us to understand three important things about our code while we are coding inside visual studio.

All these three things(Impact, test and latest) are seen right above your class / method when you code in visual studio as shown in the below figure.


Impact: - First thing code lens shows is when we change the code what isthe impact of those changes. For instancein the above figure you can see it stating that if you make any changes to the log method it will be impact 1 reference.

If you click on references further it will also show which the classes it’s referencing. With this we come to know the level of impact this change will have further.

In the below screen it’s stating that “ConsoleApplication2” and “UnitTest1.cs” are the classes which.


If you further click on “Show on Code Map” menu you should see a graphical representation of dependencies.


Test :- Second important thing code lens tells is whether this method was unit tested or not.  For instance you can see it say’s 1 passing means this method was unit tested.


Latest: -Third thing it tells where this is a latest code or not. You can see the last menu which states this is not a latest code and you need to do a get latest from the server.

But now for the bad news nothing is free, code lens is currently available only in ultimate edition. Wish it was free as air….. ;-)


Below is a nice and short video of codelens created by www.questpond.com team.



Thursday, June 12, 2014

Explain MVC model binders ? ( ASP.NET MVC interview questions)

Model binder maps HTML form elements to the model. It acts like a bridge between HTML UI and MVC model.



Take the below simple HTML form example :-








Now this form needs to fill the below “Customer” class model. If you see the HTML control name they are different from the class property name. For example HTML textbox control name is “CCode” and the class property name is “CustomerCode”.  This mapping code is written in HTML binder classes.

publicclassCustomer
{
publicstring CustomerCode { get; set; }
publicstring CustomerName { get; set; }
}

To create a model binder we need to implement “IModelBinder” interface and mapping code needs to be written in the “BindModel” method as shown in the below code.

publicclassCustomerBinder : IModelBinder
{

publicobject BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
HttpRequestBase request = controllerContext.HttpContext.Request;

string strCustomerCode = request.Form.Get("CCode");
string strCustomerName = request.Form.Get("CName");

returnnewCustomer
            {
                CustomerCode = strCustomerCode,
                CustomerName = strCustomerName
            };
}
}

Now in the action result method we need to use the “ModelBinder” attribute which will attach the binder with the class model.

publicActionResult SubmitCustomer([ModelBinder(typeof(CustomerBinder))]Customer obj)        
{

return View(“DisplayCustomer”);
}

This MVC interview question was provided by questpond which conducts ASP.NET MVC training . In case you are new to MVC you can start from questpond video which is shown below.

Monday, May 19, 2014

Server.Transfer” VS “Response.Redirect” – Simplified

Introduction

“Server.Transfer”vs “response.Redirect”

So when to use “Server.Transfer” and when to use “Response.Redirect” ?

What is importance of “preserveForm” flag in “Server.Transfer”?

Response.Redirect(URL,true) vsResponse.Redirect(URL,false) ?

Introduction


In ASP.NET some of the concepts do the same task but are meant to be used in different scenarios. One such concept which is confusing and most discussed among developers is the difference between “Server.Transfer” and “Response.Redirect”.



“response.redirect” and “server.transfer” helps to transfer user from one page to other page while the page is executing. But the way they do this transfer / redirect is very different.

In this short blog we will discuss about how they differ and in which scenarios we should use them.

In case you are visual guy and would like see demonstration rather than theory I would suggest to see the below facebook video which explains the difference in a more demonstrative way.



“Server.Transfer”vs “response.Redirect”


The main difference between them is who does the transfer. In “response.redirect” the transfer is done by the browser while in “server.transfer” it’s done by the server. Let us try to understand this statement in a more detail manner.

In “Server.Transfer” following is the sequence of how transfer happens:-
  1. User sends a request to an ASP.NET page. In the below figure the request is sent to “WebForm1” and we would like to navigate to “Webform2”.
  2. Server starts executing “Webform1” and the life cycle of the page starts. But before the complete life cycle of the page is completed “Server.transfer” happens to “WebForm2”.
  3. “Webform2” page object is created, full page life cycle is executed and output HTML response is then sent to the browser.



One important point to note here is the URL is not changed to the target page. If you have sent request from “Webform1.aspx” to redirect to “WebForm2.aspx” on the browser URL you will still see “WebForm1.aspx”.

While in “Response.Redirect” following is the sequence of events for navigation:-
  1. Client (browser) sends a request to a page. In the below figure the request is sent to “WebForm1” and we would like to navigate to “Webform2”.
  2. Life cycle of “Webform1” starts executing. But in between of the life cycle “Response.Redirect” happens.
  3. Now rather than server doing a redirect , he sends a HTTP 302 command to the browser. This command tells the browser that he has to initiate a GET request to “Webform2.aspx” page.
  4. Browser interprets the 302 command and sends a GET request for “Webform2.aspx”.

In this case you will the URL’s are changed as per redirection. So if you have redirected to “Webform2.aspx” then on the browser URL you should see “WebForm2.aspx”.

In other words “Server.Transfer” is executed by the server while “Response.Redirect” is executed by thr browser. “Response.Redirect” needs to two requests to do a redirect of the page.

So when to use “Server.Transfer” and when to use “Response.Redirect” ?


Use “Server.Transfer” when you want to navigate pages which reside on the same server, use “Response.Redirect” when you want to navigate between pages which resides on different server and domain.



Below goes the consolidated table with all the differences as discussed at the top.

Server.TransferResponse.Redirect
RedirectionRedirection is done by the server.Redirection is done by the browser client.
Browser URLDoes not change.Changes to the redirected target page.
When to useRedirect between pages of the same server.Redirect between pages on different server and domain.


What is importance of “preserveForm” flag in “Server.Transfer”?


“Server.Transfer” helps to redirect from one page to other page. If you wish to pass query string and form data of the first page to the target page during this redirection you need to set “preserveForm” to “true” as shown in the below code.

Server.Transfer("Webform2.aspx",true);

By default the value of “preserveForm” is “true”.

Response.Redirect(URL,true) vsResponse.Redirect(URL,false) ?


Response.Redirect(URL,false) :- Client is redirected to a new page and the current page on the server will keep processing ahead.

Response.Redirect(URL,true) :- Client is redirected to a new page but the processing of the current page is aborted.


Below is a facebook video whichdemonstrates practically the difference between server.transfervsresponse.redirect .A big thanks to www.questpond.com to allow me to publish this videos for free on facebook.



Sunday, April 27, 2014

IEnumerable vs IQueryable ? ( .NET Interview question)

Both these interfaces are for .NET collection’s so if you are new to .NET collection please first see this video https://www.youtube.com/watch?v=hDykzD-3z8k  before moving ahead with the article.

The first important point to remember is “IQueryable” interface inherits from “IEnumerable”, so whatever “IEnumerable” can do, “IQueryable” can also do.


There are many differences but let us discuss about the one big difference which makes  the biggest difference. “IQueryable” interface is useful when your collection is loaded using LINQ or Entity framework and you want to apply filter on the collection.

Consider the below simple code which uses “IEnumerable” with entity framework. It’s using a “where” filter to get records whose “EmpId” is “2”.



This where filter is executed on the client side where the “IEnumerable” code is. In other words all the data is fetched from the database and then at the client its scans and gets the record with “EmpId” is “2”.


But now see the below code we have changed “IEnumerable” to “IQueryable”.







In this case the filter is applied on the database using the “SQL” query.  So the client sends a request and on the server side a select query is fired on the database and only necessary data is returned.


So the difference between “IQueryable” and “IEnumerable” is about where the filter logic is executed. One executes on the client side and the other executes on the database.

So if you working with only in-memory data collection “IEnumerable” is a good choice but if you want to query data collection which is connected with database “IQueryable” is a better choice as it reduces network traffic and uses the power of SQL language.

Below is a nice FB video which demonstrates this blog in a more visual and practical manner.












Saturday, March 22, 2014

Temp variablesVS Temp tables(SQL Server interview questions)



Temp tables
Temp variables
Big difference
Temp tables are real temporary SQL Server tables , you can create indexes , they can participate in transactions , it will use SQL Server optimization techniques etc.
So if you are operating on large number of records use Temp tables.
As the name says these are variables. So they do not participate in transactions, you can not create indexes directly, they do not use SQL server optimization techniques etc.


Good for small number of records.
Should be used when?
Large number of records.
Less than 100 records.
Scope
Outside procedure
Only Inside the procedure.
Transaction
Yes
No
Indexes
Yes
No (Note: - Indexes get indirectly created if you great a unique primary key.)
Truncate
Yes
No
Alter Table
Yes
No it’s just variable.
Affected by SQL Server optimization
Yes
No
Parallelism
Yes
No.
 
Recently one of our friends was asked this tricky SQL Server interview question: - Can SQL Server views be updated ?. Below is a great video by www.questpond.com which discusses this question in detail.