Thursday, 12 July 2012

All Basic C#.Net questions

1) Describe the difference between a Thread and a Process?

Thread is minimum unit for processor to execute. Collections of threads make process. By dividing process into threads, processor achieves multi tasking (by running threads concurrently not parallel). Threads can share memory but processes can’t share memory. Threads can communicate with each other of same process without any middle layer but process can’t they required inter process communication kind of thingy. 



1.Threads(Light weight Processes) share the address space of the process that created it; processes have their own address.
2.Threads have direct access to the data segment of its process; processes have their own copy of the data segment of the parent process.
3.Threads can directly communicate with other threads of its process; processes must use interprocess communication to communicate with sibling processes.
4.Threads have almost no overhead; processes have considerable overhead.
5.New threads are easily created; new processes require duplication of the parent process.
6.Threads can exercise considerable control over threads of the same process; processes can only exercise control over child processes.
7.Changes to the main thread (cancellation, priority change, etc.) may affect the behavior of the other threads of the process; changes to the parent process does not affect child processes.If we consider running a word processing program to be a process, then the auto-save and spell check features that occur in the background are different threads of that process which are all operating on the same data set (your document).


 2) What is a Windows Service and how does its lifecycle differ from a "standard" EXE?

 Windows service is windows based background process which has no user interface like any other service (aka daemon in UNIX based environment). Windows service needs to be installed before executing unlike EXE. Windows service used to perform such tasks which doesn’t required user interaction but system status based events like performing tasks at specific intervals or at different state of system like alarm user when disk is about to get full to clean up. Windows service is controlled by Service control manager (SCM) and it started automatically even user didn’t login to his/her windows account (as SCM already has account credentials so SCM knows if system start which service needs to start and by which account), where as EXE is controlled by OS and runs only when user get login using windows account. 

 3) What is the maximum amount of memory any single process on Windows can address? Is this different than the maximum virtual memory for the system? How would this affect a system design?

Single process on windows can address different amount of memory as it depends upon systems (32bit/64bit processor) and OS as well. Yes, process memory consumption size can be different from maximum virtual memory size. If software/process code is written by keeping 64 bit processor (as 64 bit processor support more than double memory) then it won’t be able to run that process on 32 bit system.
Windows processes are allowed 4GB of virtual address space, regardless of the actual amount of memory on the machine. Windows x64 allows 16TB of address space. 

 4) What is the difference between an EXE and a DLL?

Exe is executable and independent program/process to run which has its own reserved memory space whereas DLL (Dynamic Link Library) is neither executable and not even independent, it used by other DLL/program.

 5) What is strong-typing versus weak-typing? Which is preferred? Why?

Strong typing means when code compiles, type rules enforced strictly according to their data assigned to them. whereas weak typing is quite opposite of this definition. JavaScript/C/C++ is weak typing. but .net based languages are strongly typed. Strong typing is preferred by means of less run time errors risk and efficient during execution of program but not during compile time.
Strong-typing refers to defining the specific type of a reference at compile time rather than at run time. This results in more efficient execution and memory optimizations at compile time, as well as reduces the chance of a programmer accidentally providing a value of a type another component wasn't expecting.

 6) Corillian's product is a "Component Container." Name at least 3 component containers that ship now with the Windows Server Family.

Component containers implement the IContainer interface to wrap components, providing a meta-architecture for organizing, interacting and communicating with the components.

 7) What is a PID? How is it useful when troubleshooting a system?

(Ambiguous) This could refer to either a Microsoft Product ID -- the unique key that brands each activatable component installed on a system -- or to a Process ID, which is a means of referring to a specific process in calls to the Windows API.

 8) How many processes can listen on a single TCP/IP port?

I think single process can only hold handler of any port at a time means can listen on single port. Once I got error when I ran my web application as another application (skype) was using that port. It make sense as well, ports are like doors if two people talk on specific door and third one comes up then no privacy :-D (divorce ratio would be dramatically raised)

 9) What is the GAC? What problem does it solve?

GAC stands for Global Access Cache where shareable/public assemblies (DLL) stored to be used by multiple programs. It gives a shared platform for programs to use single assembly and can store same assembly (of same name) with different versions and can help to solve DLL HELL.

 10) Describe the difference between Interface-oriented, Object-oriented and Aspect-oriented programming.

Object-oriented programming consists of defining programming structures around logical units of data and the functionality required to operate on them. Interface-oriented programming extends upon the concept by mandating that cross-dependencies between objects be expressed in the form of abstracted, defined guidelines (without specific implementation) so that objects have set expectations for touchpoints. Aspect-oriented programming proceeds one step further, defining certain "first tier" processes which apply to almost all objects (such as logging), and providing high level means of attaching functionality to a wide swath of objects without specific implementation required in each one.

 11) Does C# support multiple inheritance?


 12) What’s the implicit name of the parameter that gets passed into the class’ set method?

 13) What’s the top .NET class that everything is derived from?

 14) How’s method overriding different from overloading?

 15) What is CLR?

 16) What is CTS?

 17) What is CLS?

 18) What is strong name?

 19) What is Application Domain?

 20) Describe the difference between Interface-oriented, Object-oriented and Aspect-oriented programming.

Object-oriented programming consists of defining programming structures around logical units of data and the functionality required to operate on them. Interface-oriented programming extends upon the concept by mandating that cross-dependencies between objects be expressed in the form of abstracted, defined guidelines (without specific implementation) so that objects have set expectations for touchpoints. Aspect-oriented programming proceeds one step further, defining certain "first tier" processes which apply to almost all objects (such as logging), and providing high level means of attaching functionality to a wide swath of objects without specific implementation required in each one

 21) Describe what an Interface is and how it’s different from a Class.

Interfaces are "guidelines without implementation" for functionality in an object. They define methods and properties which must be exposed, but leave it to the individual object to determine implementation.
An interface is strictly a Contract without implementation means interface can only declare properties or methods. Class can have implementation of its methods, can have different level of access identifiers whereas interface’s properties or methods can have only public access identifier and can implement class and multiple interfaces.

 22) What is Reflection?

Reflection is the ability to dynamically execute code without pre-linking at compile time. This may take the form of dynamic module loading and late binding, or it may take the form of real-time code construction and compilation.
Reflection is mechanism to load dynamically assembly at runtime and using assembly Meta data can access its namespace, class and their properties, methods and even events.

 23) What is the difference between XML Web Services using ASMX and .NET Remoting using SOAP?

Web services are generally stateless, using a standard HTTP interface, while remoting is highly customizable and extensible, varying by the specific application that uses it.

Remoting assumes the other end is .NET. This is because .NET remoting using SOAP uses the SoapFormatter to serialize data. SoapFormatter embeds the type information required to deserialize the object into the message itself. This requires that the client and the server must have access to this assembly. Remoting believes in the .NET Type System. Remoting believes in sharing types and assemblies. Remoting can support DCOM style Client Activated Objects which are stateful. The use of CAOs though have to be carefully thought about because CAOs cannot be load balanced. ASMX model does not assume that the other end is .NET. ASMX uses XmlSerializer to serialize data. Xmlserailizer believes that the XML Type System, that is the XSD is superior and works on serializing data conforming to a schema. In other words XML Web Services believe in sharing schema and contracts over types and assemblies. This makes the Web Services interoperable. ASMX services are usually stateless.

 24) Are the type system represented by XmlSchema and the CLS isomorphic?

No, there is some impedence mismtach. That's the reason you ned IXmlSerializable to help the XmlSerializer. XSD is not a type system in the traditional sense.

 25) Conceptually, what is the difference between early-binding and late-binding?

 Early binding means compiler get information of type calling/path execution during compilation of code and in late binding compiler doesn’t get that information but this information determined at runtime/execution time.

Early binding determines execution path at compilation, late binding allows for dynamic execution at runtime.


 26) Is using Assembly.Load a static reference or dynamic reference?

Its dynamic load (Reflection)

 27) When would using Assembly.LoadFrom or Assembly.LoadFile be appropriate?

When your assembly is not in the GAC.

Difference is only about binding. LoadFrom is flexible and if it doesn’t get assembly where it was pointing then it can be redirect to another path on the other hand LoadFile points/depends upon strictly to reference/path of the assembly defined, don’t redirect in case of failure.

 28) What is an Asssembly Qualified Name? Is it a filename? How is it different?

A type reference qualified by the name of the assembly it is referenced from.
Assembly qualified name contains assembly name, version, token key whereas filename is simple file name physically on file system. Assembly names store as Meta data as is very important by means of defining scope.

 29) Is this valid? Assembly.Load("foo.dll") ?

No. Assembly.Load(string) takes the full name of the assembly (as contained in the GAC), not the name of the file.

 30) How is a strongly-named assembly different from one that isn’t strongly-named?

Strongly-named assemblies can be loaded into the GAC and use key pairs to insure non-collision and authorship verification.
Strongly named assembly have strong names due to public token key so can be stored in GAC (shared environment) and can be referred by multiple programs whereas non-strongly name can’t be stored in GAC.

 31) Can DateTimes be null?

No. They are structs, not objects.

Before .net 2.0 it was not possible as datetime/integer… are struct/value types which can’t be null but due to nullable types now its possible.

 32) What is the JIT? What is NGEN? What are limitations and benefits of each?

JIT stands for Just in time compiler it compiles code into native code to execute by processor in three different techniques. It compiles code just before code required to be run which makes execution little slow (depends) so to avoid that we use NGEN which converts IL into native code like JIT but during deployment. It comes with large image which also includes that codes compiled version which is not being calling frequently.

JIT is Just-in-Time compiling, which natively compiles .NET code as it needs to be executed, allowing more flexibility in platform optimization. NGEN is the Native Image Generator, a tool which precompiles native code for assemblies and caches it for execution, pre-empting JIT. NGEN saves time at execution in exchange for potentially slowing execution on platforms other than the one it was originally executed for.


 33) How does the generational garbage collector in the .NET CLR manage object lifetime? What is non-deterministic finalization?

The garbage collector defines objects into multiple generations based upon their expected lifecycle, and collects each generation with different frequency. Non-deterministic finalization means that the Finalize() method of objects is not guaranteed to be called as soon as the object falls out of scope; it is executed when the garbage collector has time to prioritize it.

 34) What is the difference between Finalize() and Dispose()?

Finalize() is called by the garbage collector before destroying an object, allowing it to clean up resources it may have allocated. Dispose() is a method the programmer can call on an object to force resource deallocation (and pre-empt costly finalization).


 35) How is the using() pattern useful? What is IDisposable? How does it support deterministic finalization?

The using() construct allows you to mark a resource which is guaranteed to be disposed when the block exits. IDisposable provides an interface for the Dispose() method, which allows a programmer to forcibly finalize an object while still placing a Finalize() method in it as a means of security in case another programmer neglects to use Dispose().

 Using statement is quite handy and makes code quite efficient as right after end of using statement object created/declared in that statement disposed automatically means dispose method get called in deterministic way to free up memory. IDisposible is interface which classes implements to dispose unmanaged resources in deterministic manner.

 36) What does this useful command line do? tasklist /m "mscor*"

Allows you to see which processes currently running have loaded a specific library -- in this case, anything beginning with "MSCOR".

 37) What is the difference between in-proc and out-of-proc?

In-process communication is that between threads in a particular application space, as defined by the operating system. Out-of-process communication is that between non-shared memory and process spaces.

As name implies in proc means loading in the same process memory domain of invoker/host, it is fast technique but less reliable than out proc in case of any fault/exception occurs. Out proc is opposite to in proc definition and as loading out of the host process so is not depending and could be safe in host process failure for some reason.

 38) What technology enables out-of-proc communication in .NET?

Serialization ,  .net remoting through marshalling

 39) When you’re running a component within ASP.NET, what process is it running within on Windows XP? Windows 2000? Windows 2003?



 40) What is FullTrust? Do GAC’ed assemblies have FullTrust?

 41) What are Satellite Assemblies?

 42) What is Global Assembly Cache (GAC) and what is the purpose of it?

 43) What is Reflection in .NET?

 44) What is the managed and unmanaged code in .net?

 45) What are Namespaces?

 46) What are the access-specifiers available in c#?

 47) Advantage of ADO.Net?

 48) Difference between OLEDB Provider and SqlClient ?

 49) Differences between dataset.clone and dataset.copy?

 50) In a Webservice, need to display 10 rows from a table. So DataReader or DataSet is best choice?

 51) What is Remoting?

 52) What’s the difference between System.String and System.StringBuilder classes?

 53) What’s a delegate?

 54) What’s an interface class?

 55) What is the transport protocol you use to call a Web service ?

 56) What’s wrong with a line like this? DateTime.Parse(myString);

 57) What are PDBs? Where must they be located for debugging to work?

 58) What is cyclomatic complexity and why is it important?

 59) Write a standard lock() plus “double check” to create a critical section around a variable access.

 60) What benefit does your code receive if you decorate it with attributes demanding specific Security permissions?

 61) What does this do? gacutil /l | find /i "Corillian"

 62) What does this do? sn -t foo.dll

 63) What ports must be open for DCOM over a firewall? What is the purpose of Port 135?

 64) Contrast OOP and SOA. What are tenets of each?

 65) How does the XmlSerializer work? What ACL permissions does a process using it require?

 66) Why is catch(Exception) almost always a bad idea?

 67) What is the difference between Debug.Write and Trace.Write? When should each be used?

 68) What is the difference between a Debug and Release build? Is there a significant speed difference? Why or why not?

 69) Does JITting occur per-assembly or per-method? How does this affect the working set?

 70) Contrast the use of an abstract base class against an interface?

 71) What is the difference between a.Equals(b) and a == b?

 72) In the context of a comparison, what is object identity versus object equivalence?

 73) How would one do a deep copy in .NET?

 74) Explain current thinking around IClonable.

 75) What is boxing?

 76) Is string a value type or a reference type?

 77) What is the significance of the "PropertySpecified" pattern used by the XmlSerializer? What problem does it attempt to solve?

 78) Why are out parameters a bad idea in .NET? Are they?

 79) Can attributes be placed on specific parameters to a method? Why is this useful?

 80) Juxtapose the use of override with new. What is shadowing?

 81) Explain the use of virtual, sealed, override, and abstract.

 82) Explain the importance and use of each component of this string: Foo.Bar, Version=2.0.205.0, Culture=neutral, PublicKeyToken=593777ae2d274679d

 83) Explain the differences between public, protected, private and internal.

 84) What benefit do you get from using a Primary Interop Assembly (PIA)?

 85) By what mechanism does NUnit know what methods to test?

 86) What is the difference between: catch(Exception e){throw e;} and catch(Exception e){throw;}

 87) What is the difference between typeof(foo) and myFoo.GetType()?

 88) Explain what’s happening in the first constructor: public class c{ public c(string a) : this() {;}; public c() {;} } How is this construct useful?

 89) What is this? Can this be used within a static method?

C# Windows Forms

  • Write a simple Windows Forms MessageBox statement.
           System.Windows.Forms.MessageBox.Show("Hello, Windows Forms");

  • Can you write a class without specifying namespace? Which namespace does it belong to by default??
          Yes, you can, then the class belongs to global namespace which has no name. For commercial          products, naturally, you wouldn’t want global namespace. 

You are designing a GUI application with a window and several widgets on it. The user then resizes the app window and sees a lot of grey space, while the widgets stay in place. What’s the problem?One should use anchoring for correct resizing. Otherwise the default property of a widget on a form is top-left, so it stays at the same location when resized. 
How can you save the desired properties of Windows Forms application? .config files in .NET are supported through the API to allow storing and retrieving information. They are nothing more than simple XML files, sort of like what .ini files were before for Win32 apps.
So how do you retrieve the customized properties of a .NET application from XML .config file? Initialize an instance of AppSettingsReader class. Call the GetValue method of AppSettingsReader class, passing in the name of the property and the type expected. Assign the result to the appropriate variable.
Can you automate this process? In Visual Studio yes, use Dynamic Properties for automatic .config creation, storage and retrieval.
My progress bar freezes up and dialog window shows blank, when an intensive background process takes over. Yes, you should’ve multi-threaded your GUI, with taskbar and main form being one thread, and the background process being the other.
What’s the safest way to deploy a Windows Forms app? Web deployment: the user always downloads the latest version of the code; the program runs within security sandbox, properly written app will not require additional security privileges.
Why is it not a good idea to insert code into InitializeComponent method when working with Visual Studio? The designer will likely throw it away; most of the code inside InitializeComponent is auto-generated.
What’s the difference between WindowsDefaultLocation and WindowsDefaultBounds? WindowsDefaultLocation tells the form to start up at a location selected by OS, but with internally specified size. WindowsDefaultBounds delegates both size and starting position choices to the OS.
What’s the difference between Move and LocationChanged? Resize and SizeChanged? Both methods do the same, Move and Resize are the names adopted from VB to ease migration to C#.
How would you create a non-rectangular window, let’s say an ellipse? Create a rectangular form, set the TransparencyKey property to the same value as BackColor, which will effectively make the background of the form transparent. Then set the FormBorderStyle to FormBorderStyle.None, which will remove the contour and contents of the form.
How do you create a separator in the Menu Designer? A hyphen ‘-’ would do it. Also, an ampersand ‘&\’ would underline the next letter.
How’s anchoring different from docking? Anchoring treats the component as having the absolute size and adjusts its location relative to the parent form. Docking treats the component location as absolute and disregards the component size. So if a status bar must always be at the bottom no matter what, use docking. If a button should be on the top right, but change its position with the form being resized, use anchoring.

MVC Interview Questions

 What are the 3 main components of an ASP.NET MVC application?
1. M - Model
2. V - View
3. C - Controller

In which assembly is the MVC framework defined?
System.Web.Mvc

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

What does Model, View and Controller represent in an MVC application?
Model: Model represents the application data domain. In short the applications business logic is contained with in the model.

View: Views represent the user interface, with which the end users interact. In short the all the user interface logic is contained with in the UI.

Controller: Controller is the component that responds to user actions. Based on the user actions, the respective controller, work with the model, and selects a view to render that displays the user interface. The user input logic is contained with in the controller.

What is the greatest advantage of using asp.net mvc over asp.net webforms?
It is difficult to unit test UI with webforms, where views in mvc can be very easily unit tested.

Which approach provides better support for test driven development - ASP.NET MVC or ASP.NET Webforms?
ASP.NET MVC

What are the advantages of ASP.NET MVC?
1. Extensive support for TDD. With asp.net MVC, views can also be very easily unit tested.
2. Complex applications can be easily managed
3. Seperation of concerns. Different aspects of the application can be divided into Model, View and Controller.
4. ASP.NET MVC views are light weight, as they donot use viewstate.

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.

What is the role of a controller in an MVC application?
The controller responds to user interactions, with the application, by selecting the action method to execute and alse selecting the view to render.

Where are the routing rules defined in an asp.net MVC application?
In Application_Start event in Global.asax

Name a few different return types of a controller action method?
The following are just a few return types of a controller action method. In general an action method can return an instance of a any class that derives from ActionResult class.
1. ViewResult
2. JavaScriptResult
3. RedirectResult
4. ContentResult
5. JsonResult

What is the significance of NonActionAttribute?
In general, all public methods of a controller class are treated as action methods. If you want prevent this default behaviour, just decorate the public method with NonActionAttribute.

What is the significance of ASP.NET routing?
ASP.NET MVC uses ASP.NET routing, to map incoming browser requests to controller action methods. ASP.NET Routing makes use of route table. Route table is created when your web application first starts. The route table is present in the Global.asax file.

What are the 3 segments of the default route, that is present in an ASP.NET MVC application?
1st Segment - Controller Name
2nd Segment - Action Method Name
3rd Segment - Parameter that is passed to the action method

Example: http://pragimtech.com/Customer/Details/5
Controller Name = Customer
Action Method Name = Details
Parameter Id = 5

ASP.NET MVC application, makes use of settings at 2 places for routing to work correctly. What are these 2 places?
1. Web.Config File : ASP.NET routing has to be enabled here.
2. Global.asax File : The Route table is created in the application Start event handler, of the Global.asax file.

What is the adavantage of using ASP.NET routing?
In an ASP.NET web application that does not make use of routing, an incoming browser request should map to a physical file. If the file does not exist, we get page not found error.

An ASP.NET web application that does make use of routing, makes use of URLs that do not have to map to specific files in a Web site. Because the URL does not have 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.

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.

Is the following route definition a valid route definition?
{controller}{action}/{id}
No, the above definition is not a valid route definition, because there is no literal value or delimiter between the placeholders. Therefore, routing cannot determine where to separate the value for the controller placeholder from the value for the action placeholder.

What is the use of the following default route?
{resource}.axd/{*pathInfo}
This route definition, prevent requests for the Web resource files such as WebResource.axd or ScriptResource.axd from being passed to a controller.

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.

How do you handle variable number of segments in a route definition?
Use a route with a catch-all parameter. An example is shown below. * is referred to as catch-all parameter.
controller/{action}/{*parametervalues}

What are the 2 ways of adding constraints to a route?
1. Use regular expressions
2. Use an object that implements IRouteConstraint interface

Give 2 examples for scenarios when routing is not applied?
1. 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.
2. Routing Is Explicitly Disabled for a URL Pattern - Use the RouteCollection.Ignore() method to prevent routing from handling certain requests.

What is the use of action filters in an MVC application?
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 the different types of filters, in an asp.net mvc application?
1. Authorization filters
2. Action filters
3. Result filters
4. Exception filters

Give an example for Authorization filters in an asp.net mvc application?
1. RequireHttpsAttribute
2. AuthorizeAttribute

Which filter executes first in an asp.net mvc application?
Authorization filter


What are the levels at which filters can be applied in an asp.net mvc application?

1. Action Method
2. Controller
3. Application
[b]Is it possible to create a custom filter?[/b]
Yes

What filters are executed in the end?
Exception Filters

Is it possible to cancel filter execution?
Yes

What type of filter does OutputCacheAttribute class represents?
Result Filter

What are the 2 popular asp.net mvc view engines?
1. Razor
2. .aspx

What symbol would you use to denote, the start of a code block in razor views?
@

What symbol would you use to denote, the start of a code block in aspx views?
<%= %>

In razor syntax, what is the escape sequence character for @ symbol?
The escape sequence character for @ symbol, is another @ symbol

When using razor views, do you have to take any special steps to proctect your asp.net mvc application from cross site scripting (XSS) attacks?
No, by default content emitted using a @ block is automatically HTML encoded to protect from cross site scripting (XSS) attacks.

When using aspx view engine, to have a consistent look and feel, across all pages of the application, we can make use of asp.net master pages. What is asp.net master pages equivalent, when using razor views?
To have a consistent look and feel when using razor views, we can make use of layout pages. Layout pages, reside in the shared folder, and are named as _Layout.cshtml

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.

What are the file extensions for razor views?
1. .cshtml - If the programming lanugaue is C#
2. .vbhtml - If the programming lanugaue is VB

How do you specify comments using razor syntax?
Razor syntax makes use of @* to indicate the begining of a comment and *@ to indicate the end. An example is shown below.
@* This is a Comment *@
 
What is MVC?
MVC is a framework methodology that divides an application’s implementation into three component roles: models, views, and controllers.
“Models” in a MVC based application are the components of the application that are responsible for maintaining state. Often this state is persisted inside a database (for example: we might have a Product class that is used to represent order data from the Products table inside SQL).
“Views” in a MVC based application are the components responsible for displaying the application’s user interface. Typically this UI is created off of the model data (for example: we might create an Product “Edit” view that surfaces textboxes, dropdowns and checkboxes based on the current state of a Product object).
“Controllers” in a MVC based application are the components responsible for handling end user interaction, manipulating the model, and ultimately choosing a view to render to display UI. In a MVC application the view is only about displaying information – it is the controller that handles and responds to user input and interaction.
Which are the advantages of using MVC Framework?
MVC is one of the most used architecture pattern in ASP.NET and this is one of those ASP.NET interview question to test that do you really understand the importance of model view controller.
1. It provides a clean separation of concerns between UI and model.
2. UI can be unit test thus automating UI testing.
3. Better reuse of views and model. You can have multiple views which can point to the same model and also vice versa.
4. Code is better organized.
What is Razor View Engine?
Razor view engine is a new view engine created with ASP.Net MVC model using specially designed Razor parser to render the HTML out of dynamic server side code. It allows us to write Compact, Expressive, Clean and Fluid code with new syntaxes to include server side code in to HTML.
What is namespace of asp.net mvc?
ASP.NET MVC namespaces and classes are located in the System.Web.Mvc assembly.
System.Web.Mvc namespace 
Contains classes and interfaces that support the MVC pattern for ASP.NET Web applications. This namespace includes classes that represent controllers, controller factories, action results, views, partial views, and model binders.
System.Web.Mvc.Ajax namespace 
Contains classes that support Ajax scripts in an ASP.NET MVC application. The namespace includes support for Ajax scripts and Ajax option settings.
System.Web.Mvc.Async namespace 
Contains classes and interfaces that support asynchronous actions in an ASP.NET MVC application
System.Web.Mvc.Html namespace 
Contains classes that help render HTML controls in an MVC application. The namespace includes classes that support forms, input controls, links, partial views, and validation.
How to identify AJAX request with C# in MVC.NET?
The solution is in depended from MVC.NET framework and universal across server-side technologies. Most modern AJAX applications utilize XmlHTTPRequest to send async request to the server. Such requests will have distinct request header:
X-Requested-With = XMLHTTPREQUEST
AJAX GET Request
MVC.NET provides helper function to check for ajax requests which internally inspects X-Requested-With request header to set IsAjax flag.
HelperPage.IsAjax Property
Gets a value that indicates whether Ajax is being used during the request of the Web page.
Namespace: System.Web.WebPages
Assembly: System.Web.WebPages.dll
However, same can be achieved by checking requests header directly:
Request["X-Requested-With"] == “XmlHttpRequest”
What is Repository Pattern in ASP.NET MVC?
Repository pattern is usefult for decoupling entity operations form presentation, which allows easy mocking and unit testing.
“The Repository will delegate to the appropriate infrastructure services to get the job done. Encapsulating in the mechanisms of storage, retrieval and query is the most basic feature of a Repository implementation”
“Most common queries should also be hard coded to the Repositories as methods.”
Which MVC.NET to implement repository pattern Controller would have 2 constructors on parameterless for framework to call, and the second one which takes repository as an input:
class myController: Controller
{
    private IMyRepository repository;
    // overloaded constructor
    public myController(IMyRepository repository)
    {
        this.repository = repository;
    }
    // default constructor for framework to call
    public myController()
    {
        //concreate implementation
        myController(new someRepository());
    }
...
    public ActionResult Load()
    {
        // loading data from repository
        var myData = repository.Load();
    }
}
What is difference between MVC(Model-View-Controller) and MVP(Model-View-Presenter)?
The main difference between the two is how the manager (controller/presenter) sits in the overall architecture.
All requests goes first to the ControllerMVC pattern puts the controller as the main ‘guy’ in charge for running the show. All application request comes through straight to the controller, and it will decide what to do with the request.
Giving this level of authority to the controller isn’t an easy task in most cases. Users interaction in an application happen most of the time on the View.
Thus to adopt MVC pattern in a web application, for example, the url need to become a way of instantiating a specific controller, rather than ‘simply’ finding the right View (webform/ html page) to render out. Every requests need to trigger the instantiation of a controller which will eventually produce a response to the user.
This is the reason why it’s alot more difficult to implement pure MVC using Asp.Net Webform. The Url routing system in Asp.Net webform by default is tied in to the server filesystem or IIS virtual directory structure. Each of these aspx files are essentially Views which will always get called and instantiated first before any other classes in the project. (Of course I’m overgeneralizing here. Classes like IHttpModule, IHttpHandler and Global.asax would be instantiated first before the aspx web form pages).
MVP (Supervising Controller) on the other hand, doesn’t mind for the View to take on a bigger role. View is the first object instantiated in the execution pipeline, which then responsible for passing any events that happens on itself to the Presenter.
The presenter then fetch the Models, and pass it back to the view for rendering.
What is the ‘page lifecycle’ of an ASP.NET MVC?
Following process are performed by ASP.Net MVC page:
1) App initialization
2) Routing
3) Instantiate and execute controller
4) Locate and invoke controller action
5) Instantiate and render view
How to call javascript function on the change of Dropdown List in ASP.NET MVC?
Create a java-script function:
<script type="text/javascript">
            function selectedIndexChanged() {
            }
</script>
Call the function:
<%:Html.DropDownListFor(x => x.SelectedProduct,
new SelectList(Model.Products, "Value", "Text"),
"Please Select a product", new { id = "dropDown1",
onchange="selectedIndexChanged()" })%>
How route table is created in ASP.NET MVC?
When an MVC application first starts, the Application_Start() method is called. This method, in turn, calls the RegisterRoutes() method. The RegisterRoutes() method creates the route table.
How do you avoid XSS Vulnerabilities in ASP.NET MVC?
Use thesyntax in ASP.NET MVC instead of usingin .net framework 4.0.
Explain how to access Viewstate values of this page in the next page?
PreviousPage property is set to the page property of the nest page to access the viewstate value of the page in the next page.
Page poster = this.PreviousPage;
Once that is done, a control can be found from the previous page and its state can be read.
Label posterLabel = poster.findControl("myLabel");
 string lbl = posterLabel.Text;
How to create dynamic property with the help of viewbag in ASP.NET MVC?
PreviousPage property is set to the page property of the nest page to access the viewstate value of the page in the next page.
Page poster = this.PreviousPage;
Once that is done, a control can be found from the previous page and its state can be read.
Label posterLabel = poster.findControl("myLabel");
 string lbl = posterLabel.Text;
What is difference between Viewbag and Viewdata in ASP.NET MVC?
The basic difference between ViewData and ViewBag is that in ViewData instead creating dynamic properties we use properties of Model to transport the Model data in View and in ViewBag we can create dynamic properties without using Model data.
What is Routing?
A route is a URL pattern that is mapped to a handler. The handler can be a physical file, such as an .aspx file in a Web Forms application. Routing module is responsible for mapping incoming browser requests to particular MVC controller actions.