Mar 31, 2014

Difference Between DataReader, DataSet, DataAdapter and DataTable in C#

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 will fetch the data very fast when compared with dataset. Generally we will use ExecuteReader object to bind data to datareader.To bind DataReader data to GridView we need to write the code like as shown below:

Protected void BindGridview()
{
using (SqlConnection conn = new SqlConnection("Data Source=abc;Integrated Security=true;Initial Catalog=Test"))
{
con.Open();
SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Location FROM Users", conn);
SqlDataReader sdr = cmd.ExecuteReader();
gvUserInfo.DataSource = sdr;
gvUserInfo.DataBind();
conn.Close();
}
}
  • Holds the connection open until you are finished (don't forget to close it!).
  • Can typically only be iterated over once
  • Is not as useful for updating back to the database
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.
protected void BindGridview()
{
    SqlConnection conn = new SqlConnection("Data Source=abc;Integrated Security=true;Initial Catalog=Test");    
conn.Open();   
 SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Location FROM Users", conn);  
 SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();  
da.Fill(ds);    
gvUserInfo.DataSource = ds;   
 gvUserInfo.DataBind();
}

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:

protected void BindGridview()

{    
SqlConnection con = new SqlConnection("Data Source=abc;Integrated Security=true;Initial Catalog=Test"); 
conn.Open();   
 SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Location FROM Users", conn);   
SqlDataAdapter sda = new SqlDataAdapter(cmd);   
 DataSet ds = new DataSet();    
da.Fill(ds);    
gvUserInfo.DataSource = ds;    
gvUserInfo.DataBind();
}
  • Lets you close the connection as soon it's done loading data, and may even close it for you automatically
  • All of the results are available in memory
  • You can iterate over it as many times as you need, or even look up a specific record by index
  • Has some built-in faculties for updating back to the database.
DataTable 

DataTable represents a single table in the database. It has rows and columns. There is no much difference between dataset and datatable, dataset is simply the collection of datatables.

protected void BindGridview()
{     
sqlConnection con = new SqlConnection("Data Source=abc;Integrated Security=true;Initial Catalog=Test");    
 conn.Open();     
SqlCommand cmd = new SqlCommand("Select UserName, First Name,LastName,Location FROM Users", conn);     
SqlDataAdapter sda = new SqlDataAdapter(cmd);     
DataTable dt = new DataTable();     
da.Fill(dt);     
gridview1.DataSource = dt;     
gvidview1.DataBind();

}

Mar 14, 2014

MVC Interview Questions/Answers

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 *@

Mar 3, 2014

Top 50 asp.net interview questions

1. What is ASP.Net?
It is a framework developed by Microsoft on which we can develop new generation web sites using web forms(aspx), MVC, HTML, Javascript, CSS etc. Its successor of Microsoft Active Server Pages(ASP). Currently there is ASP.NET 4.0, which is used to develop web sites. There are various page extensions provided by Microsoft that are being used for web site development. Eg: aspx, asmx, ascx, ashx, cs, vb, html, xml etc.

2. What’s the use of Response.Output.Write()? We can write formatted output  using Response.Output.Write().

3. In which event of page cycle is the ViewState available?   After the Init() and before the Page_Load().

4. What is the difference between Server.Transfer and Response.Redirect?  
In Server.Transfer page processing transfers from one page to the other page without making a round-trip back to the client’s browser.  This provides a faster response with a little less overhead on the server.  The clients url history list or current url Server does not update in case of Server.Transfer.
Response.Redirect is used to redirect the user’s browser to another page or site.  It performs trip back to the client where the client’s browser is redirected to the new page.  The user’s browser history list is updated to reflect the new address.

5. From which base class all Web Forms are inherited?
Page class. 

6. What are the different validators in ASP.NET?
  1. Required field Validator
  2. Range  Validator
  3. Compare Validator
  4. Custom Validator
  5. Regular expression Validator
  6. Summary Validator
7. Which validator control you use if you need to make sure the values in two different controls matched?
Compare Validator control.

8. What is ViewState?
ViewState is used to retain the state of server-side objects between page post backs.

9. Where the viewstate is stored after the page postback?
ViewState is stored in a hidden field on the page at client side.  ViewState is transported to the client and back to the server, and is not stored on the server or any other external source.

10. How long the items in ViewState exists?
They exist for the life of the current page.

11. What are the different Session state management options available in ASP.NET?
  1. In-Process
  2. Out-of-Process.
In-Process stores the session in memory on the web server.
Out-of-Process Session state management stores data in an external server.  The external server may be either a SQL Server or a State Server.  All objects stored in session are required to be serializable for Out-of-Process state management.

12. How you can add an event handler?
 Using the Attributes property of server side control.
e.g.
[csharp]
btnSubmit.Attributes.Add(“onMouseOver”,”JavascriptCode();”)
[/csharp]

13. What is caching?
Caching is a technique used to increase performance by keeping frequently accessed data or files in memory. The request for a cached file/data will be accessed from cache instead of actual location of that file.

14. What are the different types of caching?
ASP.NET has 3 kinds of caching :
  1. Output Caching,
  2. Fragment Caching,
  3. Data Caching.
15. Which type if caching will be used if we want to cache the portion of a page instead of whole page?
Fragment Caching: It caches the portion of the page generated by the request. For that, we can create user controls with the below code:
[xml]
<%@ OutputCache Duration=”120″ VaryByParam=”CategoryID;SelectedID”%>
[/xml]

16. List the events in page life cycle.
  1) Page_PreInit
2) Page_Init
3) Page_InitComplete
4) Page_PreLoad
5) Page_Load
6) Page_LoadComplete
7) Page_PreRender
8)Render

17. Can we have a web application running without web.Config file?
  Yes

18. Is it possible to create web application with both webforms and mvc?
Yes. We have to include below mvc assembly references in the web forms application to create hybrid application.
[csharp]
System.Web.Mvc
System.Web.Razor
System.ComponentModel.DataAnnotations
[/csharp]

19Can we add code files of different languages in App_Code folder?
  No. The code files must be in same language to be kept in App_code folder.

20. What is Protected Configuration?
It is a feature used to secure connection string information.

21. Write code to send e-mail from an ASP.NET application?
[csharp]
MailMessage mailMess = new MailMessage ();
mailMess.From = “abc@gmail.com”;
mailMess.To = “xyz@gmail.com”;
mailMess.Subject = “Test email”;
mailMess.Body = “Hi This is a test mail.”;
SmtpMail.SmtpServer = “localhost”;
SmtpMail.Send (mailMess);
[/csharp]
MailMessage and SmtpMail are classes defined System.Web.Mail namespace.

 22. How can we prevent browser from caching an ASPX page?
  We can SetNoStore on HttpCachePolicy object exposed by the Response object’s Cache property:
[csharp]
Response.Cache.SetNoStore ();
Response.Write (DateTime.Now.ToLongTimeString ());
[/csharp]

23. What is the good practice to implement validations in aspx page?
Client-side validation is the best way to validate data of a web page. It reduces the network traffic and saves server resources.

24. What are the event handlers that we can have in Global.asax file?

Application Events: Application_Start , Application_End, Application_AcquireRequestState, Application_AuthenticateRequest, Application_AuthorizeRequest, Application_BeginRequest, Application_Disposed,  Application_EndRequest, Application_Error, Application_PostRequestHandlerExecute, Application_PreRequestHandlerExecute,
Application_PreSendRequestContent, Application_PreSendRequestHeaders, Application_ReleaseRequestState, Application_ResolveRequestCache, Application_UpdateRequestCache
Session Events: Session_Start,Session_End

25. Which protocol is used to call a Web service?
HTTP Protocol

26. Can we have multiple web config files for an asp.net application?
Yes.

27. What is the difference between web config and machine config?
Web config file is specific to a web application where as machine config is specific to a machine or server. There can be multiple web config files into an application where as we can have only one machine config file on a server.

28.  Explain role based security ?
  Role Based Security used to implement security based on roles assigned to user groups in the organization.
Then we can allow or deny users based on their role in the organization. Windows defines several built-in groups, including Administrators, Users, and Guests.
[xml]
<AUTHORIZATION>< authorization >
< allow roles=”Domain_Name\Administrators” / >   < !– Allow Administrators in domain. — >
< deny users=”*”  / >                            < !– Deny anyone else. — >
< /authorization >
[/xml]

29. What is Cross Page Posting?
When we click submit button on a web page, the page post the data to the same page. The technique in which we post the data to different pages is called Cross Page posting. This can be achieved by setting POSTBACKURL property of  the button that causes the postback. Findcontrol method of PreviousPage can be used to get the posted values on the page to which the page has been posted.

30. How can we apply Themes to an asp.net application?
We can specify the theme in web.config file. Below is the code example to apply theme:
[xml]
<configuration>
<system.web>
<pages theme=”Windows7″ />
</system.web>
</configuration>
[/xml]

31: What is RedirectPermanent in ASP.Net?
  RedirectPermanent Performs a permanent redirection from the requested URL to the specified URL. Once the redirection is done, it also returns 301 Moved Permanently responses.

32: What is MVC?
MVC is a framework used to create web applications. The web application base builds on  Model-View-Controller pattern which separates the application logic from UI, and the input and events from the user will be controlled by the Controller.

33. Explain the working of passport authentication.
First of all it checks passport authentication cookie. If the cookie is not available then the application redirects the user to Passport Sign on page. Passport service authenticates the user details on sign on page and if valid then stores the authenticated cookie on client machine and then redirect the user to requested page

34. What are the advantages of Passport authentication?
All the websites can be accessed using single login credentials. So no need to remember login credentials for each web site.
Users can maintain his/ her information in a single location.

35. What are the asp.net Security Controls?
  • <asp:Login>: Provides a standard login capability that allows the users to enter their credentials
  • <asp:LoginName>: Allows you to display the name of the logged-in user
  • <asp:LoginStatus>: Displays whether the user is authenticated or not
  • <asp:LoginView>: Provides various login views depending on the selected template
  • <asp:PasswordRecovery>:  email the users their lost password
36: How do you register JavaScript for webcontrols ?
We can register javascript for controls using <CONTROL -name>Attribtues.Add(scriptname,scripttext) method.

37. In which event are the controls fully loaded?
Page load event.

38: what is boxing and unboxing?
Boxing is assigning a value type to reference type variable.
Unboxing is reverse of boxing ie. Assigning reference type variable to value type variable.

39. Differentiate strong typing and weak typing
In strong typing, the data types of variable are checked at compile time. On the other hand, in case of weak typing the variable data types are checked at runtime. In case of strong typing, there is no chance of compilation error. Scripts use weak typing and hence issues arises at runtime.

40. How we can force all the validation controls to run?
The Page.Validate() method is used to force all the validation controls to run and to perform validation.

41. List all templates of the Repeater control.
  • ItemTemplate
  • AlternatingltemTemplate
  • SeparatorTemplate
  • HeaderTemplate
  • FooterTemplate
42. List the major built-in objects in ASP.NET? 
  • Application
  • Request
  • Response
  • Server
  • Session
  • Context
  • Trace
43. What is the appSettings Section in the web.config file?
The appSettings block in web config file sets the user-defined values for the whole application.
For example, in the following code snippet, the specified ConnectionString section is used throughout the project for database connection:
[csharp]
<em><configuration>
<appSettings>
<add key=”ConnectionString” value=”server=local; pwd=password; database=default” />
</appSettings></em>
[/csharp]

44.      Which data type does the RangeValidator control support?
The data types supported by the RangeValidator control are Integer, Double, String, Currency, and Date.

45. What is the difference between an HtmlInputCheckBox control and anHtmlInputRadioButton control?
In HtmlInputCheckBoxcontrol, multiple item selection is possible whereas in HtmlInputRadioButton controls, we can select only single item from the group of items.

46. Which namespaces are necessary to create a localized application?
System.Globalization
System.Resources

47. What are the different types of cookies in ASP.NET?
Session Cookie – Resides on the client machine for a single session until the user does not log out.
Persistent Cookie – Resides on a user’s machine for a period specified for its expiry, such as 10 days, one month, and never.

48. What is the file extension of web service?
Web services have file extension .asmx..

49. What are the components of ADO.NET?
The components of ADO.Net are Dataset, Data Reader, Data Adaptor, Command, connection.

50. What is the difference between ExecuteScalar and ExecuteNonQuery?
ExecuteScalar returns output value where as ExecuteNonQuery does not return any value but the number of rows affected by the query. ExecuteScalar used for fetching a single value and ExecuteNonQuery used to execute Insert and Update statements.