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.

Tuesday, December 31, 2013

What is IOC and Dependency injection and how do they differ from each other?(Design pattern interview questions with answers)

When we talk about software programs they have LOGIC’s and LOGIC’s have FLOW. Take the below simple code. We have a “Customer” class which is instantiated from a console application.

class Customer
    {
        private SQLServer Dal = new SQLServer();
        public bool validate()
        {
            return true;
        }
        public void Add()
        {
            if (validate())
            {
                Dal.Add();
            }
        }
    }
    class SQLServer
    {
        public void Add()
        {
        }
    }

Customer obj = new Customer();
obj.Add();

If you watch the program flow of the customer object it is as follows:-
  • Client creates object of the customer class.
  • Customer class creates the object of SQL Server data access layer.
  • Customer object then invokes “Validate” method.
  • Once the “Validate” method is successful then it invokes the “Add” method.


In other words the “Customer” class is in control of his FLOW. Now let us complicate the situation.  Let’s say we have different flavors of data access layer.  So let’s say we have “SqlServer” and “Oracle” as shown below.

So the best way to implement the same is my creating a generic interface “Dal” and pointing that generic interface to “SQLServer” or “Oracle” object depending on situations. So if you see the flow now:-
  • Client creates object of the customer class.
  • Customer class depending on configuration decided to create SQL Server object or Oracle object.
  • Customer object then invokes “Validate” method.
  • Once the “Validate” method is successful then it invokes the “Add” method.


A good code is that code which takes care of his own logic rather than overloading with logic which he is not concerned with. For instance in this case the customer class is now taking care of logics like deciding which data access layer objects to be created.

class Customer
    {
        private Dal dal;
        public Customer(int DalType)
        {
            if (DalType == 1)
            {
                dal = new SQLServer();
            }
            else
            {
                dal = new Oracle();
            }
        }
        public bool validate()
        {
            return true;
        }
        public void Add()
        {
            if (validate())
            {
                dal.Add();
            }
        }
    }

interface Dal
    {
        void Add();
    }
    class SQLServer : Dal
    {
        public void Add()
        {
        }
    }
    class Oracle : Dal
    {
        public void Add()
        {
            throw new NotImplementedException();
        }
    }

This makes the customer class tightly coupled to the data access layer changes and second in long run this code becomes difficult to maintain. So the solution here  is customer class should perform his own concerned logic like validating customer class , calling add method of data access layer. But deciding which data access layer to create is not his part.

So if this logic or this control is given to some other entity or can be INVERTED to some one else then the code would look much better.


So if we change the code to something as shown below. Where the customer class say’s hey  look I am not concerned its Oracle or SQL Server. Pass me the generic interface object from the constructor and relieve me from the decision making logic of Data access layer.

class Customer
 {
        private Dal dal;
        public Customer(Dal obj)
        {
            dal = obj;
        }
      …
      …
}

So now it’s the work of client or the invoker to decide which data access layer object has to be passed.

If you visualize this scenario the flow of “Customer” class now takes care of his logic and the unconcerned logic is now passed to an external entity. This is termed as “Inversion of control”. The control or logic which is not part of that entity is taken care by someone else.

Also if you put in other terms the flow of “Customer” class is now affected by external entities depending on whether they inject “SqlServer” object or “Oracle” object.

A word of caution here, do not conclude that IOC can  only be implemented by exposing abstraction via constructor.  You can delegate the control flow by callback delegates, observer pattern, events, and lot of other ways.


The above way of sending abstraction from constructor is termed as “dependency” injection.IOC (Inversion of control) is a general parent term while DI (Dependency injection) is a subset of IOC.

DI provides objects that an object needs.  So rather than the dependencies construct themselves they are injected by some external means.  For instance let’s say we have the following below class “Customer” who uses a “Logger” class to log errors. So rather than creating the “Logger” from within the class, you can inject the same via a constructor as shown in the below code snippet.












The biggest benefit achieved by the above approach is “Decoupling”. You can now invoke the customer object and pass any kind of “Logger” object as shown in the below code.

Customer obj = new Customer(new EmailLogger());
Customer obj1 = new Customer(new EventViewerLogger());

Inversion of control
Dependency injection
It’s a generic term and implemented in several ways (events, delegates etc).
DI is a subtype of IOC and is implemented by constructor injection, setter injection or method injection.