HI WELCOME TO SIRIS

ASP.Net Interview Questions and Answers

Leave a Comment
62) What is difference between Data list, Grid view and Repeater?
All these controls have many things in common like Data Source Property, Data Bind Method ItemDataBound and ItemCreated.
When Data Source Property of a Grid view is assigned to a Dataset then each Data Row present in the Data Row Collection of Data Table is assigned to a corresponding DataGridItem and this is same for the rest of the two controls also. But The HTML code generated for a Grid view has an HTML TABLE <ROW> element created for the particular Data Row and it’s a Table form representation with Columns and Rows.
For a Data list it’s an Array of Rows and based on the Template Selected and the RepeatColumn Property value we can specify how many Data Source records should appear per HTML <table> row. In short in Grid view we have one record per row, where as in data list we can have five or six rows per row. In Repeater Control the data records which are to be displayed depends upon the Templates specified and the only HTML generated is the due to the Templates.
63) What are the difference between adding the items into cache through the Add () method and through the Insert () method?
  • Cache.Add() will return an object that represents the item added in the cache.
  • Cache.Insert() is going to replace the existing item in the cache which will not happen in Cache.Add().
64) What is the use of "EnableViewState" property?
This property is used to enable the ViewState property on the page. It is set to ON, to allow it to save the input values of the user between postback requests. When is set to OFF, it won't allow to save the user input in postbacks.
65) List all different typesS of directives in .NET?
The different types of directive in .Net –
  • @Import
  • @Page
  • @Control
  • @Register
  • @Reference
  • @Assembly
  • @OutputCache
  • @Implements
66) How to decide on the design consideration to take a GridView, Datalist or Repeater?
  • GridView provides ability to allow the end-user to edit the page data or sort the page records. But it comes at a cost of speed. Secondly, the display format is very simple i.e. is in row and columns.
  • With its templates, DataList provides more control over the look and feel of the displayed data than the GridView. And it offers better performance than GridView.
  • With Repeater, the only HTML emitted are the values of the databinding statements in the templates along with the HTML markup specified in the templates—no "extra" HTML is emitted, as with theGrdiview and DataList.
67) Which Javascript file is responsible for validation at the client side?
WebUIValidation.js javascript file is mainly used for validation by the validators at client side. This file will be installed at "aspnet_client" at IIS directory.
68) What is .Net Remoting?
.Net Remoting is considered as the replacement for DCOM. Using .Net remoting remote object calls can be done which lies in different Application domains. As the remote objects runs under different process, client which calls remote object cannot call directly.
69) What is Application Domain?
Application Domain is logical boundary created for .NET applications so that one application does not affect the other applications. .NET runtime uses Appdomain as a container for data and code.
70) In ASP.NET how many navigation controls are there?
Navigation controls will be used to navigate in a Web application. These controls will store the links either in hierarchical structure or drop-down structure. Navigation controls available in ASP.NET are –
  • Tree View
  • Menu
  • Sitemap Path
71) What is Delay signing?
During development process, you will need strong name keys to be exposed to developer which is not a good practice from security point of view. In these situations you can assign the key later on and during development, you can use delay signing.
72) What are server-side comments?
Server side comments are used in ASP.NET page. This is used to describe the purpose of code snippet.
<%--This is how server-side comments can be done -- %>
Server side comments always begins with
 “<%--“ and ends with “-- %>”.
73) What are the common properties of all validation controls?
  • ControlToValidate – control name to be validated.
  • ErrorMessage – error message to be displayed on validation fail.
  • IsValid – Boolean value for checking control’s validation has succeeded or not.
  • Text – displaying the text before validation for validation control.
74) What is cross-page posting?
Server.Transfer() method is used for posting the data from one page to another.
In cross page posting, data collected from different pages and will be displayed in single page. So, for doing this we need to set “PostBackUrl” property of the control, in which target page is specified and in target page we can use “PreviousPage” property. For doing this we need to set the directive - @PreviousPageType. Previous page control can be accessed from the method – “FindControl()”.
75) How to differentiate a sub master page from a top-level master page?
As content page, sub master page will not be having complete HTML source code. But at top level master page unlike sub master page it will have complete HTML source code in source file.
76) What’s the difference between Linkbutton control and Hyperlink control?
  • Link buttons will have events which can be handled in code behind file. 
  • Hyperlink control will not be having events like click and command events.
77) Where is ViewState information stored ?
Viewstate information is always stored in HTML hidden fields.
78) What is the significance of Finalize method in .NET?
.NET Garbage collector does almost all clean up activity for your objects. But unmanaged resources (ex: - Windows API Database connection objects, File, created objects, COM objects etc) is outside the scope of .NET framework we have to explicitly clean our resources. For these types of objects, .NET framework will provide Object.Finalize method which will be overridden and clean up code for unmanaged resources can be put in this section.
79) What are the best ways to send data across pages in ASP.NET?
Below are the two ways used to send data across pages in ASP.NET –
  • Public properties
  • Session
80) What are Web Part controls in ASP.NET?
Web part controls are integrated controls which are used to create a website. This allows the user to change the outlook, content and state of the pages in browser.
81) What is the use of Global.asax ? and explain the events in Global.asax ?
It allows to executing ASP.NET application level events and setting application-level variables.
  • Application_Init
  • Application_Disposed
  • Application_Error
  • Application_Start
  • Application_End
  • Application_BeginRequest
  • Application_EndRequest
  • Application_PreRequestHandlerExecute
  • Application_PostRequestHandlerExecute
  • Applcation_PreSendRequestHeaders
  • Application_PreSendContent
  • Application_AuthenticateRequest
  • Application_AuthorizeRequest
  • Session_Start
  • Session_End
82) How we can copy items of one dropdownlist to another dropdownlist control?
Foreach ( var listitem in firstdropdownlist.Items)
{
seconddropdownlist.Items.Add(listitem);
}
In the above code we are getting all the items from first dropdownlist and then add it to the item list of second dropdownlist.
83) What’s the difference between Literal control and Label control?
Label control mark up is given below –
<asp:Label ID = "Label1" Text="Label Test" runat="server" />
  • Label control is rendered as <span> when rendered as HTML. Label control styles like font size, font color etc can be changed with very less effort. Javascript or JQuery also can access the label control very easily.
  • Literal control rendered as it is. Literal control cannot be styled easily like label control because it does not render in enclosed HTML tags. Javascript or Jquery will not be able to access literal control because while rendering it would not have ID in spite of giving the ID in mark up.
84) Explain the components of web form in ASP.NET?
Server controls - The server controls are Hypertext Markup Language (HTML) elements that include a runat=server attribute. These controls provide automatic state management and server-side events and respond to the user events by executing event handler on the server.
  • HTML controls - These controls also respond to the user events but the events processing happen on the client machine.
  • Data controls - Data controls allows us to connect to the database, execute command and retrieve data from database.
85) Which are the different IIS isolation levels in ASP.NET?
IIS has three level of isolation –
  • LOW (IIS process) - In this, ASP.NET application and main IIS process run in same process. So, if any application crashes it will adversely affect the others too.
  • Medium (Pooled) - In Medium pooled scenario the IIS and web application run in different process. So in this case there will be two processes process1 and process2. Process1 runs the IIS process and Process2 runs the Web application.
  • High (Isolated) - Here every process runs under it’s own process. This consumes heavy memory but has highest reliability.
86) What is Virtual folder?
It is the physical folder that contains web applications. This folder is used by IIS for web application deployment.
87) Why to use “CustomErrors” section in config?
CustomError tag gives the details of custom error messages. CustomError tag can be defined at any level in application file hierarchy.
<configuration>
<system.web>
<customErrors mode="RemoteOnly" defaultRedirect="A4academicsError.html"/>
</system.web>
</configuration>
As you can see above customError section has attribute - "defaultRedirect", which specifies the default redirection.
88) How to open a page in a new window?
To open a page in a new window, we have to use client script using onclick="window.open()" attribute of mainly HTML control.
89) What exactly happens when ASPX page is requested from Browser?
Following are the steps which will occur when we request an ASPX page from web server –
  • The browser sends the request to the webserver. Let’s assume the webserver at the other end is IIS.
  • Once IIS receives the request, it looks for engine where it can serve this request. When engine means it’s the DLL which can parse this page or compile and send a response back to browser. The request which is to be mapped is decided by file extension of the page requested.
Some File extension mapping given below -
  • .aspx, for ASP.NET Web pages,
  • .asmx, for ASP.NET Web services,
  • .config, for ASP.NET configuration files,
  • .ashx, for custom ASP.NET HTTP handlers,
  • .rem, for remoting resources
90) What is the sequence of methods called during page load?
  • Init() – This method will be used to Initialize the page.
  • Load() – This method loads the page in server memory.
  • PreRender() – This method is before page loaded to the user.
  • Unload() – This method runs once loading of the page finished.
91) What is Reflection?
Reflection is a mechanism through which types defined in the metadata of each module can be accessed. The System.Reflection namespace will have the classes that can be used to define the types for an assembly.
92) What is the use of "HttpHandlers" in web.config ?
HttpHandler will be called once the request comes from client machine. Example: one .aspx or .asmx file is requested.
<configuration>
<system.web>
<compilation debug="true"/>
<httpHandlers>
<add verb="*" path="*.xsl" type="Handler" />
</httpHandlers>
</system.web>
</configuration>
Mapping will be done for the requests to appropriate handlers based on URL and HTTP request verb.
93) From web.config how to read connectionstring?
string constr = ConfigurationManager.ConnectionStrings["TestMyconnectionstring"].ToString();
94) What is role based security?
Role Based Security is basically used to implement security based on roles. We have an option to allow or deny some roles for our application. Below is the sample code snippet used in web.config –
<authorization>
<allow roles=”roles to be allowed” <!—Allowing the roles. -->
<deny users =”*”/>
</authorization>
95) How to apply themes for asp.net application?
<configuration>
<system.web>
<pages theme=”windows 8”>
</system.web>
</configuration>
96) Which are the namespaces used to create a localized application?
Namesspaces used for localization are –
  • System.Resources and
  • System.Globalization
97) Can we use different programming languages in the same web application?
Yes of course we can do it. We can create some web pages with C# language and some pages in VB.NET but the same is false when we mix up multiple programming languages in the same project because each project will be built to a single dll.
98) How can we change a Master Page at runtime?
Using page events we can change the master page during runtime. In Page_PreInit() event we can change the master page by setting the “MasterPageFile” property to the path of the master page what we have to set.
99) What are Application Pools?
Once the web application is deployed into IIS, we can set the Application Pool to the website directory where web application hosted/deployed. Application Pool is assigned to the website to make it secure and confidential. Multiple websites can be assigned under a single application pool which in turn will be under a single worker process. (Multiple worker process can also be assigned for a single application pool in the settings).
100) Why “AutoEventWireup” is used?
AutoEventWireup is used for wiring up the events in page so that it can be given at the page level. Value of this attribute is Boolean (true or false). By default it is set to “true” for C# web form where as, it is “false” for VB.NET web forms.
101) Performance wise which is better, Session or ViewState?
  • For large amount of data, Session will be an efficient way to go. When session is not used, set it to null for memory overhead but this cannot be done in all the cases. Once the session timeout happened it automatically set to null. Default timeout is 20 minutes.
  • In Viewstate, all data will be stored in HTML hidden fields. For large amount of data, it would give performance issues. Ideal size of viewstate should not be more than 20-30% of page size. So for less data viewstate will be an ideal solution.
102) How to display all validation messages in validation controls?
By adding ValidationSummary control to web page we can display all the validation messages related to different validation controls.
103) Why to use "Orientation" property of Menu control?
Orientation property is used to set the display of menu vertically or horizontally. By default the value of this property is vertical.
104) How to kill a user session?
When a user logs into the website, it’s a good practice to create a new session to track the user activities. So, meantime we need to handle log out scenario as well. So, we will kill a user session once user logs out of the application. Below is the code snippet that can be written to kill the user session –
  • Session.Abandon();
105) How to use a checkbox in a gridview?
Following are the steps to be used. Add Itemtemplate tag in gridview like below -
<ItemTemplate> 
<asp:CheckBox id="TestMyCheckBox" runat="server" AutoPostBack="True" OnCheckedChanged="Check_Clicked"></asp:CheckBox>
</ItemTemplate>
If you look at the Itemtemplate we have “OnCheckChanged” event. This “OnCheckChanged” event has “Check_Clicked” subroutine which actually resides in behind code and this method should either be “protected” or “public”. Sample code snippet shown below –
Protected Sub Check_Clicked(ByVal senderobj As Object, ByVal e As EventArgs) 
// do something
End Sub
106) How can we format data inside Gridview?
We can format data using – “DataFormatString” property.
107) How do you upload a file in ASP.NET?
ASP.NET provides two controls that lets user to upload files to server. Once web server receives the file, it can take any actions on that file. Controls used for uploading file are –
  • FileUpload – This is an ASP.NET control.
  • HtmlInputFile – This is HTML Server control.
108) What are the common properties Button controls used in ASP.NET?
Following are the list of properties used –
  • Text – This property is used to display the text of button.
  • CausesValidation – This property is used to determine whether validation occurs in page once button is clicked.
  • ImageUrl – This property is used for displaying the image on button control.
  • CommandName - This property is used to get or set the command name associated to button control.
  • CommandArgument – This property is used for passing the string value to command event once user clicks on button.
109) What is a component?
Component is a group of classes and methods which are logically related. Component should implement IComponent interface or at least uses class that implemented IComponent interface.
110) How to force all the validation control to run?
Page.Validate method is used to force all the validation controls to run.

111) If client side validation is enabled in your Web page, will that mean server side code does not run?
When client side validation is enabled, server emits JavaScript code for the custom validators. But, it does not mean that server side checks on custom validators do not execute. It does this check two times as some of the validators do not support client side scripting.
112) How can I show the entire validation error message in a message box on the client side?
This can be done by setting “ShowMessageBox” to true of validation summary.
113) How to validate textbox for zero value?
Below is a code snippet for custom validator, which is checking whether a textbox have a zero value –
<asp:CustomValidator id="MyTestCustomValidator" 
runat="server"
ErrorMessage="Divided by Zero Error"
ControlToValidate=" txtTestMyNumber"
OnServerValidate="ServerValidate"
ClientValidationFunction="CheckZero" />
<asp:TextBox id="txtTestMyNumber" runat="server" />

<script language="javascript">
function CheckZero(source, args)
{
int val = parseInt(args.Value, 8);
if (val ==0)
{
args.IsValid = false;
}
}
</script>
As shown above “txtNumber” is the text box name where in value will be entered and client script “CheckZero” checking for zero value.
114) If cookies are not enabled at browser end does Form Authentication work?
No. it will not work. Form authentication wants cookies to be enabled.
Reason – First time user will send its credentials to server and user will then be authenticated and server gives a response and this will be stored in client machine mainly as cookie. But if cookies are disabled, this would not be stored. For the second time, the same user will not be authenticated.
115) How do I sign out in forms authentication?
FormsAuthentication.Signout() method is used to sign out.
116) What are design patterns?
It is recurring solution to recurring problems in software architecture.
117) Can you list down all design patterns?
Below are the list of design patterns along with their classifications -
Creational Design Pattern
  • Abstract Factory
  • Builder
  • Factory Method
  • Singleton
  • Prototype
Structural Design Patterns
  • Composite
  • Adapter
  • Flyweight
  • Proxy
  • Decorator
  • Bridge
  • Façade
Behavioral Design Patterns
  • Interpreter
  • Iterator
  • Command
  • Observer
  • Mediator
  • Template Method
  • Strategy
  • Chain of Responsibility
  • State
  • Memento
  • Visitor
118) How to customize columns in GridView?
Gridview have the ability to generate required columns automatically using BoundField. But, we can manually create column which are to be customized instead of auto generating. For customizing columns “TemplateField” will be used.
119) Can we use COM components in .Net? If so, how can we use?
Runtime Callable Wrapper” (RCW) can be used for making communication between COM components and .NET components.
This can used in following ways –
  • Create a wrapper class and put it in BIN directory.
  • Use type library importer tool - Tlbimp.exe
  • Use namespace System.Runtime.Interopservices , which gives converter (TypeLib) which has all methods which are required to convert COM classes to assembly metadata.
120) How can I show the entire validation error message in a message box on the client side?
This can be done by adding validation summary control. In Validation Summary control, there is a property “ShowMessageBox” just set it to true.
121) List down the differences between Debug and Trace in ASP.NET?
Both these methods are under namespace - System.Diagnoastics.
  • Debug – This works only when the mode is Debug.
  • Trace – This works in both Debug and Release modes.
122) What is the difference between Process and Thread?
  • Process is collection of system resources, data, code and memory space.
  • Thread is a code which is executed in process. One process can have multiple threads along with primary thread. Thread will be executed until it’s killed or higher priority thread comes for an execution. Each thread will share resources of a process in which it is running.
123) What is the difference between cache object and session object?
  • Cache – This improves the performance by minimizing the database hits to fetch the data. It instead stores the data in cache. So cache will be checked first for data and if it is not found then go to database to get the data.
  • Session – Session will be created to store the details of the user for capturing the user’s specific actions. Session will be killed or it will be expired in 20 minutes.
124) Which method is used to remove the cache object?
To remove the cache object we can use - cache.remove() method.
125) List down at least five Gridview events?

GridView Events are as below –
  • PageIndexChanging - This event will be fired when pager button is clicked and before Gridview control handles this operation.
  • PageIndexChanged - This event will be fired when pager button is clicked and after Gridview control handles this operation.
  • RowCommand - This event will be fired when any button is clicked in Gridview.
  • RowDataBound - This event will be fired when data is bounded to GridView.
  • RowCreated - This event will be fired when row is created in GridView.
  • RowDeleted - This event will be fired when row is deleted in GridView.
126) How many object are there in ASP.NET?
There are six objects are there in ASP.NET and they are following –
  • Session
  • Request
  • Response
  • Object Request
  • Server
  • Application
127) Why PDB files are useful?
PDB files are useful for debugging. PDB files contain the debug information and project information. When project is built under Debug mode PDB files are generated and it would not generate in Release mode. These files should not be included in production deployment.
128) What is ASP.NET membership?
ASP.NET membership allows you to store and validate the user credentials. Forms Authentication can be used for storing the user credentials in ASP.NET membership using login controls of ASP.NET. Membership supports storing user credentials in SQL Server , Active Directory etc.
129) How to disable Session at the Page Level?
<%@ Page language="c#" Codebehind="TestMyPage1.aspx.cs" 
AutoEventWireup="false" Inherits="WebApplication1.TestMyPage1 "
EnableSessionState="false" %>
Using “EnableSessionState” property we can disable the session at page level as shown above.
130) How we can handle SQL Exceptions in ASP.NET?
We can use try, catch and finally block for error handling. Use SqlException class to handle exceptions specific to SQL Server.
try
{
//some code
}
catch(SQLException ex)
{
//Handle SQL Exception
}
131) How to set maximum length of Textbox in ASP.NET?
Textbox maximum length can be controlled from “MaxLength” property. By default length of the textbox will be 65535.

132) How many validations can be applied on customer’s “Age” field?
Two validations can be applied for this field and they are –
  • Required – For checking mandatory value.
  • Range – For checking the age range, age should be between the ranges.
133) What is the difference between Web Services and Remoting?
Both these applications support distributed applications.
  • Remoting is used to talk in binary format and is not cross platform. It expects consumer to be .NET application. It uses SMTP, HTTP and TCP protocols for communication.
  • Web Services can be either WCF or XML Web Services. Web Services are hosted in internet and it is cross platform. Client will be created for using web service and client can consume the methods of web service.
134) Why to use web.sitemap in ASP.NET?
For using navigation controls like menu, treeview etc we have to define xmlsitemap, which is called web.sitemap.
Eg : 
<?xml version="1.0" encoding="utf-8"?>
<siteMap
xmlns=" ">
<siteMapNode url="~/Home.aspx" title="Home" description="">
<siteMapNode url="~/ About.aspx" title="About"
description=""/>
<siteMapNode url="~/ Details.aspx" title="Details"
description=""/>
<siteMapNode url="~/ Contact.aspx" title="Contact"
description="" >
<siteMapNode url="~/ Comment.aspx" title="Comment"
description=""/>
</SiteMapNode>
</SiteMapNode>
</SiteMap>
135) Is it possible to use multiple web.config files of ConnectionString in one page?
Yes. We can have multiple web.config in an application. But these web.config files should be under different folders, it should not be in same place in an application.
136) Why to use UpdatePanel control in AJAX ASP.NET?
AJAX is a client side technology and it supports asynchronous communication between client and server. If the part of page need to be refreshed, then we can use this Update panel control, which uses AJAX request and does not harm the other part of the page.
137) How can I disable the Session at page level and at the application level?
Disabling Session at page level –
<%@ Page language="c#" Codebehind="MyPageTesting1.aspx.cs" 
AutoEventWireup="false" Inherits="WebApplication1. MyPageTesting1"
EnableSessionState="false" %>
Disabling Session at application level – This can be done in Web.Config of our application in following way.
<sessionstate mode="off"> under <system.web>
138) Why to set the property – EnableViewState to true?
Purpose of view state is to persist the state across postback. “EnableViewState” property is available at control and page level. Once we set it to TRUE, viewstate for a Control/Page will be enabled.
139) Why to use “runat=server” for HTML element?

HTML elements are treated as text by default. Once we add “runat=server” attribute to HTML element, it will be treated as a server control. If we add “runat=server” attribute we have to make sure this element is in <form> tag because it indicates that form is processed by server.
140) Can we store the dataset into viewstate? If yes, how?
Yes we can store the dataset into viewstate. We have to serialize the dataset and store it into viewstate.
141) How can we convert sql2000 numeric to integer in ASP.NET?
sqlParameter objTest=new sqlParameter();
objpara=objDataadapter.UpdataCommand.Parameter.Add("@Quantity",SqlDbType.Int);
objpara.SourceColumn="Quantity";
objTest.SourceVersion=DataRowVersion.Current; 
142) What you mean by DocType in ASP.NET?
XHTML Web pages should contain DOCTYPE, which identifies the page as XHTML. ASP.NET would not create DOCTYPE declaration when it’s rendered.
143) What is meant by runtime hosts?
Runhosts are special type where CLR is managed and executed.
144) What you mean by HTTPContext?
This is in System.Web namespace,this is the best way for reading server response at runtime.
Eg: HttpContext.Current.Items.Add("ERRORMESSAGE ", exception.Message);
145) Why to use Hidden Fields in ASP.NET?
Hidden fields are best way for exchanging the data between client (browser) and server. These controls are not visible in web page but can be accessed from javascript or Jquery.
146) What is the difference between Hidden Field and Textbox with Visible=false?
Hidden Field can be accessed from javascript or Jquery, whereas Textbox with Visible = false is not accessible from javascript or Jquery.
147) How do you decide on when to go for caching?
In case in our application, we need to store large amount of data and if it is the master data (which does not change most often) then we can use caching for storing this data.

148) What is the role of CSS in web pages in ASP.NET?
Cascading Style Sheet (CSS) is used to style the pages or controls which is visible to the user. CSS can be created in .css files and can be included this in our web pages.
149) What does mean Stateless?
Stateless mean, if the entity does not remember its previous state. HTTP is stateless protocol because it does not remember its old state (request) done. For this stateless feature ASP.NET provides state management options like Session, Cookies, Viewstate etc.
150) What does partial mean in ASP.NET?
We have the option of splitting the single class file into multiple parts. Using partial keyword, we can split the logic of single class into multiple class files with the same class name. Advantage of this would be – We will end up creating only one object for the class.
151) What could be best way to handle the data more than 10k in Datagrid?
Using dataset would be a feasible solution. Dataset will again have datatables in it. It’s easy to use LINQ to Dataset to filter the data from dataset and binding it to Datagrid.
152) Explain Page.IsValid?
This property will let you know whether all validation in a page succeeded or not.
153) Is it possible to use javascript from codebehind files in ASP.NET?
Yes we can register the javascripts from codebehind files like below –
Use method - Page.RegisterStartupScript() or use Page.RegisterClientScriptBlock().
154) How to use MessageBox without javascript in ASP.NET?
Add the reference of System.Windows.Forms library then use the method –
MessageBox(“Hi Testing”);
155) How can we change the timeout of session in ASP.NET?
Basically timeout of session is 20 minutes and if we want to change this timeout we can do in following way –
  • Change the Session time out in web.config. (In sessionstate tag change the timeout)
  • Change the Session time out in code using timeout property of session class.

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.