Saturday, 22 December 2012

Creating First ASP.NET MVC3 application

 Creating First ASP.NET MVC3 application
Hi,
Here I am going to told you that how to create simple ASP.NET MVC3 application using razor framework. In this demonstration I will told you how to create a Model, view and controller. Follow upcoming steps to create first ASP.NET MVC3 application.
1)      Open visual studio 2010 followed by C# project and then selects ASP.NET MVC3 Web application.
2)      Enter you web application name whatever you want and then click on OK. As well as you click on OK button you will find a dialog appears in front of you. This dialog box is created by ASP.NET MVC3. Here you specify which type of framework you want to use and you have to select an appropriate template.


In above image you will find two templates one is Empty and other one is Internet Application. If you want to start with built is sample then you can choose Internet Application or if you want to create sample application by yourself then you can choose Empty. I am going to select Empty template with Razor view engine.
Click on OK button.

3)      When you click on OK button then you will get following directory structure in your application.


Let’s understand meaning of directory which is related with ASP.NET MVC.
a)      Content: We can use this directory to store all Images and CSS related with web sites. As this is only convention which I follow. It’s not mandatory to put it on here. You can put anything on any place or you can follow your own convention. I am following convention which by default comes with ASP.NET MVC.
b)      Controllers: Controller’s are used to mange request and response of ASP.NET MVC website. Each browser request is mapped to a particular controller. Here I will put all controllers required for web site.
c)       Models: In ASP.NET MVC models are C# classes which describe behaviour of your views. We will use Models directory to store all model related with website.
d)      Scripts: This folder contains all jquery files which come with ASP.NET MVC.
e)      Views: This folder contains all views of your web application which finally render on browser.
Now we are ready to create our first ASP.NET MVC application.
Adding Person model in your web application
Here I am going to add first model of this web application. For adding model you can follow these steps.
1)      Right click on Model folder, followed by Add then click on Class option.
2)      After performing this action a dialog box open which ask for entering class name. I had created a class Named Person.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Excercise1.Models
{
    public class Person
    {
        public int PersonID { get; set; }
        public string PersonName { get; set; }
        public int PersonAge { get; set; }
        public string PersonCity { get; set; }
    }
}


Here I had created 4 properties in Person class. For creating this demonstration you can write code as follows. I will tell you later what purpose of this code is. For this time you can understand that these fields are used to render strongly typed view. Right now am not going to put any type of validation on models. I will tell you about validations in my next article.
Adding controller in your web application
For adding controller you can follow these steps.
1)      Right click on Controller directory followed by Add followed by controller. Then a dialog box appears where you will provide your controller name. Please note that after giving your controller name don’t remove controller convention. Here I am putting controller name Home.

Here you can see that I had put Home as a controller name and did’t remove Controller convention.

                After adding controller following line of codes are written in your controller class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Excercise1.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View();
        }

    }
}


Here you can see that  a method named Index(). Delete this method and write down following code in your controller.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Excercise1.Models;

namespace Excercise1.Controllers
{
    public class HomeController : Controller
    {
        [HttpGet]
        public ActionResult AcceptDetails()
        {
            return View();
        }

        [HttpPost]
        public ActionResult DisplayDetails(Person person)
        {
            return View(person);
        }
    }
}

Here you can see that I had created two methods, one name is AcceptDetails() and another one is DisplayDetails(). One thing important that in AcceptDetails method I had marked HttpGet which assured that we can send direct request to this method and other one is marked as HttpPost which means we cannot send direct request to that method. In other words we can understand that method marked by HttpGet is accessed by URL request and method not marked by HttpPost is not accessed by URL request. One thing more which you need to mention that in DisplayDetails() method I had passed refrense of Person class. For accessing Person class you need to add namespace of your model.
After writing your controller code it’s time to add view for your web application.
Here I am telling you simplest method to add views. Put cursor in method for which you want to add View, then write click followed by Add View option and click on it. An Add View dialog box appears which is as follows.
Note: Before performing this action please build your code so that all classes are available for creating strongly typed view.

Here you can see that View name is automatically display. Select Model class which you had created from Model class dropdown. If you build your code then Model class wills apear. Click on Add button to add view.
Add following code to this view.
@model Excercise1.Models.Person
@{
    ViewBag.Title = "AcceptDetails";
}
<h2>
    This is person accpet form.</h2>
@using (Html.BeginForm("DisplayDetails", "Home", @FormMethod.Post))
{
    @Html.EditorForModel()
    <p>
        <input type="submit" value="Submit Record" />
    </p>
}




Here You can see that I had created from using @Html.Begin form helper. Here you can see that for rendering model I used @Html.EditorForModel() helper which render your models.
Now you had successfully added first model. Now perform same task to add another view. Here I am providing code for another view.
@model Excercise1.Models.Person

@{
    ViewBag.Title = "DisplayDetails";
}

<h2>Displaying details of person class.</h2>
<p>ID : @Model.PersonID</p>
<p>Name : @Model.PersonName</p>
<p>Age : @Model.PersonAge</p>
<p>City : @Model.PersonCity</p>

Here you can see that I am using @Model helper to display details.
After performing this task now it’s time to making some routing configuration. By using routing configuration you told your web application that how to map request to controller and view.
For implementing routing configuration open global.asax file and modify code in RegisterRoutes() method.
public static void RegisterRoutes(RouteCollection routes)
{
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "AcceptDetails", id = UrlParameter.Optional } // Parameter defaults
            );

}


After performing this step you had create your first ASP.NET MVC3 application using razor framework. Now it’s time to execute your program. Press F5 to execute see it in action.
Here I am putting output.



Thanks to reading this article. I hope this article is useful for beginners . Please provide any comment and suggestion for articles.

Asp.net Difference between DataReader and DataSet and DataAdapter in C#, VB.NET

Asp.net Difference between DataReader and DataSet and DataAdapter in C#, VB.NET


Introduction:

In this article I will explain difference between datareader, dataset and dataadapter in asp.net.

Description:

In previous posts I explained Interview Questions in asp.net,C#,SQL, difference between Executereader, ExecuteNonQuery and ExecuteScalar, difference between Len and DataLength functions, difference between int,tinyint and bigint and differences between char, varchar and nvarchar in SQL Server. Now I will explain difference between datareader, dataset and dataadapter in asp.net

DataReader

DataReader is used to read the data from database and it is a read and forward only connection oriented architecture during fetch the data from database. DataReader is used to iterate through resultset that came from server and it will read one record at a time because of that memory consumption will be less and it will fetch the data very fast when compared with dataset. Generally we will use ExecuteReader object to bind data to datareader. (Read More)

Sample code of datareader will be like this

C# Code


// This method is used to bind gridview from database
protected void BindGridview()
{
using (SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select UserName,LastName,Location FROM UserInformation", con);
SqlDataReader dr = cmd.ExecuteReader();
gvUserInfo.DataSource = dr;
gvUserInfo.DataBind();
con.Close();
}
}
VB.NET Code


' This method is used to bind gridview from database
Protected Sub BindGridview()
Using con As New SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB")
con.Open()
Dim cmd As New SqlCommand("Select UserName,LastName,Location FROM UserInformation", con)
Dim dr As SqlDataReader = cmd.ExecuteReader()
gvUserInfo.DataSource = dr
gvUserInfo.DataBind()
con.Close()
End Using
End Sub
DataSet

DataSet is a disconnected orient architecture that means there is no need of active connections during work with datasets and it is a collection of DataTables and relations between tables. It is used to hold multiple tables with data. You can select data form tables, create views based on table and ask child rows over relations. Also DataSet provides you with rich features like saving data as XML and loading XML data.

C# Code


// This method is used to bind gridview from database
protected void BindGridview()
{
SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB");
con.Open();
SqlCommand cmd = new SqlCommand("select UserName,LastName,Location from UserInformation", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvUserInfo.DataSource = ds;
gvUserInfo.DataBind();
}
VB.NET Code


' This method is used to bind gridview from database
Protected Sub BindGridview()
Dim con As New SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB")
con.Open()
Dim cmd As New SqlCommand("select UserName,LastName,Location from UserInformation", con)
Dim da As New SqlDataAdapter(cmd)
Dim ds As New DataSet()
da.Fill(ds)
gvUserInfo.DataSource = ds
gvUserInfo.DataBind()
End Sub
DataAdapter

DataAdapter will acts as a Bridge between DataSet and database. This dataadapter object is used to read the data from database and bind that data to dataset. Dataadapter is a disconnected oriented architecture. Check below sample code to see how to use DataAdapter in code

C# Code


// This method is used to bind gridview from database
protected void BindGridview()
{
SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB");
con.Open();
SqlCommand cmd = new SqlCommand("select UserName,LastName,Location from UserInformation", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
gvUserInfo.DataSource = ds;
gvUserInfo.DataBind();
}
VB.NET Code


' This method is used to bind gridview from database
Protected Sub BindGridview()
Dim con As New SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB")
con.Open()
Dim cmd As New SqlCommand("select UserName,LastName,Location from UserInformation", con)
Dim da As New SqlDataAdapter(cmd)
Dim ds As New DataSet()
da.Fill(ds)
gvUserInfo.DataSource = ds
gvUserInfo.DataBind()
End Sub                      onclick="btnAdd_Click" />

Wednesday, 19 December 2012

Layout Manager Controls in SilverLight :

Layout Manager Controls in SilverLight :

                  1.Canvas
                  2.StackPanel
                  3.Grid
                  4.Border
                  5.You can always create your own

Features of Silverlight ?

Features of Silverlight:

1.It is a cross browser,cross platform technology.
2.Supported by all web browsers like IE,firefox,Apple safari,google chrome,opera.
3.It is Supported small download that installs in seconds.
4.It streams video and audio and scales video quality to everything from mobile videos to desktop browsers    to HDTV video modes.
5.It includes very efficient graphics mechnism that users can manipulate drag,turn and zoom directly  with in the browser.
6.It provides efficient databinding mechanisms.
7.It provides efficient graphic facilities,rendering facilities,transform facilities etc.

What is Silverlight ?

 What is Silverlight ?

Silverlight is a powerful development platform for creating rich media applications and business applications for the Web, desktop, and mobile devices.

Silverlight enables development of the next generation of Microsoft .NET-based media experiences and rich interactive applications (RIAs) for the Web. Silverlight is delivered as a cross-platform and cross-browser plug-in that exposes a programming framework and features that are a subset of the .NET Framework and Windows Presentation Foundation (WPF).

WCF Interview Questions With Answers for 1 year Experience

 WCF Interview Questions With Answers for 1 year Experience

What is WCF?
Windows Communication Foundation (WCF) is an SDK for developing and deploying services on Windows. WCF provides a runtime environment for services, enabling you to expose CLR types as services, and to consume other services as CLR types.

WCF is part of .NET 3.0 and requires .NET 2.0, so it can only run on systems that support it.
What is service and client in perspective of data communication?
A service is a unit of functionality exposed to the world.
The client of a service is merely the party consuming the service.
What is address in WCF and how many types of transport schemas are there in WCF?
Address is a way of letting client know that where a service is located. In WCF, every service is associated with a unique address. This contains the location of the service and transport schemas.

WCF supports following transport schemas

HTTP
TCP
Peer network
IPC (Inter-Process Communication over named pipes)
MSMQ

The sample address for above transport schema may look like

http://localhost:81
http://localhost:81/MyService
net.tcp://localhost:82/MyService
net.pipe://localhost/MyPipeService
net.msmq://localhost/private/MyMsMqService
net.msmq://localhost/MyMsMqService
What are contracts in WCF?
In WCF, all services expose contracts. The contract is a platform-neutral and standard way of describing what the service does.

WCF defines four types of contracts.

Service contracts

Describe which operations the client can perform on the service.
There are two types of Service Contracts.
ServiceContract - This attribute is used to define the Interface.
OperationContract - This attribute is used to define the method inside Interface.

[ServiceContract]



interface IMyContract

{
   [OperationContract]
   string MyMethod( );

}

class MyService : IMyContract

{

   public string MyMethod( )

   {

      return "Hello World";

   }


}



Data contracts

Define which data types are passed to and from the service. WCF defines implicit contracts for built-in types such as int and string, but we can easily define explicit opt-in data contracts for custom types.

There are two types of Data Contracts.
DataContract - attribute used to define the class
DataMember - attribute used to define the properties.

[DataContract]


class Contact
{
   [DataMember]
   public string FirstName;
   [DataMember]
   public string LastName;

}



If DataMember attributes are not specified for a properties in the class, that property can't be passed to-from web service.

Fault contracts

Define which errors are raised by the service, and how the service handles and propagates errors to its clients.


Message contracts

Allow the service to interact directly with messages. Message contracts can be typed or untyped, and are useful in interoperability cases and when there is an existing message format we have to comply with.
Where we can host WCF services?
Every WCF services must be hosted somewhere. There are three ways of hosting WCF services.

They are

1. IIS
2. Self Hosting
3. WAS (Windows Activation Service)

What is binding and how many types of bindings are there in WCF?
A binding defines how an endpoint communicates to the world. A binding defines the transport (such as HTTP or TCP) and the encoding being used (such as text or binary). A binding can contain binding elements that specify details like the security mechanisms used to secure messages, or the message pattern used by an endpoint.

WCF supports nine types of bindings.

Basic binding

Offered by the BasicHttpBinding class, this is designed to expose a WCF service as a legacy ASMX web service, so that old clients can work with new services. When used by the client, this binding enables new WCF clients to work with old ASMX services.

TCP binding

Offered by the NetTcpBinding class, this uses TCP for cross-machine communication on the intranet. It supports a variety of features, including reliability, transactions, and security, and is optimized for WCF-to-WCF communication. As a result, it requires both the client and the service to use WCF.


Peer network binding

Offered by the NetPeerTcpBinding class, this uses peer networking as a transport. The peer network-enabled client and services all subscribe to the same grid and broadcast messages to it.


IPC binding

Offered by the NetNamedPipeBinding class, this uses named pipes as a transport for same-machine communication. It is the most secure binding since it cannot accept calls from outside the machine and it supports a variety of features similar to the TCP binding.


Web Service (WS) binding

Offered by the WSHttpBinding class, this uses HTTP or HTTPS for transport, and is designed to offer a variety of features such as reliability, transactions, and security over the Internet.


Federated WS binding

Offered by the WSFederationHttpBinding class, this is a specialization of the WS binding, offering support for federated security.


Duplex WS binding

Offered by the WSDualHttpBinding class, this is similar to the WS binding except it also supports bidirectional communication from the service to the client.


MSMQ binding

Offered by the NetMsmqBinding class, this uses MSMQ for transport and is designed to offer support for disconnected queued calls.


MSMQ integration binding

Offered by the MsmqIntegrationBinding class, this converts WCF messages to and from MSMQ messages, and is designed to interoperate with legacy MSMQ clients.
What is endpoint in WCF?
Every service must have Address that defines where the service resides, Contract that defines what the service does and a Binding that defines how to communicate with the service. In WCF the relationship between Address, Contract and Binding is called Endpoint.

The Endpoint is the fusion of Address, Contract and Binding.
How to define a service as REST based service in WCF?
WCF 3.5 provides explicit support for RESTful communication using a new binding named WebHttpBinding.
The below code shows how to expose a RESTful service

[ServiceContract]
interface IStock
{
[OperationContract]
[WebGet]
int GetStock(string StockId);
}



By adding the WebGetAttribute, we can define a service as REST based service that can be accessible using HTTP GET operation.
What is the address formats of the WCF transport schemas?
Address format of WCF transport schema always follow

[transport]://[machine or domain][:optional port] format.

for example:

HTTP Address Format

http://localhost:8888
the way to read the above url is

"Using HTTP, go to the machine called localhost, where on port 8888 someone is waiting"
When the port number is not specified, the default port is 80.

TCP Address Format

net.tcp://localhost:8888/MyService

When a port number is not specified, the default port is 808:

net.tcp://localhost/MyService

NOTE: Two HTTP and TCP addresses from the same host can share a port, even on the same machine.

IPC Address Format
net.pipe://localhost/MyPipe

We can only open a named pipe once per machine, and therefore it is not possible for two named pipe addresses to share a pipe name on the same machine.

MSMQ Address Format
net.msmq://localhost/private/MyService
net.msmq://localhost/MyService
What is Proxy and how to generate proxy for WCF Services?
The proxy is a CLR class that exposes a single CLR interface representing the service contract. The proxy provides the same operations as service's contract, but also has additional methods for managing the proxy life cycle and the connection to the service. The proxy completely encapsulates every aspect of the service: its location, its implementation technology and runtime platform, and the communication transport.

The proxy can be generated using Visual Studio by right clicking Reference and clicking on Add Service Reference. This brings up the Add Service Reference dialog box, where you need to supply the base address of the service (or a base address and a MEX URI) and the namespace to contain the proxy.

Proxy can also be generated by using SvcUtil.exe command-line utility. We need to provide SvcUtil with the HTTP-GET address or the metadata exchange endpoint address and, optionally, with a proxy filename. The default proxy filename is output.cs but you can also use the /out switch to indicate a different name.

SvcUtil http://localhost/MyService/MyService.svc /out:Proxy.cs

When we are hosting in IIS and selecting a port other than port 80 (such as port 88), we must provide that port number as part of the base address:

SvcUtil http://localhost:88/MyService/MyService.svc /out:Proxy.cs
What are different elements of WCF Srevices Client configuration file?

WCF Services client configuration file contains endpoint, address, binding and contract. A sample client config file looks like

<system.serviceModel>

   <client>
      <endpoint name = "MyEndpoint"
         address  = "http://localhost:8000/MyService/"
         binding  = "wsHttpBinding"
         contract = "IMyContract"
      />
   </client>

</system.serviceModel>

What is Transport and Message Reliability?

Transport reliability (such as the one offered by TCP) offers point-to-point guaranteed delivery at the network packet level, as well as guarantees the order of the packets. Transport reliability is not resilient to dropping network connections and a variety of other communication problems.

Message reliability deals with reliability at the message level independent of how many packets are required to deliver the message. Message reliability provides for end-to-end guaranteed delivery and order of messages, regardless of how many intermediaries are involved, and how many network hops are required to deliver the message from the client to the service.
How to configure Reliability while communicating with WCF Services?

Reliability can be configured in the client config file by adding reliableSession under binding tag.

<system.serviceModel>
   <services>
      <service name = "MyService">
         <endpoint
            address  = "net.tcp://localhost:8888/MyService"
            binding  = "netTcpBinding"
            bindingConfiguration = "ReliableCommunication"

            contract = "IMyContract"
         />
      </service>
   </services>
   <bindings>

      <netTcpBinding>

         <binding name = "ReliableCommunication">

            <reliableSession enabled = "true"/>

         </binding>

      </netTcpBinding>
  </bindings>
</system.serviceModel>


Reliability is supported by following bindings only

NetTcpBinding
WSHttpBinding
WSFederationHttpBinding
WSDualHttpBinding

How to set the timeout property for the WCF Service client call?
The timeout property can be set for the WCF Service client call using binding tag.

<client>
   <endpoint
      ...



      binding = "wsHttpBinding"
      bindingConfiguration = "LongTimeout"

      ...



   />
</client>
<bindings>
   <wsHttpBinding>
      <binding name = "LongTimeout" sendTimeout = "00:04:00"/>

   </wsHttpBinding>
</bindings>



If no timeout has been specified, the default is considered as 1 minute.
How to deal with operation overloading while exposing the WCF services?

By default overload operations (methods) are not supported in WSDL based operation. However by using Name property of OperationContract attribute, we can deal with operation overloading scenario.

[ServiceContract]
interface ICalculator
{
   [OperationContract(Name = "AddInt")]

   int Add(int arg1,int arg2);

   [OperationContract(Name = "AddDouble")]
   double Add(double arg1,double arg2);
}

Asp.net real time MVC Interview Quesitons with answers

 Asp.net real time MVC Interview Quesitons with answers

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.

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

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 ‘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

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

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

Examplehttp://nareshkamuni.blogspot.in/search/label/MVC
Controller Name = search
Action Method Name = label
Parameter Id = MVC

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.
How do you avoid XSS Vulnerabilities in ASP.NET MVC?
Use thesyntax in ASP.NET MVC instead of usingin .net framework 4.0.

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