Untitled Page

Tuesday, August 11, 2009

Difference between Custom Controls and User Controls?

1.User Control is a page file with extension .ascx which can only be used within
a single application. But custom controls are assemblies(dll files) that can be
used in multiple applications.

2.User Controls cannot be added to the ToolBox of VS.NET . To use a user Control with in an
aspx page u have to drag the user Control from the solution Explorer to designer page.
But Custom Controls can be added to ToolBox of VS.NET.

3.User Controls can be viewed as a sort of generic controls during the design time.
The proper GUI of user controls can be viewed only during the run time.
But Custom Controls can be viewed during the design time.

4. User controls are created from existing Webserver and html server controls .
But a developer who creates custom controls have to render every thing from the scratch.

5.Since the dll assembly of a custom control is being used,a custom control developed in C# can be used in a project developed in VB.NET or any other managed code and vice versa.
This is not possible with user controls.They are language spefic We cannot give any examples for custom controls since they are developed either by a developer of a third party vendor.

Wednesday, August 5, 2009

asp.net interview questions part2

Home

ASP.NET Interview Question Categories

What is the difference between login controls and Forms authentication?

* Forms authentication can be easily implemented using login controls without writing any code.
* Login control performs functions like prompting for user credentials, validating them and issuing authentication just as the FormsAuthentication class.
* However, all that’s needs to be dne is to drag and drop the use control from the tool box to have these checks performed implicitly.
* The FormsAuthentication class is used in the background for the authentication ticket and ASP.NET membership is used to validate the user credentials.

What is Fragment Caching in ASP.NET?

* Fragment caching refers to the caching of individual user controls within a Web Form.
* Each user control can have independent cache durations and implementations of how the caching behavior is to be applied.
* Fragment caching is useful when you need to cache only a subset of a page.
* Navigation bars, header, and footers are good candidates for fragment caching.

What is partial classess in .net?

When there is a need to keep the business logic separate from the User Interface or when there is some class which is big enough to have multiple number of developers implement the methods in it, the class can be separated and written in different files as partial class.

The keyword partial must appear in each class.

//syntax for C#
Public partial class MyPartialClass1
{
//code
}

// this code could be in file1

Public partial class MyPartialClass1
{
//code
}
// this code could be in file2

Explain how to pass a querystring from an .asp page to aspx page.

Consider the following URL:

http:// localhost/form.aspx?param1=career¶m2=ride

This html addresses use QueryString property to pass values between pages.

From the URL above the information obtained is:

form.aspx: which is the destination page for your browser.
Param1 is the first parameter, the value of which is set to career
Param2 is the first parameter, the value of which is set to ride

The ‘?’ marks the beginning of the QueryString
‘&’ is used as a separator between parameters.

private void formButtonSubmit_Click(object sender, System.EventArgs e)
{
Response.Redirect("form.aspx?Param1=" +
this.formTextfieldParam1.Text + "&Param2=" +
this. formTextfieldParam2.Text);
}

The above code is a submit button event handler and it sends the values of the query string to the second page.

The following code demonstrates how to retrieve these valus on the second page:
private void Page_Load(object sender, System.EventArgs e)
{
this.form2TextField1.Text = Request.QueryString["Param1"];
this. form2TextField2.Text = Request.QueryString["Param2"];
}

You can also use the following method to retrieve the parameters in the string:

for (int i =0;i < Request.QueryString.Count;i++)
{
Response.Write(Request.QueryString[i]);
}

What is a ViewState?

* If a site happens to not maintain a ViewState, then if a user has entered some information in a large form with many input fields and the page is refreshes, then the values filled up in the form are lost.
* The same situation can also occur on submitting the form. If the validations return an error, the user has to refill the form.
* Thus, submitting a form clears up all form values as the site does not maintain any state called ViewState.
* In ASP .NET, the ViewState of a form is maintained with a built-in state management technique keeps the state of the controls during subsequent postbacks by a particular user.

* The ViewState option can be disabled by including the directive <%@ Page EnableViewState="false"%> at the top of an .aspx page
* If a ViewState of a certain control has to be disabled, then set EnableViewState="false"

Advantages:

i) No server resources.
ii) Viewstate ensures security because it stores the data in encrypted format.
iii) Viewstates are simple. They are used by enabling or disabling the viewstate properties.
iv) It is based on the wish of developer that they want to implement it at the page level or at control level.

Disadvantages:

i) If large amount of data is stored on the page, then page load might cause a problem.
ii) Does not track across pages. Viewstate information does not automatically transfer from page to page.

Difference between src and Code-Behind?

With the ‘src’ attribute, the source code files are deployed and are compiled by the JIT as needed.
Though the code is available to everyone with an access to the server (NOT anyone on the web), this method is preferred as it does away with the compilation of the DLLs.

‘CodeBehind’ attribute just has the VS.NET associate the code file with the aspx file. This is necessary since VS.NET automates the pre-compiling that is harder by hand.

Due to this the ‘Src’ attribute is done away with having only a DLL to be deployed enhancing the protection level even though it can be decompiled.

What is the Pre-Compilation feature of ASP.NET 2.0?

Previously, in ASP.NET, the pages and the code used to be compiled dynamically and then cached so as to make the requests to access the page extremely efficient. In ASP.NET 2.0, the pre-compilation feature is used with which an entire site is precompiled before it is made available to users.

There is a pre-defined folder structure for enabling the pre-compilation feature:

* App_Code: stores classes
* App_Themes: stores CSS files, Images, etc.
* App_Data: stores XML files, Text Files, etc.
* App_GlobalResources: stores all the resources at global level E.g. resx files, etc
* App_LocalResources: stores all the resources at local/Page level

ASP.NET - What is the Pre-Compilation feature of ASP.NET 2.0?

It is a process where things that can be handled before compilation are prepared in order to reduce the deployment time, response time, increase safety. It’s main aim to boost performance.

It also helps in informing about the compilation failures.

During development, it allows you to make changes to the web pages and reuse it using the same web browser to validate the changes without compiling the entire website.

During deployment, it generates the entire website folder structure in the destination. All the static files are copied to the folder and bin directory would later on contain the compiled dll.

How can we create custom controls in ASP.NET?

Custom controls are user defined controls. They can be created by grouping existing controls, by deriving the control from System.Web.UI.WebControls.WebControl or by enhancing the functionality of any other custom control. Custom controls are complied into DLL’s and thus can be referenced by as any other web server control.

Basic steps to create a Custom control:

1. Create Control Library
2. Write the appropriate code
3. Compile the control library
4. Copy to the DLL of the control library to the project where this control needs to be used
5. The custom control can then be registered on the webpage as any user control through the @Register tag.

Explain the steps to create a web services and consume it?

Steps to create and consume a webservice

Creation:

* a. Create a new website by selecting "ASP.NET Web Site" and giving it a suitable name.
* b. service.cs file appears inside the solution with a default webmethod named as "HelloWorld()"
* c. Right click on the webservice project and add a web reference instead of adding a normal reference.
* d. A window appears that displays a list of webservices knows to the solution.
* e. Click on "Webservices in this solution"
* f. a search progress bar appears and
* g. Select the service that appears in the list
* h. progress bar appears once again.
* i. web method appears on the screen
* j. Click on "Add reference" button. This would add localhost
* k. solution would have App_WebReference folder

Consumption or Usage:

* a. Add a UI (.aspx) to the webservice project
* b. Add a button and a label to the form
* c. Double click the button to see the click event of the button
* d. Create an object of type service localhost.serviceName
* e. Write code to display the value returned by the webmethod on the label
* f. Execute the solution by setting the added aspx as the startpage.
* g. click on the button and the message "Hello World" would be displayed on the label

What is Cache Callback in Cache?

The cache object has dependencies e.g. relationships to the file it stores. Cache items remove the object when these dependencies change. As a work around we would need to simply execute a callback method whenever items are removed from the cache to add the items back in cache.

e.g.: We have a string variable string var="hello" and store it in cache. This item would be removed from the cache if value is changed from "hello" to "bye". In such a case we need to simply right a callback function which would add updated var back in cache as it’s been removed as a result of its dependencies changing.

Explain the types of Caching using Cache object of ASP.NET?

* Page output: Is used to fetch information or data at page level. It is best used when the site is mainly static. Used by declaring the output page directive
* Page fragment: Is used to cache the structure level information. It is used when parts of pages change. For example: user control
* Programmatic or data: Is used to fetch the information of an application quickly based on the requirements.

What is SQL Cache Dependency in ASP.NET?

SQL Cache Dependency in ASP.NET: It is the mechanism where the cache object gets invalidated when the related data or the related resource is modified. It is a feature in SQL Server 2005 and SQL Server 2000.

3 types of SQL-cache dependencies exist:

a. Other cache items.
b. Files/folders.
c. Dependencies on a database query.



Home

ASP.NET Interview Question Categories

Tuesday, August 4, 2009

what is global.asax?

The Global.asax file, which is derived from the HttpApplication class, maintains a pool
of HttpApplication objects, and assigns them to applications as needed. The Global.asax
file contains the following events:
Application_Init: Fired when an application initializes or is first called. It is invoked for
all HttpApplication object instances.
Application_Disposed: Fired just before an application is destroyed. This is the ideal
location for cleaning up previously used resources.
Application_Error: Fired when an unhandled exception is encountered within the
application.
Application_Start: Fired when the first instance of the HttpApplication class is created.
It allows you to create objects that are accessible by all HttpApplication instances.
Application_End: Fired when the last instance of an HttpApplication class is destroyed.
It is fired only once during an application's lifetime.
Application_BeginRequest: Fired when an application request is received. It is the first
event fired for a request, which is often a page request (URL) that a user enters.
Application_EndRequest: The last event fired for an application request.
Application_PreRequestHandlerExecute: Fired before the ASP.NET page framework
begins executing an event handler like a page or Web service.
Application_PostRequestHandlerExecute: Fired when the ASP.NET page framework has
finished executing an event handler.
Applcation_PreSendRequestHeaders: Fired before the ASP.NET page framework sends
HTTP headers to a requesting client (browser).
Application_PreSendContent: Fired before the ASP.NET page framework send content
to a requesting client (browser).
Application_AcquireRequestState: Fired when the ASP.NET page framework gets the
current state (Session state) related to the current request.
Application_ReleaseRequestState: Fired when the ASP.NET page framework completes
execution of all event handlers. This results in all state modules to save their current state
data.
Application_ResolveRequestCache: Fired when the ASP.NET page framework completes
an authorization request. It allows caching modules to serve the request from the cache,
thus bypassing handler execution.
Application_UpdateRequestCache: Fired when the ASP.NET page framework completes
handler execution to allow caching modules to store responses to be used to handle
subsequent requests.
Application_AuthenticateRequest: Fired when the security module has established the
current user's identity as valid. At this point, the user's credentials have been validated.
Application_AuthorizeRequest: Fired when the security module has verified that a user
can access resources.
Session_Start: Fired when a new user visits the application Web site.
Session_End: Fired when a user's session times out, ends, or they leave the application Web site.

Note :- During interview you do not have to really cram all these events. But just keep the basic events in mind

What order they are triggered ?
They're triggered in the following order:
Application_BeginRequest
Application_AuthenticateRequest
Application_AuthorizeRequest
Application_ResolveRequestCache
Application_AcquireRequestState
236
Application_PreRequestHandlerExecute
Application_PreSendRequestHeaders
Application_PreSendRequestContent
<>
Application_PostRequestHandlerExecute
Application_ReleaseRequestState
Application_UpdateRequestCache
Application_EndRequest.

asp.net interview questions on gridview

Home

ASP.NET Interview Question Categories

What is DataGrid...

We can define DataGrid as a Powerfull WebServer tool which is used for displaying information from a DataSource in a tabular form an enables us to perform Sorting, Paging and Editing by setting a few properties and creating a couple of event handlers.

How Web DataGrid is Different from Windows DataGrid Control...


The WebPage DataGrid control is Different from Windows DataGrid in entire programming paradigm. Let's see...

* Web DataGrid Control performs a round trip to the server.
* Web DataGrid manage State.
* Windows DataGrid Control Supports master-detail data structure while web Datagrid doesn't.
* In Web DataGrid ,you can Edit only one row at a time.
* Web DataGrid Does not inherently support sorting, but raises events while Windows DataGrid does support.
* Web DataGrid supports Paging.
* You can bind Web DataGrid Control to any object that supports the IEnumerable interface.

How do you bind data in the DataGrid?

Binding Data in DataGrid means how we show the data from a table or a relation in our DataGrid.

Suppose We want to show the data of "Customers" table of "Northwind" database present in SQL Server on the Button Click. Now Follow the given steps....

step 1: Drag a DataGrid and a Button control on the Page.
step 2: In the Code behind Use the namespace as
using System.Data.SqlClient;
step 3: Write the following code in the Button's Click event handler...

protected void Button1_Click(object sender,EventArgs e)
{
SqlConnection con=new SqlConnection ("server=rajkumar;uid=sa;pwd=kumar;database=northwind) ;
SqlDataAdapter da_show=new SqlDataAdapter (" select ProductName, UnitPrice, UnitsInStock from Products", con);
DataSet ds=new DataSet;
da_show.Fill(ds, "Products");
GridView1.DataSource=ds.Tables["products"];
GridView1.DataBind( );
}

This will show all the rows and selected column in the DataGrid. The Column names in the DataGrid will be same as attributes name in the database table.

How do you customize the DataGrid...

Here I will show you how to Display only Selected Column in the DataGrid even when you selected all the columns in your Query in Code Behind file. Also I will show you how to change the Name of the Column in the DataGrid.

Suppose I want to Display only ProductName and UnitPrice from the table and Also Want To display ProductName as Product Name and UnitPrice as Price......So

Step 1 : In the Code behind file the code will be same as above.
Step 2 : Set the Property AutoGenerateColumns of DataGrid to false.
Step 3 : Go to source View and Insert TemplateColumns in the datagrid tag.

You code should be like this....





<%# DataBinder.Eval(Container.DataItem,"productname") %>




<%# DataBinder.Eval(Container.DataItem, "UnitPrice")%>



Difference between Datagrid, Datalist and repeater ?

A Datagrid, Datalist and Repeater are all ASP.NET data Web controls.
They have many things in common like DataSource Property, DataBind Method
ItemDataBound and ItemCreated.
When you assign the DataSource Property of a Datagrid to a DataSet then each DataRow
present in the DataRow Collection of DataTable 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 Datagrid has an HTML TABLE element created for the particular DataRow and its a Table form representation with Columns and Rows.
For a Datalist its an Array of Rows and based on the Template Selected and the
RepeatColumn Property value We can specify how many DataSource records should
appear per HTML row. In short in datagrid we have one record per row, but in
datalist we can have five or six rows per row.
For a Repeater Control, the Datarecords to be displayed depends upon the Templates
specified and the only HTML generated is the due to the Templates.
In addition to these, Datagrid has a in-built support for Sort, Filter and paging the Data, which is not possible when using a DataList and for a Repeater Control we would require to write an explicit code to do paging.

-----------------------------------------------------------------------------

Differences between Datagrid, Datalist and Repeater?
1. Datagrid has paging while Datalist doesnt.
2. Datalist has a property called repeat. Direction = vertical/horizontal. (This is of great help in designing layouts). This is not there in Datagrid.
3. A repeater is used when more intimate control over html generation is required.
4. When only checkboxes/radiobuttons are repeatedly served then a checkboxlist or radiobuttonlist are used as they involve fewer overheads than a Datagrid.
The Repeater repeats a chunk of HTML you write, it has the least functionality of the three. DataList is the next step up from a Repeater; accept you have very little control over the HTML that the control renders. DataList is the first of the three controls that allow you Repeat-Columns horizontally or vertically. Finally, the DataGrid is the motherload. However, instead of working on a row-by-row basis, you’re working on a column-by-column basis. DataGrid caters to sorting and has basic paging for your disposal. Again you have little contro, over the HTML. NOTE: DataList and DataGrid both render as HTML tables by default.
Out of the 3 controls, I use the Repeater the most due to its flexibility w/ HTML. Creating a Pagination scheme isn't that hard, so I rarely if ever use a DataGrid. Occasionally I like using a DataList because it allows me to easily list out my records in rows of three for instance.

-----------------------------------------------------------------------

Datagrid is most restrictive as regards to customization followed by DataList and finally Repeater is the most customizable.

Datagrid has built in paging sorting and editing capabilities which are not there with the other two controls. So if you want users to sort / page / edit data datagrid is the natural choice.

DataList and repeater have better performance than datagrid. So if performance is a major concern for example a site with large number of concurrent visitors then you could think of datalist or repeater.

Repeater is the most customizable. It allows you to create structures like nested lists for example.

A datagrid row displays one record from the data source while a datalist row can display more than one records (set by RepeatColumns property)

Datagrid and Datalist are derived from WebControl while Repeater is not and so does not have the stylistic properties of web controls.

All are similar in that they have a datasource property and ItemCreated ItemDataBound and ItemCommand events.

How to decide on the design consideration to take a Datagrid, datalist or repeater ?
Many make a blind choice of choosing datagrid directly, but that's not the right way.
Datagrid provides ability to allow the end-user to sort, page, and edit its data. But it
comes at a cost of speed. Second the display format is simple that is in row and columns.
Real life scenarios can be more demanding that
With its templates, the DataList provides more control over the look and feel of the
displayed data than the DataGrid. It offers better performance than datagrid
Repeater control allows for complete and total control. With the 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 the DataGrid and DataList. By requiring the developer to specify the complete generated HTML markup, the Repeater often requires the longest development time. But repeater does not provide editing features like datagrid so everything has to be coded by programmer.
However, the Repeater does boast the best performance of the three data Web controls.
Repeater is fastest followed by Datalist and finally datagrid.

asp.net interview questions

Home

ASP.NET Interview Question Categories

What’ is the sequence in which ASP.NET events are processed ?
Following is the sequence in which the events occur :-
√ Page_Init.
√ Page_Load.
√ Control events
√ Page_Unload event.
Page_init event only occurs when first time the page is started, but Page_Load occurs in subsequent request of the page.

In which event are the controls fully loaded ?
Page_load event guarantees that all controls are fully loaded. Controls are also accessed in Page_Init events but you will see that viewstate is not fully loaded during this event.
How can we identify that the Page is PostBack ?
Page object has a “IsPostBack” property which can be checked to know that is the page
posted back.
How does ASP.NET maintain state in between
subsequent request ?

Refer caching chapter.
What is event bubbling ?
Server controls like Datagrid, DataList, Repeater can have other child controls inside them. Example DataGrid can have combo box inside datagrid. These child control do not raise there events by themselves, rather they pass the event to the container parent (which can be a datagrid, datalist, repeater), which passed to the page as “ItemCommand” event. As the child control send there events to parent this is termed as event bubbling.

How do we assign page specific attributes ?
Page attributes are specified using the @Page directive.
(A) Administrator wants to make a security check that no
one has tampered with ViewState, how can he ensure this ?
Using the @Page directive EnableViewStateMac to True.
(B) What is the use of @ Register directives ?
@Register directive informs the compiler of any custom server control added to the
page.
(B) What’s the use of SmartNavigation property ?
It’s a feature provided by ASP.NET to prevent flickering and redrawing when the page is
posted back.
Note:- This is only supported for IE browser. Project’s who have browser compatibility as
requirements have to think some other ways of avoiding flickering.
What is AppSetting Section in “Web.Config” file ?
Web.config file defines configuration for a webproject. Using “AppSetting” section we
can define user defined values. Example below defined is “ConnectionString” section
which will be used through out the project for database connection.




Where is ViewState information stored ?
In HTML Hidden Fields.

What is the use of @ OutputCache directive in ASP.NET?

It is basically used for caching. See more for Caching chapter.


Can you explain what is “AutoPostBack” feature in
ASP.NET ?

If we want the control to automatically postback in case of any event, we will need to check this attribute as true. Example on a ComboBox change we need to send the event immediately to the server side then set the “AutoPostBack” attribute to true.
How can you enable automatic paging in DataGrid ?
Following are the points to be done in order to enable paging in Datagrid :-
√ Set the “AllowPaging” to true.
√ In PageIndexChanged event set the current pageindex clicked.
Note:- The answers are very short, if you have implemented practically its just a revision. If you are fresher just make sample code using Datagrid and try to implement this functionality.
What’s the use of “GLOBAL.ASAX” file ?
It allows to executing ASP.NET application level events and setting application-level
variables.
What is the difference between “Web.config” and “Machine.Config” ?
“Web.config” files apply settings to each web application, while “Machine.config” file
apply settings to all ASP.NET applications.
What is a SESSION and APPLICATION object ?
Session object store information between HTTP requests for a particular user, while
application object are global across users.
What is the difference between Server.Transfer and response.Redirect ?
Following are the major differences between them:-
√ Response.Redirect sends message to the browser saying it to move to some
different page, while server.transfer does not send any message to the browser
but rather redirects the user directly from the server itself. So in server.transfer
there is no round trip while response.redirect has a round trip and hence puts
a load on server.
√ Using Server.Transfer you can not redirect to a different from the server itself.
Example if your server is www.yahoo.com you can use server.transfer to move
to www.microsoft.com but yes you can move to www.yahoo.com/travels, i.e.
within websites. This cross server redirect is possible only using
Response.redirect.
√ With server.transfer you can preserve your information. It has a parameter
called as “preserveForm”. So the existing query string etc. will be able in the
calling page. In response.redirect you can maintain the state, but has
lot of drawbacks.
If you are navigating within the same website use “Server.transfer” or else go for
“response.redirect()”
What is the difference between Authentication and authorization?

This can be a tricky question. These two concepts seem altogether similar but there is wide range of difference. Authentication is verifying the identity of a user and authorization is process where we check does this identity have access rights to the system. In short we can say the following authentication is the process of obtaining some sort of credentials from the users and using those credentials to verify the user’s identity. Authorization is the process of allowing an authenticated user access to resources. Authentication always proceed to Authorization; even if your application lets anonymous users connect and use the application, it still authenticates them as being anonymous.

What is impersonation in ASP.NET ?
By default, ASP.NET executes in the security context of a restricted user account on the local machine. Sometimes you need to access network resources such as a file on a shared drive, which requires additional permissions. One way to overcome this restriction is to use impersonation. With impersonation, ASP.NET can execute the request using the identity of the client who is making the request, or ASP.NET can impersonate a specific account you specify in web.config.
Can you explain in brief how the ASP.NET authentication process works?
ASP.NET does not run by itself, it runs inside the process of IIS. So there are two
authentication layers which exist in ASP.NET system. First authentication happens at
the IIS level and then at the ASP.NET level depending on the WEB.CONFIG file.
Below is how the whole process works:-
√ IIS first checks to make sure the incoming request comes from an IP address
that is allowed access to the domain. If not it denies the request.
√ Next IIS performs its own user authentication if it is configured to do so. By
default IIS allows anonymous access, so requests are automatically
authenticated, but you can change this default on a per – application basis
with in IIS.
√ If the request is passed to ASP.net with an authenticated user, ASP.net checks
to see whether impersonation is enabled. If impersonation is enabled, ASP.net
acts as though it were the authenticated user. If not ASP.net acts with its own
configured account.
√ Finally the identity from step 3 is used to request resources from the operating
system. If ASP.net authentication can obtain all the necessary resources it
grants the users request otherwise it is denied. Resources can include much
more than just the ASP.net page itself you can also use .Net’s code access
security features to extend this authorization step to disk files, Registry keys
and other resources.
What are the various ways of authentication techniques
in ASP.NET?

Selecting an authentication provider is as simple as making an entry in the web.config file for the application. You can use one of these entries to select the corresponding built in authentication provider:
√
√
√
√ Custom authentication where you might install an ISAPI filter in IIS that
compares incoming requests to list of source IP addresses, and considers
requests to be authenticated if they come from an acceptable address. In that
case, you would set the authentication mode to none to prevent any of the
.net authentication providers from being triggered.

Monday, August 3, 2009

ASP.NET Interview Questions on Globalization

Home

ASP.NET Interview Question Categories

What is Globalization?
Globalization is the process of creating an application that meets the needs of users from multiple cultures. This process involves translating the user interface elements of an application into multiple languages, using the correct currency, date and time format, calendar, writing direction, sorting rules, and other issues. Accommodating these cultural differences in an application is called localization.

The Microsoft .NET Framework simplifies localization tasks substantially by making its formatting, date/time, sorting, and other classes culturally aware. Using classes from the System.Globalization namespace, you can set the application’s current culture, and much of the work is done automatically!

What are the 3 different ways to globalize web applications?

Detect and redirect approach : In this approach we create a separate Web application for each supported culture, and then detect the user’s culture and redirect the request to the appropriate application. This approach is best for applications with lots of text content that requires translation and few executable components.

Run-time adjustment approach : In this approach we create a single Web application that detects the user’s culture and adjusts output at run time using format specifiers and other tools. This approach is best for simple applications that present limited amounts of content.

Satellite assemblies approach : In this approach we create a single Web application that stores culture-dependent strings in resource files that are compiled into satellite assemblies. At run time, detect the user’s culture and load strings from the appropriate assembly. This approach is best for applications that generate content at run time or that have large executable components.

In ASP.NET, how do you detect the user's language preference on his/her computer?
Use the Request object’s UserLanguages property to return a list of the user’s language preferences. The first element of the array returned by UserLanguages is the user’s current language on his/her computer.

What are the steps to follow to get user's culture at run time?
To get the user’s culture at run time, follow these steps:
1. Get the Request object’s UserLanguages property.
2. Use the returned value with the CultureInfo class to create an object representing the user’s current culture.

For example, the following code gets the user’s culture and displays the English name and the abbreviated name of the culture in a label the first time the page is displayed:
private void Page_Load(object sender, System.EventArgs e)
{
// Run the first time the page is displayed
if (!IsPostBack)
{
// Get the user's preferred language.
string sLang = Request.UserLanguages[0];
// Create a CultureInfo object from it.
CultureInfo CurrentCulture = new CultureInfo(sLang);
lblCulture.Text = CurrentCulture.EnglishName + ": " +
CurrentCulture.Name;
}
}

What are the advantages of using detect and redirect approach to globalizing web applications?
1. Content is maintained separately, so this approach allows the different applications to present very different information, if needed.
2. Users can be automatically directed to sites that are likely to be geographically close, and so can better meet their needs.
3. Content files (Web forms and HTML pages, for example) can be authored in the appropriate natural language without the complexity of including resource strings.

What are the disadvantages of using detect and redirect approach to globalizing web applications?
1. Using this approach requires that the executable portion of the Web application be compiled and deployed separately to each culture-specific Web site.
2. This approach requires more effort to maintain consistency and to debug problems across Web sites.

What is the use of culture attribute of the globalization element in web.config?
The Web.config file’s globalization element is used to create a culture-specific Web application. The culture attribute of the globalization element specifies how the Web application deals with various culture-dependent issues, such as dates, currency, and number formatting.

Web.config globalization settings in subordinate folders override the globalization settings in the application’s root Web.config file. You can store content for various cultures in subfolders within your application, add Web.config files with the globalization settings for each culture, then direct users to the appropriate folder based on the user’s CurrentCulture.

The text on the webform is usually written from left to right. How do you change the writing direction to "right to left"?
The wrting direction of a webform can be changed using the HTML dir attribute as shown below.


You can use the dir attribute individually in panels, text boxes, or other controls as well. Setting the dir attribute on the body element applies right-to-left formatting to the entire page.

What do you mean by neutral cultures?
Neutral cultures represent general languages, such as English or Spanish, rather than a specific language and region. When you set the culture attribute for a Web application in Web.config, ASP.NET assigns that culture to all the threads running for that Web application. Threads are the basic unit to which the server allocates processor time. ASP.NET maintains multiple threads for a Web application within the aspnet_wp.exe worker process.

What are advantages of setting the culture dynamically at the thread level over creating separate Web applications for each culture?
1. All cultures share the same application code, so the application doesn’t have to be compiled and deployed for each culture.
2. The application resides at a single Web address, you don’t need to redirect users to other Web applications.
3. The user can choose from a full array of available cultures.

For what type of web applications setting the culture dynamically is best suited?
Setting the culture dynamically is best suited for simple Web applications that don’t contain large amounts of text that must be translated into different languages.

Home

ASP.NET Interview Question Categories

Application build related ASP.NET interview questions

Home

ASP.NET Interview Question Categories

What are the 2 build options for an ASP.NET web application?
1. Debug
2. Release

What are the 3 levels at which we can have a configuration file for an ASP.NET web application?
1. At the web server level : The Machine.config file located in the Windows\Microsoft.NET\Framework\version\config directory. This sets the base configuration for all .NET assemblies running on the server.
2. At the application or web site level : The Web.config file located in the IIS root directory.This sets the base configuration for all Web applications and overrides settings in Machine.config.
3. In the sub directory of an application root folder : These settings override the settings in the root folder's web.config file.

What happens when you make changes to an application’s Web.config file?
When you make changes to an application’s Web.config file, IIS automatically restarts the application and applies the changes. This has the side effect of resetting current Application or Session state variables, which can adversely affect users.

What happens when you access the Web.config file from a browser?
For security
reasons, you can’t access the Web.config file from a browser. If a user requests the Web.config file from your Web site, he or she will receive an "This type of page is not served" error message.

What happens when you access the Global.asax file from a browser?
For security reasons, you can’t access the Global.asax file from a browser. If a user requests the Global.asax file from your Web site, he or she will receive an "This type of page is not served" error message.

What are the steps to follow to host a web application on a web server?
1. Use IIS to set up a virtual folder for the application.
2. Copy the Web application to the virtual directory.
3. Add any shared .NET components to the server’s global assembly cache (GAC).
4. Set the security permissions on the server to allow the application to access required resources.

What are the 2 components that should be installed on a web server where, the ASP.NET web application runs?

ASP.NET Web applications run under IIS, so both IIS and the Microsoft .NET Framework must be installed on the server before that server can host Web applications.

What is the purpose of default start page in IIS?
A default page enables IIS to display a page if the user does not specify one in his or her request. For example, a user might make a request using only your domain name, such as http://www.venkataspinterview.blogspot.com/. If a default page is enabled, IIS will respond with http://www.venkataspinterview.blogspot.com/default.aspx.

Don’t confuse IIS default pages with the Web Forms application start page in Visual Studio .NET. Visual Studio .NET requires that you set a start page for each project so that the development environment knows which page to display first during debugging. This setting has no effect on the IIS default page settings.

How do you copy the COM component to the server and register?
COM components generally provide a setup program to install or remove them from the system. If the component doesn’t provide a setup program, you can copy it to the server and register it using the MFC RegSvr32.exe utility, as shown below:
RegSvr32 MyComname.dll

What is GAC?
GAC stands for Global Assembly Cache. The global assembly cache (GAC) is a special subfolder within the Windows folder that stores the shared .NET components.

What is the difference between weak-named .NET components and strong-named .NET components?
This difference is how the names are stored within the assembly. Weak names are not guaranteed to be unique and thus cannot be shared without potentially causing conflicts. Strong names are digitally signed and provide a public key that ensures there are no conflicts. Furthermore, .NET components with strong names can’t call unmanaged code (such as COM components) and thus avoid potential conflicts with dependencies.

Weak-named .NET components must be individually copied to the /bin directories of the Web applications where they are used. Strong-named .NET components can be copied into the server’s GAC

What is the account under which the ASP.NET worker process run?
By default, the ASP.NET worker process runs using the ASPNET account, which is created when you install the .NET Framework. This account has limited privileges, which can cause permission-denied errors if your application writes files or tries to read files outside the current Web application’s boundaries.

What are the 3 ways in which you can modify the additional permissions required by your application.?
1. Grant the ASPNET user access to the required files. To use this option, the server must be using the Windows NT file system (NTFS).
2. Change the group the ASPNET user belongs to.
3. Use impersonation to run the process as another user.

Why is it not a good idea to add ASPNET user to the Administrators group?
Adding the ASPNET user to the Administrators group gives your Web application full privileges on the server; however, it also poses a potential security risk because outside users might be able to manipulate your application to hack your server.

How do you impersonate the ASP.NET worker process?

To use impersonation to run the ASP.NET worker process as a user other than ASPNET, set the identity element’s impersonation attribute in the application’s Web.config file.

Home

ASP.NET Interview Question Categories

XML Interview Questions - Validating XML documents

Home

ASP.NET Interview Question Categories

What determines the validity of an XML document?
Document Type Definition(DTD) or an XML Schema determines the validity of an XML document.

What is a valid XML document?
XML documents are compared to rules that are specified in a DTD or schema. A well-formed XML document that meets all of the requirements of one or more specifications is called a valid XML Document.

What are the 2 types of XML parsers?
Nonvalidating Parsers - Parsers that don’t support validation
Validating Parsers - Parsers that support validation

Can you combine both Schema and DTD references in a single XML document?
Yes

Are DTD's well-formed XML documents?
No, DTDs are not well-formed XML documents. This is because they follow DTD syntax rules rather than XML document syntax.

Are XML schema's well-formed XML documents?

Yes.

What is the difference between an XML schema and a DTD?
The XML Schema is the officially sanctioned Schema definition. Unlike DTDs, the format of XML Schemas follows the rules of well-formed XML documents. The Schema also allows for much more granular control over the data that is being described. Because of the XML format and the detailed format controls, Schemas tend to be very complex and often much longer than the XML documents that they are describing. Schemas are often much more easy for developers to read and follow,due to the less cryptic nature of the references in Schemas versus DTDs.

How do you define references to schemas in an XML document?
References to schemas are defined by creating an instance of the XMLSchemainstance namespace. An example is shown below.


The namespace declaration reference to http://www.w3.org/2001/XMLSchemainstance resolves to an actual document at that location, which is a brief description of the way that the W3C Schema should be referenced. The noNamespaceSchemaLocation value tells us that there is no predefined namespace for the Schema. This means that all of the elements in the XML document should be validated against the schema specified. The location of the Schema is schemafile.xsd. Because there is no path defined, the file containing the schema should be located in the same directory as the XML file to be validated by the Schema.

You can also define the schema location, and map it to a specific namespace by using the schemaLocation attribute declaration instead of noNamespace SchemaLocation. If you do so, you have to declare a namespace that matches the schemaLocation attribute value. The declaration must be made before you reference the schema in a schemaLocation attribute assignment.

Home

ASP.NET Interview Question Categories

Techniques to send data from one web form to another web form

Home

ASP.NET Interview Question Categories
What are the different techniques to send data from one web form to another web form?
1. Query strings :
Use these strings to pass information between requests and responses as part of the Web address. Query strings are visible to the user, so they should not contain secure information such as passwords.

2. Cookies :
Use cookies to store small amounts of information on a client. Clients might refuse cookies, so your code has to anticipate that possibility.

3. Session state :
Use Session state variables to store items that you want keep local to the current session (single user).

4. Application state :
Use Application state variables to store items that you want be available to all users of the application.

Home

ASP.NET Interview Question Categories

Web application maintainance related ASP.NET Interview Questions

Home

ASP.NET Interview Question Categories

Why is it important to monitor a deployed a Web application?
After you have deployed a Web application, you need to monitor how it performs on the server. Many issues can crop up at this point because of
1. The number of users accessing the application.
2. The unpredictable nature of user interaction.
3. The possibility of malicious attack.

What are the 3 major steps invloved in maintaining a deployed web application?

Maintaining a deployed application is an ongoing task that involves three major steps:
1. Monitoring the application for error, performance, and security issues.
2. Repairing the application as issues are discovered.
3. Tuning the application to respond to user traffic.

What are the MMC snap-ins provided by windows for monitoring security, performance, and error events?
The Event Viewer snap-in : Lists application, system, and security events as they occur on the system. Use this tool to see what is currently happening on the server and to get specific information about a particular event.
The Performance snap-in : Lets you create new events to display in the Event Viewer and allows you to track event counters over time for display graphically or in report form.

How do run the Event Viewer to view application, system, and security events as they happen?
To run the Event Viewer, choose Event Viewer from the Administrative Tools submenu on the Windows Start menu. (You can show the Administrative Tools menu in Windows XP Professional by opening the Start button’s Properties dialog box and clicking the Customize button on the Start Menu tab. The Administrative Tools option is located on the Advanced tab of the Customize Start Menu dialog box.) After clicking the Event Viewer shortcut, Windows displays the Event Viewer snap-in in the MMC.

What are the 3 levels at which the Event Viewer snap-in displays general application, system, and security events?
1. Informational events.
2. Warning events.
3. Error events.

Can you repair a deployed web application in place without restarting the server or IIS?
Yes, to repair a deployed Web application, copy the new assembly (.dll) and/or content files (.aspx, .ascx, and so on) to the application folder on the server. ASP.NET automatically restarts the application when you replace the assembly. You do not need to install or register the assembly on the server.

What is ASP.NET Process recycling?

ASP.NET Web applications have a limited ability to repair themselves through process recycling. Process recycling is the technique of shutting down and restarting an ASP.NET worker process (aspnet_wp.exe) that has become inactive or is consuming excessive resources. You can control how ASP.NET processes are recycled through attributes in the processModel element in the Machine.config file.

Describes the processModel attributes found in machine.config that relate to process recycling?

1. timeout attribute :The amount of time (hh:mm:ss) before the process is shut down and restarted. Use this setting to automatically recycle a process after a certain number of requests as a preventive measure.
2. shutDownTimeOut attribute : How much time each process has to shut itself down. After this amount of time, the process is terminated by the system if it still running.
3. requestLimit attribute : The number of queued requests to serve before the process is shut down and restarted. Use this setting the same way you use the timeout attribute.
4. restartQueueLimit attribute : The number of queued requests to retain while the process is shut down and restarted.
5. memoryLimit attribute : The percentage of physical memory the ASP.NET process is allowed to consume before that process is shut down and a new process is started. This setting helps prevent memory leaks from degrading the server.
6. responseRestart­ - DeadlockInterval : The amount of time to wait before restarting a process that was shut down because it was deadlocked. This setting is usually several minutes to prevent applications with serious errors from degrading the server.
7. responseDeadlockInterval : The amount of time to wait before restarting a process that is deadlocked. The process is restarted if there are queued requests and the process has not responded within this time limit.

What is the use of processModel element apart from providing process recycling?
The processModel element in the server’s Machine.config file provides attributes that control certain performance aspects, such as
1. The maximum number of requests to be queued.
2. How long to wait before checking whether a client is connected.
3. How many threads to allow per processor.

Describe the processModel attributes that relate to performance tuning?
requestQueueLimit
The number of queued requests allowed before ASP.NET returns response code 503 (Server too busy) to new requests
clientConnectedCheck
The amount of time (hh:mm:ss) to wait before checking whether a client is still connected
maxWorkerThreads
The maximum number of threads per processor
maxIOThreads
The maximum number of I/O threads per processor

In general, lowering these settings allows your server to handle fewer clients more quickly. Increasing these settings permits more clients and more queued requests, but slows response times.

How do you turn off Session state?
To turn off Session state, in the application’s Web.config file, set the sessionState element’s mode attribute to Off.

If you turn of Session State, can you use Session state variables in code anywhere in the application?
No

What is Optimization?
Optimization usually refers to writing code in a way that executes more quickly or consumes fewer resources. In general, optimizations simply reflect the good programming practices.

List some of the common steps to follow to optimize a web application for performance?

Turn off debugging for deployed applications.
Code that has been compiled with release options runs faster than code compiled with debug options.
Avoid round-trips between the client and server.
ASP.NET uses postbacks to process server events on a page. Try to design Web forms so that the data on the Web form is complete before the user posts the data to the server. You can use the validation controls to ensure that data is complete on the client side before the page is submitted.
Turn off Session state if it isn’t needed.
In some cases, you can design your code to use other techniques, such as cookies, to store client data.
Turn off ViewState for server controls that do not need to retain their values.
Saving ViewState information adds to the amount of data that must be transmitted back to the server with each request.
Use stored procedures with databases.
Stored procedures execute more quickly than ad hoc queries.
Use SqlDataReader rather than data sets for read-forward data retrieval.
Using SqlDataReader is faster and consumes less memory than creating a data set.

Home

ASP.NET Interview Question Categories

ASP.NET Events related Interview Questions

Home

ASP.NET Interview Question Categories

What are the different levels at which events can occur in an ASP.NET web application?
Web application events occur at the application, page, and server control levels

Give some examples for application level events?
1. Application_Start
Occurs when the first user visits a page within your Web application.

2. Application_End
Occurs when there are no more users of the application.

3. Application_BeginRequest
Occurs when at the beginning of each request to the server. A request happens every time a browser navigates to any of the pages in the application.

4. Application_EndRequest
Occurs when at the end of each request to the server.

5. Session_Start
Occurs when a new user visits a page within your application.

6. Session_End
Occurs when a user stops requesting pages from the Web application and their session times out. Sessions time out after a period specified in the Web.config file.

7. Application_Error
Occurs when when there is an unhandled exception in an application.

Where are the application level event handlers present in an ASP.NET web application?
Application level event handlers are present in Global.asax of an ASP.NET web application

What is the difference between Application and Session Events?
At an application level we can have Application and Session events. Use Application events to initialize objects and data that you want to make available to all the current sessions of your Web application. Use Session events to initialize data that you want to keep throughout individual sessions, but that you don’t want to share between sessions.

Give an example of how to use Application and Session events?

To see how Application and Session events occur, add the following code to the Global.asax file in a Web forms project.
void Application_Start(object sender, EventArgs e)
{
// Create Application state variables.
Application["AppCount"] = 0;
Application["SessCount"] = 0;
// Record application start.
Application["AppCount"] = (int)Application["AppCount"] + 1;
}
void Session_Start(object sender, EventArgs e)
{
// Count sessions.
Application["SessCount"] = (int)Application["SessCount"] + 1;
}
void Session_End(object sender, EventArgs e)
{
// Decrement sessions.
Application["SessCount"] = (int)Application["SessCount"] - 1;
}

Add the following code to WebForm1.aspx file in a Web forms project and set WebForm1 as start up page.
protected void Page_Load(object sender, EventArgs e)
{
// Display Application count.
Response.Write("Number of applications: " +
Application["AppCount"] + "
");
// Display session count.
Response.Write("Number of sessions: " +
Application["SessCount"] + "
");
}
To demonstrate the events, run the preceding code, and then start a new instance of the browser and navigate to the address. Each new instance of the browser increments the session count, but the application count stays at 1.

How long a webform instance is available on the web server?
Web forms live for barely a moment. When we request a webform from the browser, the applications executable creates an instance of the requested Web form, generates the HTML to respond to the request, and posts that response to the browser. It then destroys the instance of the Web form.

When the client browser has the generated HTML, the user can type text in boxes, select options, and perform other tasks until triggering a postback event, such as a button click. Postback events cause the browser to send the page’s data (view state) back to the server for event processing. When the server receives the view state, it creates a new instance of the Web form, fills in the data from the view state, and processes any events that occurred. As soon as the server has finished, it posts the resulting HTML back to the browser and destroys the instance of the Web form.

Give some examples for page level events and when they occur?
1. Page_Init
During Page_Init the server controls are loaded and initialized from the Web form’s view state. This is the first step in a Web form’s life cycle.

2. Page_Load
During Page_Load the server controls are loaded in the Page object. View state information is available at this point, so this is where you put code to change control settings or display text on the page.

3. Page_PreRender
During Page_PreRender the application is about to render the Page object.

4. Page_Unload
During Page_Unload the page is unloaded from memory.

5. Page_Disposed
During Page_Disposed the Page object is released from memory. This is the last event in the life of a Page object.

6. Page_Error
Page_Error event is raised when an unhandled exception occurs.

7. Page_AbortTransaction
Page_AbortTransaction is raised when a transaction is aborted.

8. Page_CommitTransaction
Page_CommitTransaction is raised when a transaction is commited.

9. Page_DataBinding
Page_DataBinding occurs when a server control on the page binds to a data source.

What is the order in which Page level events occur?
Page_Init
Page_Load
Page_PreRender
Page_Unload
Page_Disposed

What page property is used to differentiate between a postback and initial get request of a page?
IsPostback property of the Page class.

What are the 3 types of Server Control Events?

Server controls, such as a Button, TextBox, and DropDownList, each have their own sets of events that occur in response to user actions. However, not all server control events are created equal. There are three types of server control events as listed below.

Postback events :
These events cause the Web page to be sent back to the server for immediate processing. Postback events affect perceived performance because they trigger a round-trip to the server. A Button control triggers a postback event. A dropdowinlist can also trigger a post back if the AutoPostBack property of the DropDownList is set to true, else a dropdownlist triggers a cached event. The same is the case with a TextBox.

Cached events :
These events are saved in the page’s view state to be processed when a postback event occurs. A DropDownList and a TextBox can trigger a cached event if the AutoPostBack property is set to false.

Validation events :
These events are handled on the page without posting back or caching. The validation server controls use these types of events.

How can you convert a Cached event of control to a post back event?
You can convert a Cached event of control to a post back event by setting the AutoPostBack property to true.

What is the order in which events are executed?
The validations controls are evaluated before the page is posted back to the server. When the page is posted back, the Page_Init and Page_Load events are handled, then cached events are handled, and finally the event that caused the postback is processed. Among cached events, the event order is determined by the order of the controls on the Web form.

Home

ASP.NET Interview Question Categories

Frequently asked ADO.NET Interview Questions

Home

ASP.NET Interview Question Categories

How do you create an instance of SqlDataReader class?
To create an instance of SqlDataReader class, you must call the ExecuteReader method of the SqlCommand object, instead of directly using a constructor.
//Error! Cannot use SqlDataReader() constructor
//to create an instance of SqlDataReader class
SqlDataReader ReaderObject = new SqlDataReader();

//Call the ExecuteReader method of the SqlCommand object
SqlCommand CommandObject = new SqlCommand();
SqlDataReader ReaderObject = CommandObject.ExecuteReader();

Creating an instance of SqlDataReader class using SqlDataReader() constructor generates a compile time error - The type 'System.Data.SqlClient.SqlDataReader' has no constructors defined.

How do you programatically check if a specified SqlDataReader instance has been closed?
Use the IsClosed property of SqlDataReader to check if a specified SqlDataReader instance has been closed. If IsClosed property returns true, the SqlDataReader instance has been closed else not closed.

How do you get the total number of columns in the current row of a SqlDataReader instance?
FieldCount property can be used to get the total number of columns in the current row of a SqlDataReader instance.

Give an example for executing a stored procedure with parameters?
//Create the Connection Object
SqlConnection ConnectionObject = new SqlConnection(ConnectionString);
//Create the Command Object
SqlCommand CommandObject = new SqlCommand("StoredProcedureName", ConnectionObject);
//Specify to CommandObject that you intend to execute a Stored Procedure
CommandObject.CommandType = CommandType.StoredProcedure;
//Create an SQL Parameter object
SqlParameter ParameterObject = new SqlParameter();
//Specify the name of the SQL Parameter
ParameterObject.ParameterName = "Parameter1";
//Assign the Parameter value
ParameterObject.Value = "Some Value";
//Specify the Database DataType of the Parameter
ParameterObject.DbType = DbType.String;
//Specify the type of parameter - input-only, output-only, bidirectional
ParameterObject.Direction = ParameterDirection.Input;
//Associate the Parameter to the Command Object
CommandObject.Parameters.Add(ParameterObject);
//Open the connection
ConnectionObject.Open();
//Execute the command
int Records_Affected = CommandObject.ExecuteNonQuery();
//Close the Connection
ConnectionObject.Close();

What is the use of SqlParameter.Direction Property?
SqlParameter.Direction Property is used to specify the Sql Parameter type - input-only, output-only, bidirectional, or a stored procedure return value parameter. The default is Input.

How do you retrieve two tables of data at the same time by using data reader?
Include 2 select statements either in a stored procedure or in a select command and call the ExecuteReader() method on the command object. This will automatically fill the DataReader with 2 Tables of data.

The datareader will always return the data from first table only. If you want to get the second table then you need to use ReaderObject.NextResult() method. The NextResult() method will return true if there is another table. The following code shows you how do it.
//Create the SQL Query with 2 Select statements
string SQLQuery = "Select * from Customers;Select * from Employees;";
//Create the Connection Object
SqlConnection ConnectionObject = new SqlConnection(ConnectionString);
//Create the Command Object
SqlCommand CommandObject = new SqlCommand(SQLQuery, ConnectionObject);
//Open the connection
ConnectionObject.Open();
//Execute the command. Now reader object will have 2 tables of data.
SqlDataReader ReaderObject = CommandObject.ExecuteReader();
//Loop thru the tables in the DataReader object
while (ReaderObject.NextResult())
{
while (ReaderObject.Read())
{
//Do Something
}
}
//Close the Reader
ReaderObject.Close();
//Close the Connection
ConnectionObject.Close();

What are the advantages of using SQL stored procedures instead of adhoc SQL queries in an ASP.NET web application?
Better Performance : As stored procedures are precompiled objects they execute faster than SQL queries. Every time we run a SQL query, the query has to be first compiled and then executed where as a stored procedure is already compiled. Hence executing stored procedures is much faster than executing SQL queries.
Better Security : For a given stored procedure you can specify who has the rights to execute. You cannot do the same for an SQL query. Writing the SQL statements inside our code is usually not a good idea. In this way you expose your database schema (design) in the code which may be changed. Hence most of the time programmers use stored procedures instead of plain SQL statements.
Reduced Network Traffic : Stored Procedures reside on the database server. If you have to execute a Stored Procedure from your ASP.NET web application, you just specify the name of the Stored Procedure. So over the network you just send the name of the Stored Procedure. With an SQL query you have to send all the SQL statements over the network to the database server which could lead to increased network traffic.

Can you update the database using DataReader object?
No, You cannot update the database using DataReader object. DataReader is read-only, foward only. It reads one record at atime. After DataReader finishes reading the current record, it moves to the next record. There is no way you can go back to the previous record.

What is the difference between a DataReader and a DataSet?

DataReader
1. DatReader works on a Connection oriented architecture.
2. DataReader is read only, forward only. It reads one record at atime. After DataReader finishes reading the current record, it moves to the next record. There is no way you can go back to the previous record. So using a DataReader you read in forward direction only.
3. Updations are not possible with DataReader.
4. As DataReader is read only, forward only it is much faster than a DataSet.
DataSet
1. DataSet works on disconnected architecture.
2. Using a DataSet you can move in both directions. DataSet is bi directional.
3. Database can be updated from a DataSet.
4. DataSet is slower than DataReader.

Give an example scenario of using a DataSet and a DataReader?

If you want to just read and display the data(No updates, deletes, or inserts) then use a DataReader.
If you want to do a batch inserts, updates and deletes then use a DataSet.

Home

ASP.NET Interview Question Categories

Interview Questions on cascading style sheets

Home

ASP.NET Interview Question Categories

What are the 2 ways provided by ASP.NET to format output in a Web application?
1. Use cascading style sheets (CSS) to control the appearance of elements on a Web form.These styles can set the color, size, font, and behavior of the HTML elements on a Web page.

2. Use Extensible Stylesheet Language Transformations (XSLT) to convert information from an Extensible Markup Language (XML) file to HTML output and position that information on a Web form. XSLT puts data from the XML file into HTML elements and applies styles to those elements.

What are Cascading style sheets?
Cascading style sheets (CSS) collect and organize all of the formatting information applied to HTML elements on a Web form. Because they keep this information in a single location, style sheets make it easy to adjust the appearance of Web applications.

What are the 3 levels at which formatting can be applied with in a web application?
1. Styles can be defined in a style sheet file. Styles in a style sheet can be applied to all webforms referencing the style sheet.

2. You can also define styles in the page’s head element. These styles can be applied to all elements on the current page.

3. You can also define styles inline, in the HTML tag itself. Inline styles are applicable only to the HTML element in which these styles are defined.

Inline formatting takes precedence over local formatting, which, in turn, takes precedence over global formatting. These precedence rules are the reason style sheets are referred to as cascading.

What are the advantages of storing style definitions in a style sheet file (.css) rather than locally in each Web form or inline with each HTML element?
1. Formatting can be maintained in one location so that you make changes only once for an entire application.

2. Several sets of parallel formatting rules can be maintained in separate style sheets for formatting output on different devices or for different user needs. For example, an application might provide standard, enlarged-type, and printer-friendly style sheets that the user can select at run time.

3. In general, you should use page and inline styles only when you have a really good reason to override the global styles. Relying heavily on page and inline styles can make it difficult to maintain the formatting in a Web application.

What HTML element is used to reference a style sheet on webform?
To reference a style sheet on webform you must add a link element to the page’s head element, as shown below.



What is the use of Style Builder?

Style Builder is used to change the appearance of any of the styles in a style sheet. Changes to the style sheet change the appearance of all Web forms that reference that style sheet.

How do you modify a style sheet using style builder?
To modify a style sheet using style builder, follow these steps:

1. Open the style sheet in Visual Studio. Visual Studio .NET displays the style definitions in the Document window and an outline of the style sheet in the Tool window

2. Select the style to modify from the Tool window. Visual Studio .NET displays the definition for that style in the Document window.

3. Right-click in the style definition or right-click the style in the Tool window, and select Build Style from the shortcut menu. Visual Studio .NET displays the Style Builder Wizard.

4. Use the Style Builder to compose the formatting that you want to add or modify in the selected style, and then click OK.

5. When you have finished, you’ll see that the Style Builder adds the new or modified style attributes to the style definition.

Can you apply styles using class names or element IDs?
Yes, Using class names allows you to apply a single style to a number of different elements or to style the same element differently, depending on how the element is used. Using element IDs allows you to apply a style to a unique element on one or more Web forms.

When you create a style rule for a class, Visual Studio .NET adds a style definition to the style sheet using a .classname identifier.

You apply the style class to HTML elements by using the class attribute. You apply the style to server controls by using the CssClass attribute.

Can you change style sheets at run time?
Yes.

Home

ASP.NET Interview Question Categories

Interview Questions on ASP.NET Validation controls

Home

ASP.NET Interview Question Categories

What are ASP.NET Validation controls?
ASP.NET provides validation controls to help you check Web form data entries before the data is accepted and saved in the Database. Validation controls can be used to address the following questions.
1. Did the user enter anything?
2. Is the entry the appropriate kind of data (For example, Date of Birth should be a valid Date, Name should be a string etc.)?
3. Is the data within a required range?(For example age cannot be greater than 100 years)
The validation controls check the validity of data entered in associated server controls on the client before the page is posted back to the server.Most validity problems can be caught and corrected by the user without a round-trip to the server.

Where do the ASP.NET validation controls validate data, on the Client or on the Web Server?

ASP.NET validation controls validate data first on the client and then on the web server. If a client disables javascript on the browser then, client side validations are bypassed and validations are performed on the web server.

Client-side validation is provided by a JScript library named WebUIValidation.js, which is downloaded separately to the client. Validation controls also automatically provide server-side validation. Server-side validation is always performed, whether or not client-side validation has occurred. This double-checking ensures that custom validations are performed correctly and that client-side validation has not been circumvented.

What are the 6 different validation controls provided by ASP.NET?
RequiredFieldValidator:Checks whether a control contains data
CompareValidator:Checks whether an entered item matches an entry in another control
RangeValidator:Checks whether an entered item is between two values
RegularExpressionValidator:Checks whether an entered item matches a specified format
CustomValidator:Checks the validity of an entered item using a client-side script or a server-side code, or both
ValidationSummary:Displays validation errors in a central location or display a general validation error description

What property of the validation control is used to specify which control to validate?
ControlToValidate property.

Explain in simple steps how to use validation controls?
1.Draw a validation control on a Web form and set its ControlToValidate property to the control you want to validate.
2.If you’re using the CompareValidator control, you also need to specify the ControlToCompare property.
3.Set the validation control’s ErrorMessage property to the error message you want displayed if the control’s data is not valid.
4.Set the validation control’s Text property if you want the validation control to display a message other than the message in the ErrorMessage property when an error occurs. Setting the Text property lets you briefly indicate where the error occurred on the form and display the longer ErrorMessage property in a ValidationSummary control.
5.Draw a ValidationSummary control on the Web form to display the error messages from the validation controls in one place.
6.Provide a control that triggers a postback event. Although validation occurs on the client side, validation doesn’t start until a postback is requested.

Are the validation controls fired on the client side if javascript is disabled on the client browser?
No, validation controls are not fired on the client side if javascript is disabled on the client browser.

What is the use of CausesValidation property of an ASP.NET button control?
CausesValidation property of an ASP.NET button control is used to determine if the validation controls should be fired when the button is clicked. If CausesValidation property is set to true, then validation is performed and if the CausesValidation property is set to false then validation is not done.

Give an example of real time scenario where you might use CausesValidation property of an ASP.NET button control?
Let us assume we have a Page that collects user information like name, age, date of birth, gender with a submit and reset buttons. When I click the submit button the information filled on the form should be validated and saved to the database. If I click the reset button then all the controls on the webform should default to their initial values without validation happening.So you have to set the CausesValidation property of the reset button to false for the validation to be bypassed. Other wise you will not be able to post back the page to the server.

What is ASP.NET Custom Validator used for?
ASP.NET Custom Validator is used to perform complex types of validation not provided by the standard validation control, use a CustomValidator control and write code to perform the validation on the server side and optionally on the client side.

How do you programatically check, if the client side validation is not bypassed by disabling the javascript on the client browser?

We use Page.IsValid property to determine if all the validations have succeeded. For this property to return true, all validation server controls in the current validation group must validate successfully.

How do you programatically invoke all validation controls on a page?

Call Page.Validate() method. When this method is invoked, it iterates through the validation controls contained in the ValidatorCollection object associated with the Page.Validators property and invokes the validation logic for each validation control in the current validation group.

What is a validation group?
Validation groups allow you to group validation controls on a page as a set. Each validation group can perform validation independently from other validation groups on the page.

How do you create a validation group?
You create a validation group by setting the ValidationGroup property to the same name for all the controls you want to group. You can assign any name to a validation group, but you must use the same name for all members of the group.

Explain how a validation group works when the Page is posted by clicking a button?
During postback, the Page class's IsValid property is set based only on the validation controls in the current validation group. The current validation group is determined by the control that caused validation to occur. For example, if a button control with a validation group of LoginGroup is clicked, then the IsValid property will return true if all validation controls whose ValidationGroup property is set to LoginGroup are valid.

Can a DropDownList fire validation controls?

Yes, DropDownList control can also fire validation if the control's CausesValidation property is set to true and the AutoPostBack property is set to true.

How do you programatically force all validation controls in a particular validation group to be fired?

Call the Page.Validate(string GroupName) method and pass the name of the validation group. This will fire only the validation controls in that validation group.

What is SetFocusOnError property of a validation control used for?
Use the SetFocusOnError property to specify whether focus is automatically set to the control specified by the ControlToValidate property when this validation control fails. This allows the user to quickly update the appropriate control.

If multiple validation controls fail and this property is set to true, the control specified in the ControlToValidate property for the first validation control receives focus.

What is InitialValue property of a RequiredFieldValidator?

Use this property to specify the initial value of the input control.Validation fails only if the value of the associated input control matches this InitialValue upon losing focus.

Home

ASP.NET Interview Question Categories

Interview Questions on ASP.NET Custom Controls

Home

ASP.NET Interview Question Categories

What are composite custom controls?
Composite custom controls combine one or more server or HTML controls within a single control class, which can be compiled along with other control classes to create an assembly (.dll) that contains a custom control library. Once created, the custom control library can be loaded into Visual Studio .NET and used in the same way as the standard server and HTML controls.

Composite custom controls are functionally similar to user controls, but they reside in their own assemblies, so you can share the same control among multiple projects without having to copy the control to each project, as you must do with user controls. However, composite controls are somewhat more difficult to create because you can’t draw them visually using the Visual Studio .NET Designer.

What are the steps to follow create and use a custom control in a Web application?
1. Create a solution containing a custom control project.
2. Add a Web application
project to the solution, and set it as the startup project. You will use the Web application project to test the custom control during development.
3. Add a project reference from the Web application to the custom control project, and add an HTML @Register directive and control element to use the custom control on a Web form.
4. Create the custom control’s visual interface by adding existing controls to it through the custom control’s CreateChildControls method.
5. Add the properties, methods, and events that the custom control provides.
6. Build and test the custom control.

In general what is the base class for every composite custom control?
System.Web.UI.WebControls.WebControl

Which directive is used to add a custom control to a Web form?
Register directive.

What are the 3 Register directive's attributes?

TagPrefix
This name identifies the group that the user control belongs to. For example, the tag prefix for ASP.NET server controls is “asp”. You use this prefix to create a naming convention to organize your custom controls.
Namespace
This is the project name and namespace within the custom control assembly that contains the controls to register. Microsoft Visual Basic .NET uses the project name as an implicit namespace, so for controls written in Visual Basic .NET, use the project name.
Assembly
This is the name of the assembly (.dll) containing the custom controls. The control assembly must be referenced by the Web application. Referencing the assembly maintains a copy of it in the Web application’s /bin directory.

What are the differences between User Controls and Custom Controls?

1. User Controls are easy to create where as Custom Controls are difficult to create.
2. User Controls cannot be compiled into an assembly, where as Custom Controls can be compiled into an assembly.
3. User Controls cannot be added to tool box, where as Custom controls can be added to the toolbox.
4. You need to have a copy of user control in every project where you want to use it, where as this is not the case with custom controls. You can install a single copy of the Web custom control in the global assembly cache and share it between applications, which makes maintenance easier.
5. User controls are used for reusing existing user interface elements and code, but are not useful for developing reusable components for multiple web applications.

Home

ASP.NET Interview Question Categories

ASP.NET ViewState related Interview Questions

Home

ASP.NET Interview Question Categories

What is ViewState?
Web forms have very short lifetimes.In ASP.NET, the data that is entered in controls is encoded and stored in a hidden field. This encoded data is then sent with each request and restored to controls in Page_Init. The data in these controls is then available in the Page_Load event.The data that ASP.NET preserves between requests is called the Web form’s view state.

How do you enable or disable a ViewState for a control on the page?

Every ASP.NET control has a property called EnableViewState. If EnableViewState is set to true ViewState is enabled for the control. If EnableViewState is set to false ViewState is disabled for the control.

How do you enable or disable a ViewState at the page level?
At the page level you can enable or disable ViewState using EnableViewState property of the page.

What is the name of the hidden form field in which ViewState of the page is saved?

__ViewState

What are the performance implications of ViewState?
ViewState is usually good to retain the state of the controls on the webform across postbacks. If you have a huge DataGrid with tons of data being loaded on every page load. It is a good idea to disable the ViewState of the DataGrid for the page to load faster. If the ViewState of a large DataGrid is not disabled, ViewState can easily get very large, on the order of tens of kilobytes. Not only does the __ViewState form field cause slower downloads, but, whenever the user posts back the Web page, the contents of this hidden form field must be posted back in the HTTP request, thereby lengthening the request time, as well.

When does ViewState restoration happens?
During the Page_Init event

What are the disadvantages of using ViewState?
1. On all page visits, during the save view state stage the Page class gathers the collective view state for all of the controls in its control hierarchy and serializes the state to a base-64 encoded string. (This is the string that is emitted in the hidden __ViewState form filed.) Similarly, on postbacks, the load view state stage needs to deserialize the persisted view state data, and update the pertinent controls in the control hierarchy.

2. The __ViewState hidden form field adds extra size to the Web page that the client must download. For some view state-heavy pages, this can be tens of kilobytes of data, which can require several extra seconds (or minutes!) for modem users to download. Also, when posting back, the __ViewState form field must be sent back to the Web server in the HTTP POST headers, thereby increasing the postback request time.

Is ViewState encoded?
Yes, ViewState is base-64 encoded.

Can you encrypt ViewState of Page?
Yes, we can use the LosFormatter class to encrypt ViewState of Page

Can the HTML controls retian State accross postbacks?
No, by default HTML controls donot retain state accross postbacks.

Can you make HTML controls retain State accross postbacks?

Yes, HTML controls can retain State accross postbacks, if you convert HTML controls to Server Controls. There are 2 ways to convert HTML control to Server Controls.

1. Right click on the HTML Control and then click "Run As Server Control"
Or
2. Set runat="server" attribute for the Control.

Is ViewState supported in classic ASP?
No,ViewState is introduced in asp.net, it was not in classic asp.

When a form is submitted in classic ASP, all form values are cleared. Suppose you have submitted a form with a lot of information and the server comes back with an error. You will have to go back to the form and correct the information. You click the back button, and what happens.......ALL form values are CLEARED, and you will have to start all over again! The site did not maintain your ViewState.

When a form is submitted in ASP .NET, the form reappears in the browser window together with all form values. How come? This is because ASP .NET maintains your ViewState. The ViewState indicates the status of the page when submitted to the server.

Is ViewState of one page available to another page?

No, ViewState of a Page is available only in that page. You cannot access ViewState of one page from another page.

Can you programatically store and retrieve data from ViewState?
Yes. In ASP.NET you can programatically store and retrieve data from ViewState.See the example below

//Save the value in ViewState object
ViewState("SomeVar") = txtFirstName.text;

//Retrieve the value from ViewState object
String strFirstName = ViewState("SomeVar").ToString();

Can someone view the Page HTML source and read ViewState?
No. ViewState is base-64 encoded. Hence you cannot read ViewState. If you right click on the Page and View Source you will find __ViewState is base-64 encoded.

What happens during the Page_Init event?
The server controls are loaded and initialized from the Web form’s view state. This is the first step in a Web form’s life cycle.

Home

ASP.NET Interview Question Categories