Sunday 30 November 2014

Object Oriented Programming

What is Class ?
A class is a template which contains a property  and method. It is a blueprint of an object. It  is a central point of OOP which describes a set of objects with common behavior.

What is an object ?
Objects is an instance of a class which can access the method or properties of the class from which the object is created.

What is encapsulation ?
Encapsulatin can be define as follows :
1. The process of binding a data and method into a single unit are known as encapsulation.
2. It is a process of hiding all the internal details of an object from the outside world.
3. Encapsulation is the ability to hide the data and method from outside the world and only expose data and method that are required.
4. Encapsulation is a protective barrier that prevents the code and data being randomly accessed by the other code or by outside the class.
5. It gives us maintainability, flexibility and extensibility to our code.
6. Encapsualtion makes implementation inaccessible to other parts of the program and protect from whatever action might be taken outside the function or class.
Ex :     
Public class Test
{
string   Name;
int   Age;
int  Total;
  Public string GetName()
{ {
name =”Bhimsen”;
}

Public  int Age()
{
age = 25
}

Public int getTotal(int a, int b, int c)
{
total = add(a,b,c);
}
private add(int x, int y, int z)
{
return  a+b+c;
}
}
Explanation : In the above example Test  class binds the Data and Method into a single unit (Class). GetName,GetAge and GetTotal is a public function which can be exposed by an object. But GetTotal Method using  Add() method which is private which only can use by getTotal not outside the world. So Encapsulation is the ability to hide the data and method from outside the world and only expose data and method that are required.

What is Abstraction ?
Abstraction is a process of hiding the implementation details and displaying the essential features. It is used to hide certain details and only show the essential features of the object. In other words, it deals with the outside view of an object (interface). 
Example : A Laptop consists of many things such as processor, motherboard, RAM, keyboard, LCD screen, wireless antenna, web camera, usb ports, battery, speakers etc. To use it, you don't need to know how internally LCD screens, keyboard, web camera, battery, wireless antenna, speaker’s works.  You just need to know how to operate the laptop by switching it on. Think about if you would have to call to the engineer who knows all internal details of the laptop before operating it. This would have highly expensive as well as not easy to use everywhere by everyone.
Note : Abstraction is a concept of hiding the internal details of the object. And encapsulation is an implementation of the abstraction.

What is Constructor ?
A constructor can define as follows:
1. A constructor is a mechanism which initialize the data and object  of its class.
2. It  is special method because its name is same as the class name.
3. They do not have return type not even void.
4. It cannot be inherited.
5. Constructor can be invoked whenever an object of its associated class is created.
Note :  Every class always contains atleast one constructor. If there are no constructor in class, C# automatically provide one for you, this is called default constructor.

What is Polymorphism ?
As the name suggested Polymorphism, It is made by Two words “Poly” and “Morph”. Poly means “Many” and morph means “Forms”. Hence polymorphism is a technique in which a single identifiers (Data, Method or object etc.) have a different forms. It has an ability to process object differently on their data types. It also has the ability to redefine the method for derived class.
There are two types of polymorphism. They are :
1. Compile Time Polymorphism ( Early Binding)  - Function Overloading  and Operator Overloading.
2. Runtime Polymorphism (Late Binding)   -  Method overriding and Virtual Function.

What is Function Overloading ? When and why we use it?
Function overloading is a mechanism in which a class contains two or more than two method with the same name but with different argument. It comes under the compile time polymorphism.
EX :        
class bits
{
void speak()
Console.WriteLine(“Hello”); 
}
void peak(string s)
{
Console.WriteLine(“Hello {0}”,s); }
}

Explanation : In the above example There are two “Speak” method and both has a different argument(0,1).

When and why to use method overloading
Use method overloading in situation where you want a class to be able to do something, but there is more than one possibility for what information is supplied to the method that carries out the task.

What is Function Overriding ?
Overriding is a mechanism in which a More the one method having the same argument but different class(Base, Derive).It is use to enhance or customize the functionality of the Function. Means changing the functionality of a method without changing the signature. We can override a function in base class by creating a similar function in derived class. This is done by using virtual/override keywords.Base class method has to be marked with virtual keyword and we can override it in derived class using override keyword.Derived class method will completely overrides base class method i.e. when we refer base class object created by casting derived class object a method in derived class will be called.

Example: 
// Base class
public class BaseClass
{
public virtual void Test1()
{
Console.Write("Base Class Method");
}
}
// Derived class
public class DerivedClass : BaseClass
{
public override void Test1()
{
Console.Write("Derived Class Method");
}
}
// Using base and derived class
public class Sample
{
public void TestMethod()
{
// calling the overriden method
DerivedClass objDC = new DerivedClass(); 
objDC.Test1();
 // calling the baesd class method
BaseClass objBC = (BaseClass)objDC; 
objDC.test1();
}
}

Output :
Derived Class Method
Derived Class Method

What is Inheritance ?
Inheritance is a mechanism in which one class inherits the data or method into the another class.The class whose data or method inherited are known as Base Class,Parent class or Super class. and the another class who inherits the data or method are know as Derive class, child class or subclass class.
Public class BaseClass
{
    Public BaseClass ()
    {
        Console.WriteLine ("Base Class Constructor executed");
    }
                                 
    Public void Write ()
    {
        Console.WriteLine ("Write method in Base Class executed");
    }
}
                                 
Public class ChildClass: BaseClass
{
                                 
    Public ChildClass ()
    {
        Console.WriteLine("Child Class Constructor executed");
    }
   
    Public static void Main ()
    {
        ChildClass CC = new ChildClass ();
        CC.Write ();
    }
}


In the Main () method in ChildClass we create an instance of childclass. Then we call the write () method. If you observe the ChildClass does not have a write() method in it. This write () method has been inherited from the parent BaseClass.

How method overriding is different from overloading?
When overriding, you change the method behavior for a derived class. Overloading simply involves having a method with the same name within the class.

What is Inheritance ?
Inheritance is a mechanism in which one class inherits the data or method into the another class.The class whose data or method inherited are known as Base Class,Parent class or Super class. and the another class who inherits the data or method are know as Derive class, child class or subclass class.
Public class BaseClass
{
    Public BaseClass ()
    {
        Console.WriteLine ("Base Class Constructor executed");
    }
                               
    Public void Write ()
    {
        Console.WriteLine ("Write method in Base Class executed");
    }
}
                               
Public class ChildClass: BaseClass
{
                               
    Public ChildClass ()
    {
        Console.WriteLine("Child Class Constructor executed");
    }
 
    Public static void Main ()
    {
        ChildClass CC = new ChildClass ();
        CC.Write ();
    }
}


In the Main () method in ChildClass we create an instance of childclass. Then we call the write () method. If you observe the ChildClass does not have a write() method in it. This write () method has been inherited from the parent BaseClass.

Or

Inheritance can be also define as follows :
1. Inheritance enables you to create new classes that reuse, extend, and modify the behavior that is defined in other classes.
2. The Class whose methods and variables are defined is called super class or base class.
3. The Class that inherits methods and variables are defined is called sub class or derived class.
4. Sometimes base class known as generalized class and derived class known as specialized class
Keyword to declare inheritance is “:” (colon) in visual c#


Benefits of using Inheritance
Once a behavior (method) or property is defined in a super class(base class),that behavior or property is automatically inherited by all subclasses (derived class).
Code reusability increased through inheritance
Inheritance provide a clear model structure which is easy to understand without much complexity
Using inheritance, classes become grouped together in a hierarchical tree structure
Code are easy to manage and divided into parent and child classes


What is an Interface ? When and why we use it ?
1. An Interface is a group of constants and method declaration.
2. C# supports multiple inheritance through Interface.
3. Interface states “what” to do, rather than “how” to do.
4. An interface defines only the members that will be made available by an implementing object. The definition of the interface states nothing about the implementation of the members, only the parameters they take and the types of values they will return. Implementation of an interface is left entirely to the implementing class. It is possible, therefore, for different objects to provide dramatically different implementations of the same members.

When to Use an interface

if we want to Implement same signature in different class then we can use it.
consider a company where there are staffs and supporting staffs. All will be given salary but staff salary calculation is different from supporting staff salary calculation. here is how it is implemented

public interface ISalary
    {
        decimal CalculateSalary();
    }
public class Staff : ISalary
    {
       public  decimal CalculateSalary()
        {
            //Staff salary calcuation logic        
        }
    }
    public class SupportingStaffs :ISalary
    {
      public  decimal CalculateSalary()
        {
            //Supporting Staff salary calcuation logic
     
        }
    }

What is an abstract class ?

An abstract class can de define as follows :-
1. An abstract class is a class that cannot be instantiated. This implies that you cannot create an object of the abstract class.
2. It exists extensively for inheritance and it must be inherited.
3. An abstract class may contain abstract as well as non abstract member.
4. The abstract method in abstract class may contain definition and declaration.
5. A class with abstract member must be abstract.
6. You must declare at least on abstract method in the abstract class.
7. Abstract class is declared using the abstract keyword.
8. An abstract class is always public.

When do you absolutely have to declare a class as abstract?

1. When the class itself is inherited from an abstract class, but not all base abstract methods have been overridden.
2.  When at least one of the methods in the class is abstract.

Difference between Abstract class and interface.

1. In an interface class, all methods are abstract - there is no implementation.  In an abstract class some methods can be concrete.
2. In an interface class, no accessibility modifiers are allowed.  An abstract class may have accessibility modifiers.
3. A class can extends only one abstract class where as a class can implement several interface.
4. Abstract class should have subclass. An interface must have implementation by classes.
5. There  can be a constructor for an abstract class. But interface doesnot have constructor.

Or

Abstract Class: 
1. A class can extend only one abstract class
2. The members of abstract class can be private as well as protected.
3. Abstract classes should have subclasses
4. Any class can extend an abstract class.
5. Methods in abstract class can be abstract as well as concrete.
6. There can be a constructor for abstract class.
7. The class extending the abstract class may or may not implement any of its method.
8. An abstract class can implement methods.

Interface 
1. A class can implement several interfaces
2. An interface can only have public members.
3. Interfaces must have implementations by classes
4. Only an interface can extend another interface.
5. All methods in an interface should be abstract
6. Interface does not have constructor.
7. All methods of interface need to be implemented by a class implementing that interface.
8. Interfaces cannot contain body of any of its method.

What is difference between structure and class?
1    1.  Structure is a value type and class is a reference type.
2    2. Structure allocates memory on stack where as class allocates memory in heap.
3    3. Structure does not support inheritance where as class supports inheritance.
4    4. Variable of structure can not be null but the variable of class can be assign null.
5    5. Structure does not requires constructor where as class must have at least one constructor.
6    6. We cannot put sealed/abstract modifier before the structure. But class can do it.
7. What is pure virtual function?
8. It  is a function that must be overridden in derived class and need not be defined. A virtual function is declare to be “pure” using the  “=0”.

Some OOP’s Terms with explanation.

Static Method :  Static method is a class level method that does not require an object to access the method.

Static Field : This field indicates that, the field should store only once. No matter how many instance of the class we created.

Virtual keyword : A virtual keyword indicates that, a member can be overwritten in the child class. It can be applied to method , properties, index and events.

New  Modifier : The new modifier hides the member of base class.

Sealed modifier :
   1.  Sealed type cannot be inherited.
   2.  Sealed modifier can be applied to instance method, properties , indexes and events.
   3.  It cannot be applied to static member.

    *    Static , value type & interface does not support abstract modifier.
    *    Static member cannot be abstract.

What is the relationship between a class and an object?

A class acts as a blue-print that defines the properties, states, and behaviors that are common to a number of objects. An object is an instance of the cass. For example, you have a class called Vehicle and Car is the object of that class. You can create any number of objects for the class named Vehicle, such as Van, Truck, and Auto. The new operator is used to create an object of a class. When an object of a class is instantiated, the system allocates memory for every data member that is present in the class.

What is the difference between procedural and object-oriented programming?
Procedural programming is based upon the modular approach in which the larger programs are broken into procedures. Each procedure is a set of instructions that are executed one after another. On the other hand, OOP is based upon objects. An object consists of various elements, such as methods and variables. Access modifiers are not used in procedural programming, which implies that the entire data can be accessed freely anywhere in the program. In OOP, you can specify the scope of a particular data by using access modifiers - public, private, internal, protected, and protected internal.

What is a static constructor?
Static constructors are introduced with C# to initialize the static data of a class. CLR calls the static constructor before the first instance is created. The static constructor has the following features:
No access specifier is required to define it.
You cannot pass parameters in static constructor.
A class can have only one static constructor.
It can access only static members of the class.
It is invoked only once, when the program execution begins.

Difference between new and override keyword

Let me explain this through code. 

namespace BaseDerive
{
    public partial class Form1 : Form
    {
        public Form1()
      {
            InitializeComponent();
        }
   private void Form1_Load(object sender, EventArgs e)
   {
            BaseClass b = new BaseClass();
            b.func1();
            DeriveClass d = new DeriveClass();
            d.func1();
            //Calls Base class function 1 as new keyword is used.
            BaseClass bd = new DeriveClass();
            bd.func1();
            //Calls Derived class function 2 as override keyword is used.
            BaseClass bd2 = new DeriveClass();
            bd2.func2();
        }
    }
    public class BaseClass
    {
        public virtual void func1()
        {
            MessageBox.Show("Base Class function 1.");
      }
        public virtual void func2()
        {
            MessageBox.Show("Base Class function 2.");
       }
  public void func3()
        {
            MessageBox.Show("Base Class function 3.");
        }
    }
    public class DeriveClass : BaseClass
    {
        public new void func1()
        {
            MessageBox.Show("Derieve Class fuction 1 used new keyword");
        }
        public override void func2()
        {
            MessageBox.Show("Derieve Class fuction 2 used override keyword");
        }
        public void func3()
        {
            MessageBox.Show("Derieve Class fuction 3 used override keyword");
        }
    }
}

This is a window application so all the code for calling the function through objects is written in Form_Load event.
 
As seen in above code, I have declared 2 classes. One works as a Base class and second is a derieve class derived from base class.
 

Now the difference is
 

new: hides the base class function. 
Override: overrides the base class function. 

BaseClass objB = new DeriveClass();

If we create object like above notation and make a call to any function which exists in base class and derive class both, then it will always make a call to function of base class. If we have overidden the method in derive class then it will call the derive class function.
 


For example… 
objB.func1(); //Calls the base class function. (In case of new keyword)

objB.func2(); //Calls the derive class function. (Override)

objB.func3(); //Calls the base class function.(Same prototype in both the class.)

Note: 
// This will throw a compile time error. (Casting is required.) 

DeriveClass objB = new BaseClass(); 


//This will throw run time error. (Unable to cast) 


DeriveClass objB = (DeriveClass) new BaseClass(); 

What are queues and stacks?

 Stacks refer to a list in which all items are accessed and processed on the Last-In-First-Out (LIFO) basis. In a stack, elements are inserted (push operation) and deleted (pop operation) from the same end called top. Queues refer to a list in which insertion and deletion of an item is done on the First-In-First-Out (FIFO) basis. The items in a queue are inserted from the one end, called the rear end, and are deleted from the other end, called the front end of the queue.



Saturday 29 November 2014

Dataview VS Datatable

1. DataView can be used to select the data.Datatable can be used to edit or select or delete or insert a data.Means that Dataview is read only where as Datatable is read/Write.
2. Dataview is a reference to an existing DataTable.It must be instantiated with a reference to an existing DataTable.it Cannot be populated from scratch. where as Can be created empty and then populated
3. Since Dataview is a reference of datatable so it does not consume space. where as datatable's data takes storage space.
4. Dataview Can sort or filter rows without modifying the underlying data.where as datatable can add/edit/delete rows, columns, and data, and all changes are persistent.
5. Dataview supports calculated columns, which are columns with a value calculated on the fly by combining or manipulating other columns. Does not support calculated columns.

DataSet Vs DataReader


1. DataReader is used to retrieve read-only (cannot update/manipulate data back to datasource) and forward-only (cannot read backward/random) data from a database. It provides the ability to expose the data from database while DataSet is a collection of in-memory tables.

2. DataReader fetches the records from database and stores in the network buffer and gives whenever requests. It releases the records as query executes and do not
      wait for the entire query to execute. Hence very fast as compare to the DataSet which releases the data after loading all the data in memory.

3. DataReader is like a forward only recordset. It fetches one row at a time so very less network cost compare to DataSet which fetches all the rows at a time i.e. it fetches all data from the datasource at a time to its memory area.

4. As one row at a time is stored in memory in DataReader it increases application performance and reduces system overheads while there is more system overheads in DataSet as it fetches all the data from the datasource at a time in memory.

5. As DataReader is forward only, we can’t fetch random records as we can’t move back and forth .While in DataSet we can move back and forth and fetch records randomly as per requirement.

6. DataReader fetches data from a single table while DataSet can fetch data from multiple tables.

7. As DataReader can have data from a single table so no relationship can be maintained while relationship between multiple tables can be maintained in DataSet.

8. DataReader is read only so no transaction like insert, update and delete is possible while these transactions are possible in DataSet.

9. DataSet is a bulky object that requires lot of memory space as compared to DataReader .

10.DataReader is a connected architecture: The data is available as long as the connection with database exists while DataSet is a disconnected architecture that automatically opens the connection, fetches the data into memory and closes the connection when done.
11.DataReader requires connection to be open and close manually in code while DataSet automatically handles it.

12. DataSet can be serialized and represented in XML so easily passed around to other tiers but DataReader can't be serialized.

13. DataReader will be the best choice where we need to show the data to the user which requires no manipulation while DataSet is best suited where there is possibility of manipulation on the data.

14. Since DataSet can be serialized it, can be used in wcf services  and web service that will return retrieved data. But DataReader can’t be serialized so can’t be used in wcf services and web services.

15. When you need to navigate through the data multiple times then DataSet is better choice e.g.  we can fill data in multiple controls But DataReader can only be read once so it can be bound to a single control and requires data to be retrieved for each control.

Thursday 27 November 2014

MVC Interview Question

What is MVC ?
MVC stands for Model View Controller, It is a framework pattern or software design which splits the application into three component. They are :
  1.    Model  (Data Access Layer)
  2.       View  ( Presentation Layer)
  3.       Controller (Business Logic )
Model :  Model is a business  entity on which overall  application operates. It represents a set of class which describes the business logic .It also define a business rule, means that how our data can be retrieve, change or manipulate.
View : View represents a User Interface(UI). It is responsible for displaying the data that comes from the controller as a result. We can also say that, It is a user interface that render the model into form. Its basic components are Html, Css, Jquery etc.
Controller: The Controller is responsible to process the data that comes from the user via view. It process the user data with the help of model and passes the result back to the view. Typically, it acts as a co-ordinator between view and Model.


What is the page Lifecycle of the MVC?

MVC page lifecycle can be define as follows :-
 i) App Initialisation 
 In this stage, the aplication starts up by running Global.asax’s Application_Start() method.
 
 In this method, you can add Route objects to the static RouteTable.Routes collection.
 
 If you’re implementing a custom IControllerFactory, you can set this as the active controller  factory by assigning it to the System.Web.Mvc.ControllerFactory.Instance property.
 

 ii) Routing
 
 Routing is a stand-alone component that matches incoming requests to IHttpHandlers by URL  pattern.
 
 MvcHandler is, itself, an IHttpHandler, which acts as a kind of proxy to other IHttpHandlers  configured in the Routes table.
 

 iii) Instantiate and Execute Controller
 
 At this stage, the active IControllerFactory supplies an IController instance.
 

 iv) Locate and invoke controller action
 
 At this stage, the controller invokes its relevant action method, which after further processing,  calls RenderView().
 

 v) Instantiate and render view
 
 At this stage, the IViewFactory supplies an IView, which pushes response data to the  IHttpResponse object.

     What is MVC Architecture.

  MVC Architecture can be easily understand by the following figure and the explanation.



 1.   Browser sends the request to the IIS.
 2.   ISS searches route defined in MVC and passes to controller as per route.
 3.  Controller communicate the model and passes populated model to view.
 4. View are populated with model property via controller.
 5.  Controller passes the response to browser  through IIS.

What is the advantage of an MVC?
Following are an advantage of MVC :-
 1.   MVC provides a clean separation of application concern among  Model(Data Access Layer) View(Presentation Layer)  and Controller(Business Logic ).
2.  It is easy for unit Testing.
3.  It provides improved reusability of View and improved structuring of code.
4.  It gives us the full control over the behavior of application as it does not use Viewstate or server based form.
5.   It provides better support to Test Driven Development.


What is the new features in MVC3 and MVC4 ?
New features of MVC3 :
1.       Razor View Engine.
2.       Support form .Net 4 Data Annotation.
3.       Improved model validation.
4.       Better javascript support,Jquery validation and JSON Binding.

New Features in MVC4 :
1.   Web API
2.   Enhancement to default project template.
3.   Mobile project template using jquery mobile displaying model.
4.  Task support for Asynchronous controller.

What is Razor view Engine?
1.       Razor view is the first major update to render HTML in MVC3, It is the part of new rendering framework.
2.       It is lighter then the Asp.Net render engine. Becouse Asp.Net rendering engine user opening and closing bracket.  Whereas razor view allows clean syntax.
3.       It is easier to type, read and learn.
4.       Razor does not have XML like heavy syntax for web form.  

What is ViewData and ViewBag? Also describe its similarity and Difference.
View Data : In Viewdata objects are accessible using  string key. When we go to use an object on the view then we have to cast it, Because the viewdata  stores everything as object. In otherway, It is a dictionary of object which derives from the viewdatadictionary class and accessible using string as key.
ViewBag :  It is a dynamic properties that takes advantage of new features in c# 4.0. It allows the object to dynamically have the properties add to it.There are no need to cast the object when using data in view. This is because the dynamic we uses let us know the type.

Similarity between ViewData and viewBag.

1. Both maintain the data when moving from controller to view.
2. Both passes data from controller to respective view.
3. The value becomes null when any redirection occers.

Difference between Viewdata and viewbag.

1. ViewData is a dictionary of object that derives from the viewdatadictionary class. And its objects accessible using string as key. Where as viewbag is a dynamic property that takes advantage of new features in C# 4.0.It allows the object to dynamically property added to it.
2. It requires typecasting for complex data type and checks for null value to avoid error. While a viewbag does not requires typecasting for complex datatype.

What is Tempdata in MVC ?
1. Tempdata is a dictionary of object which derived  from the tempdatadictionary class.
2. It help us to maintain the data when we move from one controller to another and one action
        to another action.
3. It keeps the information for the time httprequest only.Means, only from one page to another.
4. When we redirect,  tempdata  helps to maintain data between those redirect.It internally uses
        session veriable.
5. It is a string key and object value.
6. It  requires typecasting for complex data type and checks null value to avoid error.
7. Generally, It is used to store only one time message like error message, validation message etc.

What is Repository pattern in MVC? what are the benefits of it?
Repository pattern basically works as a mediator between our  Business Logic Layer and and Data Access Layer. Sometimes it would be troublesome to expose the data access mechanism to directly to Business Logic Layer, It may result in redundant code for accessing data for similar entity or it may be result in code that is hard to test and understand. To overcome this kind of issue and write interface driven and test driven code to access data we uses repository pattern.
Benefits of repository pattern:
1. It centralize the data logic or the service access logic.
2. It provides substitution point for unit test.
3. It provides a flexible architecture that can be adopted as overall design.

What is Routing in MVC ?
A route is a stand alone component or url pattern that Is mapped to a handler (IHTPPheldler).Handler can be any physical file such as .aspx page or other web form. It is responsible for mapping incoming browser request to MVC controller action.
1. Router matches incoming request from browser to controller action ( IHTPPhandler by using URL pattern).

2. It also construct outgoing URL that correspond to acton.

Segment of default route in MVC
There are three segment of default route. Thery are :
1. Controller name
2. Action Name
3. Parameter                            

  Ex :  http://bccenter.com/Photogalary/GetImage/22
Controller Name = Photogalary
Action Method Name = GetImage
Parameter Id = 22

How route table created in MVC ?
When an MVC application starts, It calls the Application_Start() method from the global.ascs page. This method calls the Registerroute() method which creates a route table.

What is layout in MVC Razor?
When the application requires maintaining a consistent look and feel across multiple view then we uses layout. It is just like a master page of the web application,  But it provides a greater flexibility and has a simple syntax as compared to asp.net web application. It is generally use to define a common template for our application.

What is ViewStart in MVC? Or What does _ViewStart.cshtml file in MVC?
In MVC, When  multiple or group of view uses the same layout it may get some redundant code which is harder to maintain. So, To remove this redundancy we uses _viewstart.cshtml page. because this file executed before the any view page in directory. And a view can override the layout property and choose another property.  If a set of views shares common settings, the _ViewStart.cshtml file is a useful place to consolidate these common view settings. If any view needs to override any of the common settings, the view can set those values to another value.

What is NonActionAttribute in MVC?
It is already known that all the public method of a controller treated as action method. So, if you don’t want this default behavior then you can change public method with NonActionAttribute.

What is difference between Asp.net MVC and web form?
There are many difference of MVC and Web Form which are as follows :-
1. Web form follows an event driven development where as MVC follows Model View Controller.
2. Web page has server control wher as mvc has html helper.
3. Web form has state management technique where as mvc has not.
4. Web form has file based url where as mvc has route based url.
5. Web form uses masterpage for look and feel but MVC uses layout.
6. For reuseablity web form has a user control but MVC has partial View.

What is partial view in Asp.Net Mvc?
A partial view is just like as user control in Asp.Net web form. It is generally uses for the purpose of reusability.  Partial views are reusable views like as Header and Footer. It has .csHtml extension.
Partial and RenderPartial Html method renders partial view in MVC.s

<div>@Html.Partial("_Comments")</div>
<div>@ { Html.RenderPartial("_Comments") } </div>


What is the name of assembly where MVC framework defined?
System.Web.Mvc

Is it possible to combine ASP.NET webforms and ASP.MVC and develop a single web application?
Yes,

Is it possible to unit test an MVC application without running the controllers in an ASP.NET process?
Yes, all the features in an asp.net MVC application are interface based and hence mocking is much easier. So, we don't have to run the controllers in an ASP.NET process for unit testing.

Is it possible to share a view across multiple controllers?
Yes, put the view into the shared folder. This will automatically make the view available across multiple controllers.

Name the Some of the Return type of a controller Action .
1. ViewResult
2. PartialView Result
3. JavaScript Result
4. Json Result
5. Content Result
6. Redirect Result
7. File Result
8. Empty Result

Explain the advantages of using routing in ASP.NET MVC ?
Without using Routing in an ASP.NET MVC application, the incoming browser request should be mapped to a physical file.The thing is that if the file is not there, then you will get a page not found error.
By using Routing, it will make use of URLs where there is no need of mapping to specific files in a web site.
This is because, for the URL, there is no need to map to a file, you can use URLs that are descriptive of the user's action and therefore are more easily understood by users.

Explain with examples for scenarios when routing is not applied ?
Below are the 2 scenarios where routing is not applied.
i) A Physical File is Found that Matches the URL Pattern - This default behaviour can be overriden by setting the RouteExistingFiles property of the RouteCollection object to true.
ii) Routing Is Explicitly Disabled for a URL Pattern - By using the RouteCollection.Ignore() method, you can prevent routing from handling certain requests.

What are the 3 things that are needed to specify a route?
1. URL Pattern - You can include placeholders in a URL pattern so that variable data can be passed to the request handler without requiring a query string.
2. Handler - The handler can be a physical file such as an .aspx file or a controller class.
3. Name for the Route - Name is optional.

What is the difference between adding routes, to a webforms application and to an mvc application?
To add routes to a webforms application, we use MapPageRoute() method of the RouteCollection class, where as to add routes to an MVC application we use MapRoute() method.

Explain the usage of action filters in an MVC application ?
Action filter in an mvc application is used to perform some additional processing, such as providing extra data to the action method, inspecting the return value, or canceling execution of the action method.
Action filter is an attribute that implements the abstract FilterAttribute class. Or we also can say that, Action Filters allow us to add pre-action and post-action behavior to controller action methods.

If I have multiple filters impleted, what is the order in which these filters get executed?
1. Authorization filters
2. Action filters
3. Response filters
4. Exception filters

What are sections?
Layout pages, can define sections, which can then be overriden by specific views making use of the layout. Defining and overriding sections is optional.

LINQ

What is LINQ ?

1. LINQ stands for Language of Integrated Query.It is a new technology developed by Microsoft.
2. Its primary function is to add native data query capability to .net using similar syntax like SQL.
3. It is a simple query operator which allow Traversing, Filtering and projection operation in .net based programming language.
4. It Simplifies the situation by consistent syntax for working data across the different datasourse and there formats.
5. It allows the query expression to benefit from rich metadata, Compile Time error checking and intelligence that previously available only to the imperative code.

Why LINQ is beneficial than Store Procedure?

1. Debugging : Since LINQ is part .Net, so we can use the debugger of visual Studio t debug the query.But to debug the stored procedure is very hard.
2. Development : Deployment becomes easy with LinQ, because its(LINQ) is a .Net component,so its compiles everything into a single DLL File.
3. Type Safety : Since, In LINQ query errors are type checked at compile time.It is really good to encounter an error when compiling rather than run time exception.

Difference between FirstOrDefault and single or default

If your result set returns 0 records:

SingleOrDefault returns the default value for the type (e.g. default for int is 0)
FirstOrDefault returns the default value for the type

If you result set returns 1 record:

SingleOrDefault returns that record
FirstOrDefault returns that record

If your result set returns many records:

SingleOrDefault throws an exception
FirstOrDefault returns the first record
Conclusion:

If you want an exception to be thrown if the result set contains many records, use SingleOrDefault.

If you always want 1 record no matter what the result set contains, use FirstOrDefault.


LINQ Single vs SingleOrDefault vs First vs FirstOrDefault

Single()SingleOrDefault()First()FirstOrDefault()
DescriptionReturns a single, specific element of a sequenceReturns a single, specific element of a sequence, or a default value if that element is not foundReturns the first element of a sequenceReturns the first element of a sequence, or a default value if no element is found
Exception thrown whenThere are 0 or more than 1 elements in the resultThere is more than one element in the resultThere are no elements in the resultOnly if the source is null (they all do this)
When to useIf exactly 1 element is expected; not 0 or more than 1When 0 or 1 elements are expectedWhen more than 1 element is expected and you want only the firstWhen more than 1 element is expected and you want only the first. Also it is ok for the result to be empty
What is a query expression in LINQ? 
A LINQ query, also known as a query expression, it consists of a combination of query clauses that identify the data sources for the query. It includes instructions for sorting, filtering, grouping, or joining to apply to the source data. The LINQ query expressions syntax is similar to the SQL syntax. It specifies what information should be retrieved from the data source.

Example of Searching in Collections:

The Old Way
Find the names of all customers from New Delhi.
List<string> LstDelhi = new List<string>();
foreach (Customer c in customers) {
if (c.City == “New Delhi”) {
LstDelhi.add(c.Name);
}
}

The LINQ Way
string[] LstDelhi =from c  in customers
   where c.City == “New Delhi”
   select c.Name;

How LINQ query executes? Or What are the basic steps to execute LINQ query?
The following are the three basic steps to execute a LINQ query:
1. Obtain the data source (Data source can be either an SQL database or an XML file).
2. Create a query .
3. Execute the query

What is the DataContext class and how is it related to LINQ?
After you add a LINQ to SQL Classes item to a project and open the O/R Designer, the empty design surface represents an empty DataContext class ready to be configured. The DataContext class is a LINQ to SQL class that acts as a conduit between a SQL Server database and the LINQ to SQL entity classes mapped to that database. This class contains the connection string information and the methods for connecting to a database and manipulating the data in the database. It is configured with connection information provided by the first item that is dragged onto the design surface.

What does DISTINCT clause in a LINQ query? Also write a simple query.
The DISTINCT clause returns the result set without the duplicate values.

 var query_distinct = (from c in svcContext.ContactSet
                       select c.LastName).Distinct();
 foreach (var c in query_distinct)
 {
  System.Console.WriteLine(c);
 }


What are lambda expressions in LINQ? 
A lambda expression is a function without a name that calculates and returns a single value. All lambda expressions use the lambda operator =>, which read as goes to. The left side of the lambda operator specifies the input parameters and the right side holds the expression or statement block.

What are the different implementations of LINQ? 
The different implementations of LINQ are:
LINQ to SQL - Refers to a component of.NET Framework version 3.5 that provides a run-time infrastructure to manage relational data as objects.
LINQ to DataSet - Refers to a component that makes it easier and faster to query over data cached in a DataSet object.
LINQ to XML - Provides an in-memory XML programming interface.
LINQ to Objects - Refers to the use of LINQ queries with any IEnumerable or IEnumerable(T) collection directly, without the use of an intermediate LINQ provider or API, such as LINQ to SQL or LINQ to XML.

What is the difference between the Select clause and SelectMany() method in LINQ? 
Both the Select clause and SelectMany() method are used to produce a result value from a source of values. The difference lies in the result set. The Select clause is used to produce one result value for every source value. The result value is a collection that has the same number of elements from the query. In contrast, the SelectMany() method produces a single result that contains a concatenated collection from the query.



Entity Framework Interview Question

What is Entity Framework?

1. Entity Framework is an ORM(Object Relational Mapping) framework.Its a new technology of .net developed by Microsoft.
2. It is an enhancement of ADO.Net which allows the developer to connect to Database with Data Model Object instead of old data connection.
3. It allow us to create an entity calss which represents the table in database, and using that class developer can do all the work to the backend.
4. Sincel the class represents the table in the databse,due to which we can easily understand the table's data and there relationship among the table.
5. It supports the LINQ qery to retriving and manipulating the data into the datasource.
6. Entity Framework makes us free from the Old compnents of the ADO.Net componets such as DAtaTable, DataSet, Connection etc.


What is ORM (Object Relational Mapping)?

1. ORM is a tool for storing data from domain objects to relational database like MS SQL Server, in an automated way, without much programming.
2. O/RM includes three main parts: Domain class objects, Relational database objects and Mapping information on how domain objects map to relational database objects (tables, views & stored procedures).

OR

Object-relational mapping (ORM) is a mechanism that makes it possible to access and manipulate objects without having to consider how those objects relate to their data sources.

Or , simply you can say,

A simple answer is that you wrap your tables or stored procedures in classes in your programming language, so that instead of writing SQL statements to interact with your database, you use methods and properties of objects.
In other words, instead of something like this:

String sql = "SELECT ... FROM persons WHERE id = 10"
DbCommand cmd = new DbCommand(connection, sql);
Result res = cmd.Execute();
String name = res[0]["FIRST_NAME"];


you do something like this:

Person p = repository.GetPerson(10);
String name = p.FirstName;

or similar code (lots of variations here.) Some frameworks also put a lot of the code in as static methods on the classes themselves, which means you could do something like this instead:

Person p = Person.Get(10);

Some also implement complex query systems, so you could do this:

Person p = Person.Get(Person.Properties.Id == 10);

The framework is what makes this code possible.

Now, benefits. First of all, you hide the SQL away from your logic code. This has the benefit of allowing you to more easily support more database engines. For instance, MS SQL Server and Oracle has different names on typical functions, and different ways to do calculations with dates, so a query to "get me all persons edited the last 24 hours" might entail different SQL syntax just for those two database engines. This difference can be put away from your logic code.
Additionally, you can focus on writing the logic, instead of getting all the SQL right. The code will typically be more readable as well, since it doesn't contain all the "plumbing" necessary to talk to the database.


Or, Finally...

Object-relational mapping products integrate object programming language capabilities with relational databases managed by Oracle, DB2, Sybase, and other relational database managers. Object-relational mapping products are designed to work well with object programming languages such as C#, C++, and Java.

History of ADO.NET Entity Framework
1. The first version of Entity Framework released on 11 August, 2008 with .NET Framework 3.5 Service Pack 1 and Visual Studio 2008 Service Pack 1.
2. The second version of Entity Framework was released on 12 April 2010 with .NET Framework 4.0
3. A third version of Entity Framework was released on April 12, 2011. Its name was Entity Framework 4.1.
4. A refresh of version of Entity Framework 4.1 was released on July 25, 2011.
5. The version Entity Framework 4.3.1 was released on February 29, 2012.
6. The latest version is 5.0.0 and is targeted at .NET framework 4.5. But it is also available for .Net framework 4.
7. The Entity Framework 6.0 is an open source project. Its source code is hosted at CodePlex using Git and licensed under Apache License v2. Like ASP.NET MVC Framework.

Advantage/Benefit of Entity Framework
The main and only benefit of Entity Framework is its auto generated code for model, Data access layer and mapping code. This reduces the lot of development time.


Difference between IEnumeable and IQueryable.

1.  if you are working with only in-memory data collection (List, Array etc.) “IEnumerable” is a good choice but if you want to query data collection which is connected with database (LinQ, EntityFramework), “IQueryable” is a better choice as it reduces network traffic and uses the power of SQL language.
2.  IEnumerable exists in System.Collections Namespace. Where as IQueryable exists in System.Linq Namespace.
3.  While query data from database, IEnumerable execute select query on server side, load data in-memory on client side and then filter data.


While query data from database, IQueryable execute select query on server side with all filters.

4. IEnumerable doesn’t supports custom query. Where as IQueryable supports custom query using CreateQuery and Execute methods.

5. IQueryable support lazy loading. Hence it is suitable for paging like scenarios. While IEnumerable doesn’t support lazy loading. Hence not suitable for paging like scenarios.

What is .edmx file in Entity Framework?
EDMX stands for Entity Data Model XML. It is an XML file which contains all the mapping detail of how your object map with SQL table. It also define the conceptual model, Storage model and mapping between these model. An .edmx file can be divided into three section. They are :
1. CSDL  : Conceptual Schema Definition language is the conceptual abstraction which is exposed to application.
2. SSDL  : Storage Schema Definition Language defines the mapping with our RDBMS structure.
3. MSL   : Mapping Schema Language is use to connect the CSDL and SSDL.

What is code first approach in Entity Framework?
In code first approach we avoid working with visual designer of Entity Framework. Means that, .edmx file is excluded from the solution. So you have complete control over the context class and entity class. Because you are going to manually create the class.

What is T4 template? Describe its importance.
T4 means Text Template Transformation Toolkit. It is a technical based code generation engine. In T4 template file we can write the c# code and execute it to generate file  as per written in c# logic. Its extension is .tt.
Importance of T4 template:
T4 file is the heart of the Entity Framework. It reads the .edmx XML file and generate C# code behind. And code behind is nothing but your entity and context class.

What is lazy loading in entity framework?
Lazy loading is a concept where we load objects  on demand rather than everything in one go. It is the default behavior of entity framework. It returns only the object that are used. When you query the database model, lazy loading only returns the immediate table needed by user. So it makes your program faster using limited memory.

What is drawback of Entity Framework?
The main drawback of entity framework is lazy loading. It is the default setting of EF. Due to this behavior , if we loads large number of record than it may take long time.

What is POCO class in Entity Framework?
POCO means Plane Old C# Object. When we create .edmx class. They are mix-up with a lot of entity tag. POCO is a semi-automatic  so you have full control on entity class. But context class are still generated by .edmx file.

In POCO classes do we need EDMX files?
Yes, you will still need EDMX files because the context object reads the EDMX files to do the mapping.

How to Read, Add, Update and Delete record using EF?
For performing the CURD operation in EF. We have to use an object of context class.
Example:
To Read data record :
CustomerContext obj = new CustomerContext();
Foreach(Customer cust in obj.customer)
{
// Do your work here.
}
To add data record: we use AddObject method and savechange method to add record.
CustomerContext   obj   =   new  CustomerContext();
Customer  custObj= new Customer();
custObj.Name=”Bhimsen”;
custObj.Email=”bhimsen6@gmail.com”;
custObj.Mobile=8010326915;
custObj.Address=”New Delhi”;
obj.customer.addobject(custObj);
obj.savechanges();
To Update Record :
CustomerContext   obj   =   new  CustomerContext();
Customer  custObj= (Customer) obj.Customer.firstOrDefault();
custObj.Name=”Bhimsen”;
obj.AcceptAllChanges();
To Delete Record:
CustomerContext   obj   =   new  CustomerContext();
Customer  custObj= (Customer) obj.Customer.FirstOrDefault();
Obj.DeleteObject(CustObj);

What the difference is between POCO, Code First, and simple EF approach?
All these three approaches define how much control you want on your Entity Framework code. Entity Framework is an OR mapper, it generates a lot of code, it creates your middle tier (Entity), and Data Access layer (Context).
But a lot of times you want to enjoy the benefits of both worlds, you want the auto-generation part to minimize your development time and you want control on the code so that you can maintain code quality.
Below is the difference table which defines each of the approaches. In simple Entity Framework, everything is auto generated and so you need the EDMX XML file as well. POCO is semi-automatic so you have full control on the entity classes but then the context classes are still generated by the EDMX file.
In Code First, you have complete control on how you can create the entity and context classes. Because you are going to manually create these classes, you do not have dependency on the EDMX XML file. Below is a simple table which shows the cross comparison.

                                       EDMX         Entity         Context
Simple entity framework    Needed          Auto           Auto
POCO approach                Needed          Manual           Auto
Code First                        Not Needed Manual           Manual

What’s the difference between LINQ to SQL and Entity Framework?
1. LINQ to SQL is good for rapid development with SQL Server. EF is for enterprise scenarios and works with SQL Server as well as other databases.
2. LINQ maps directly to tables. One LINQ entity class maps to one table. EF has a conceptual model and that conceptual model maps to the storage model via mappings. So one EF class can map to multiple tables, or one table can map to multiple classes.
3. LINQ is more targeted towards rapid development while EF is for enterprise level where the need is to develop a loosely coupled framework.

What is the difference between DbContext and ObjectContext?
DbContext is a wrapper around ObjectContext, it’s a simplified version of ObjectContext.
As a developer you can start with DbContext as it’s simple to use. When you feel that some of the operations cannot be achieved by DbContext, you can then access ObjectContext from DbContext, as shown in the below code:
 ((IObjectContextAdapter)dbContext).ObjectContext

What is the difference between old ADO .NET and Entity framework coding techniques?
When you used ADO, you connected to the database and had to define a stored procedure or query to retrieve data. With Entity framework, you don’t have to be “blind” when it comes to your tables. ADO did not allow you to get the table structure. With code first, you already have the table structure and Entity framework connects to the database and hides any connection processes. With Entity framework, you’re more aware of the database structure, which helps you avoid any coding mistakes. In addition, if the table structures change, Entity framework updates the data models for you during a refresh.