asp.net
asp.net
asp.net
Answer: ASP.NET was developed in direct response to the problems that developers had with
classic ASP. Since ASP is in such wide use, however, Microsoft ensured that ASP scripts execute
without modification on a machine with the .NET Framework (the ASP engine, ASP.DLL, is not
modified when installing the .NET Framework). Thus, IIS can house both ASP and ASP.NET scripts
on the same machine.
Advantages of ASP.NET
To make a clean sweep, with ASP.NET you have the ability to completely separate layout
and business logic. This makes it much easier for teams of programmers and designers to
collaborate efficiently.
Developer can use VB.NET and access features such as strong typing and object-oriented
programming. Using compiled languages also means that ASP.NET pages do not suffer the
performance penalties associated with interpreted code. ASP.NET pages are precompiled to
byte-code and Just In Time (JIT) compiled when first requested. Subsequent requests are
directed to the fully compiled code, which is cached until the source changes.
The .NET Framework provides class libraries that can be used by your application. Some of
the key classes help you with input/output, access to operating system services, data
access, or even debugging. We will go into more detail on some of them in this module.
Visual Studio .NET provides a very rich development environment for web developers. You
can drag and drop controls and set properties the way you do in Visual Basic 6. And you
have full IntelliSense support, not only for your code, but also for HTML and XML.
5. State management:
To refer to the problems mentioned before, ASP.NET provides solutions for session and
application state management. State information can, for example, be kept in memory or
stored in a database. It can be shared across web farms, and state information can be
recovered, even if the server fails or the connection breaks down.
Components of your application can be updated while the server is online and clients are
connected. The framework will use the new files as soon as they are copied to the
application. Removed or old files that are still in use are kept in memory until the clients have
finished.
ASP.NET Overview
Here are some points that give the quick overview of ASP.NET.
ASP.NET provides services to allow the creation, deployment, and execution of Web
Applications and Web Services.
Web Applications are built using Web Forms. ASP.NET comes with built-in Web Forms
controls, which are responsible for generating the user interface. They mirror typical HTML
widgets like text boxes or buttons. If these controls do not fit your needs, you are free to
create your own user controls.
Web Forms are designed to make building web-based applications as easy as building
Visual Basic applications.
Introduction to ASP.NET
Client-Side Validation
Server-Side Validation
Client-Side Validation:
When validation is done on the client browser, then it is known as Client-Side Validation. We use
JavaScript to do the Client-Side Validation.
Server-Side Validation:
When validation occurs on the server, then it is known as Server-Side Validation. Server-Side
Validation is a secure form of validation. The main advantage of Server-Side Validation is if the user
somehow bypasses the Client-Side Validation, we can still catch the problem on server-side.
A web application is stateless. That means that a new instance of a page is created every time when
we make a request to the server to get the page and after the round trip our page has been lost
immediately
1. Retains the value of the Control after post-back without using a session.
2. Stores the value of Pages and Control Properties defined in the page.
3. Creates a custom View State Provider that lets you store View State Information in a SQL
Server Database or in another data store.
1. Easy to Implement.
2. No server resources are required: The View State is contained in a structure within the page
load.
3. Enhanced security features: It can be encoded and compressed or Unicode implementation.
A new instance of the Web page class is created each time the page is posted to the server.
In traditional Web programming, all information that is associated with the page, along with
the controls on the page, would be lost with each roundtrip.
The Microsoft ASP.NET framework includes several options to help you preserve data on
both a per-page basis and an application-wide basis.
These options can be broadly divided into the following two categories:
Client-based options involve storing information either in the page or on the client computer.
o Hidden fields
o View state
o Cookies
o Query strings
There are situations where you need to store the state information on the server side.
ASP.NET provides the following options to manage state at the server side:
o Application state
o Session state
For further information click on the link:
Caching is for providing solutions or the results to the users depending on their request, admin
needs to recreate the pages often depending on user requests…STOP!!! "A cache simply stores the
output generated by a page in the memory and this saved output (cache) will serve us (users) in the
future.".
Types
For further information click on the link:
Caching in ASP.Net
Page Theme
A Page theme contains the control skins, style sheets, graphic files, and other resources inside the
subfolder of the App_Theme folder in the Solution Explorer window. A page theme is applied to a
single page of the web site.
Global Theme
A Global theme is a theme that is applied to all the web sites on a web server and includes property
settings, and graphics. This theme allows us to maintain all the websites on the same web server
and define the same style for all the web pages of the web sites.
For further information click on the link:
1. Model
2. View
3. Controller
The ASP.NET MVC framework provides an alternative to the ASP.NET Web Forms pattern for
creating web applications. The ASP.NET MVC Framework is a lightweight, highly testable
presentation framework that (as with Web Forms-based applications) is integrated with existing
ASP.NET features, such as master pages and membership-based authentications. The MVC
framework is defined in the System.Web.Mvc assembly. It provides full control over HTML,
JavaScript and CSS. It's the better as well as a recommended approach for large-scale applications
where various teams are working together.
It makes it very easy to manage complexity by dividing an application into the Model, View
and Controller.
It does not use view state or server-based forms.
Full control over HTML, JavaScript and CSS.
It provides better support for Test-Driven Development (TDD).
It works well for Web applications that are supported by large teams of developers and for
web designers who need a high degree of control over the application behaviour.
By default support of Facebook and Google Authentication.
It easy to manage a large application to divide in multiple areas.
1. Domain: Using these properties we can set the domain of the cookie.
2. Expires: This property sets the Expiration time of the cookies.
3. HasKeys: If the cookies have a subkey then it returns True.
4. Name: Contains the name of the Key.
5. Path: Contains the Virtual Path to be submitted with the Cookies.
6. Secured: If the cookies are to be passed in a secure connection then it only returns True.
7. Value: Contains the value of the cookies.
AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with
the server behind the scenes. This means that it is possible to update parts of a web page, without
reloading the entire page.
We can also define Ajax is a combination of client side technologies that provides asynchronous
communication between the user interface and the web server so that partial page rendering occurs
instead of complete page post back.
Ajax is platform-independent; in other words AJAX is a cross-platform technology that can be used
on any Operating System since it is based on XML & JavaScript. It also supports open source
implementation of other technology. It partially renders the page to the server instead of complete
page post back. We use AJAX for developing faster, better and more interactive web applications.
AJAX uses a HTTP request between web server & browser.
With AJAX, when a user clicks a button, you can use JavaScript and DHTML to immediately
update the UI, and spawn an asynchronous request to the server to fetch results.
When the response is generated, you can then use JavaScript and CSS to update your UI
accordingly without refreshing the entire page. While this is happening, the form on the users
screen doesn't flash, blink, disappear, or stall.
The power of AJAX lies in its ability to communicate with the server asynchronously, using a
XMLHttpRequest object without requiring a browser refresh.
Ajax essentially puts JavaScript technology and the XMLHttpRequest object between your
Web form and the server.
Language Independent.
Protocol Independent.
Platform Independent.
It assumes a stateless service architecture.
Scalable (e.g. multiplying two numbers together to an entire customer-relationship
management system).
Programmable (encapsulates a task).
Based on XML (open, text-based standard).
Self-describing (metadata for access and use).
Discoverable (search and locate in registries)- ability of applications and developers to
search for and locate desired Web services through registries. This is based on UDDI.
XML- Describes only data. So, any application that understands XML-regardless of the
application's programming language or platform-has the ability to format XML in a variety of
ways (well-formed or valid).
SOAP- Provides a communication mechanism between services and applications.
WSDL- Offers a uniform method of describing web services to other programs.
UDDI- Enables the creation of searchable Web services registries.
Advantages of ASP.NET:
Introduction to ASP.NET
Proper Globalization: Your application should be able to Accept, Verify, and Display all
global kind of data. It should well also be able to operate over this data, accordingly. We will
discuss more about this "Accordingly operations over diff. culture data".
Localizability and Localization: Localizability stands for clearly separating the components
of culture based operations regarding the user interface, and other operations from the
executable code.
.NET framework has greatly simplified the task of creating the applications targeting the clients of
multiple cultures. The namespaces involved in creation of globalize, localizing applications are:
System.Globalization
System.Resources
System.Text
For further info click on the link:
ASP.NET Configuration system is used to describe the properties and behaviors of various aspects
of ASP.NET applications. Configuration files help you to manage the settings related to your
website. Each file is an XML file (with the extension .config) that contains a set of configuration
elements. Configuration information is stored in XML-based text files.
The CLR can allow the multiple .NET applications to run in a single AppDomain. Mulitple
Appdomains can exist in Win32 process.
How to create AppDomain: AppDomains are created using the CreateDomain method.
AppDomain instances are used to load and execute assemblies (Assembly). When an AppDomain is
no longer in use, it can be unloaded.
Request.QueryString(variable)[(index).count]
Advantages:
Simple to Implement
Easy to get information from Query string.
Used to send or read cross domain (from different domain).
Disadvantages:
Human Readable
Client browser limit on URL length
Cross paging functionality makes it redundant
Easily modified by end user
1. </asp:ContentPlaceHolder>
2. <br /> Footer...
3. </form>
1. We can see the execution path of the page and application using the debug statement.
2. We can access and manipulate trace messages programmatically.
3. We can see the most recent tracing of the data.
1. Page Level: When the trace output is displayed on the page and for the page-level tracing
we need to set the property of tracing at the page level.
2. Application: Level: In Application-Level tracing the information is stored for each request of
the application. The default number of requests to store is 10. But if you want to increase the
number of requests and discard the older request and display a recent request then you
need to set the property in the web.config file.
<trace enabled="true"/>
Data Binding is binding controls to data from databases. With data binding we can bind a control to a
particular column in a table from the database or we can bind the whole table to the data grid.
Data binding provides simple, convenient, and powerful way to create a read/write link between the
controls on a form and the data in their application.
Data binding allows you to take the results of properties, collection, method calls, and database
queries and integrate them with your ASP.NET code. You can combine data binding with Web
control rendering to relieve much of the programming burden surrounding Web control creation. You
can also use data binding with ADO.NET and Web controls to populate control contents from SQL
select statements or stored procedures.
<%# %>
The <%#, which instructs ASP.NET to evaluate the expression. The difference between a data
binding tags and a regular code insertion tags <% and %> becomes apparent when the expression
is evaluated. Expressions within the data binding tags are evaluated only when the DataBind method
in the Page objects or Web control is called.
Data Bind Control can display data in connected and disconnected model.
Repeater Control
DataGrid Control
DataList Control
GridView Control
DetailsView
FormView
DropDownList
ListBox
RadioButtonList
CheckBoxList
BulletList etc.
Application_Init
Application_Disposed
Application_Error
Application_Start
Application_End
Application_BeginReques
Property Description
Specifies whether the form should be posted immediately after the Checked
AutoPostBack
property has changed or not. The default is false.
CausesValidation Specifies if a page is validated when a Button control is clicked.
Checked Specifies whether the check box is checked or not.
InputAttributes Attribute names and values used for the Input element for the CheckBox control.
LabelAttributes Attribute names and values used for the Label element for the CheckBox control.
runat Specifies that the control is a server control. Must be set to "server".
Text The text next to the check box.
TextAlign On which side of the check box the text should appear (right or left).
Group of controls for which the Checkbox control causes validation when it posts
ValidationGroup
back to the server.
OnCheckedChanged The name of the function to be executed when the Checked property has changed.
In ASP.NET authentication means to identify the user or in other words its nothing but to validate
that he exists in your database and he is the proper user.
Authorization means does he have access to a particular resource on the IIS website. A resource
can be an ASP.NET web page, media files (MP4, GIF, JPEG etc), compressed file (ZIP, RAR) etc.
Types of authentication and authorization in ASP.NET
Windows authentication: In this methodology ASP.NET web pages will use local windows
users and groups to authenticate and authorize resources.
Anonymous access: If you do not want any kind of authentication then you will go for
Anonymous access.
In 'web.config' file set the authentication mode to 'Windows' as shown in the below code snippets.
1. <authentication mode="Windows"/>
We also need to ensure that all users are denied except authorized users. The below code snippet
inside the authorization tag that all users are denied. '?' indicates any unknown user.
1. <authorization>
2. <deny users="?"/>
3. </authorization>
HTML developers must be familiar with old HTML controls, which they use to write GUI
applications in HTML. These controls are the same HTML controls; you can run these
controls on the server by defining the runat ="server" attribute. These control names start
with Html.
Controls Description
HtmlForm Create an HTML form control, used as a place holder of other controls.
HtmlInputText Creates an input text box control used to get input from user.
HtmltextArea Creates multiline text box control.
HtmlAnchor Creates a Web navigation.
HtmlButton Creates a button control.
HtmlImage Creates an image control, which is used to display an image.
HtmlInputCheckBox Creates a check box control.
HtmlInputRadioButton Creates a radio button control.
HtmlTable Creates a table control.
HtmlTableRow Creates a row within a table.
HtmlTableCell Creates a cell with in a row.
1. <authentication mode="Windows">
2. <forms name=" AuthenticationDemo" loginUrl="logon.aspx" protection="All" path="/"tim
eout="30" />
3. </authentication>
1. <authentication mode="Forms">
2. <forms name=" AuthenticationDemo" loginUrl="logon.aspx" protection="All" path="/"tim
eout="30" />
3. </authentication>
Features:
It is light weight and thus good for small devices also like tablets, smart phones.
No tedious & extensive configuration like WCF REST is required.
MediaTypeFormatter makes easy to configure your APIs response type in single line (JSON,
XML and so on).
IIS Hosting dependency is no more and it can be hosted in application too.
Easy and simple control with HTTP features such as Caching, Versioning, request/response
headers and its various content formats.
It support content-negotiation (deciding the best response data format that client can accept).
Whenever the webserver has been restarted or stopped then the information maintained by the
application object will be lost.
If any data is stored on the application object then that information will be shared upon all the users
accessing the webserver.
Since the information is shared among all the users, it is advisable to lock and unlock the application
object as per requirement.
It is a Class which consists of event handlers which executes the code implicitly whenever a relevant
task has been performed on the web server.Design:
Code Behind refers to the code for an ASP.NET Web page that is written in a separate class file that
can have the extension of .aspx.cs or .aspx.vb depending on the language used. Here the code is
compiled into a separate class from which the .aspx file derives. You can write the code in a
separate .cs or .vb code file for each .aspx page. One major point of Code Behind is that the code
for all the Web pages is compiled into a DLL file that allows the web pages to be hosted free from
any Inline Server Code.
Inline Code
Inline Code refers to the code that is written inside an ASP.NET Web Page that has an extension of
.aspx. It allows the code to be written along with the HTML source code using a <Script> tag. It's
major point is that since it's physically in the .aspx file it's deployed with the Web Form page
whenever the Web Page is deployed.
There are four stages that occur during the Page Life Cycle before the HTML Response is returned
to the client. Later in this article we"ll study all these stages and their sub events.
1. Initialization
2. Loading
3. Rendering
4. Unloading
During this stage the IsPostback property is set. The page determines whether the request
is a Postback (old request) or if this is the first time the page is being processed (new
Initialization request). Controls on the page are available and each control's UniqueID property is set.
Now if the current request is a postback then the data has not been loaded and the value of
the controls have not yet been restored from the view state.
Loading At this stage if the request is a Postback then it loads the data from the view state.
Before rendering, the View State is saved for the page and its controls. During this phase,
Rendering the page calls the render method for each control, providing a text writer that writes its
output to the OutputStream of the page's Response property.
Unload is called after the page has been fully rendered, sent to the client and is ready to be
Unloading discarded. At this point also the page properties such as Response and Request are
unloaded.
For further info click on the link:
Page request
When ASP.NET gets a page request, it decides whether to parse and compile the page or
there would be a cached version of the page; accordingly the response is sent,
At this stage, the Request and Response objects are set. If the request is an old request or
post back, the IsPostBack property of the page is set to true. The UICulture property of the
page is also set.
Page initialization
At this stage, the controls on the page are assigned unique ID by setting the UniqueID
property and themes are applied. For a new request postback data is loaded and the control
properties are restored to the view-state values.
Page load
At this stage, control properties are set using the view state and control state values.
Validation
Validate method of the validation control is called and if it runs successfully, the IsValid
property of the page is set to true.
If the request is a postback (old request), the related event handler is called.
Page rendering
At this stage, view state for the page and all controls are saved. The page calls the Render
method for each control and the output of rendering is written to the OutputStream class of
the Page's Response property.
Unload
The rendered page is sent to the client and page properties, such as Response and Request
are unloaded and all cleanup done.
PreInit is the first event in page life cycle. It checks the IsPostBack property and determines
whether the page is a postback. It sets the themes and master pages, creates dynamic
controls and gets and sets profile property values. This event can be handled by overloading
the OnPreInit method or creating a Page_PreInit handler.
Init
Init event initializes the control property and the control tree is built. This event can be
handled by overloading the OnInit method or creating a Page_Init handler.
InitComplete
InitComplete event allows tracking of view state. All the controls turn on view-state tracking.
LoadViewState
LoadViewState event allows loading view state information into the controls.
LoadPostData
During this phase, the contents of all the input fields defined with the <form> tag are
processed.
PreLoad
PreLoad occurs before the post back data is loaded in the controls. This event can be
handled by overloading the OnPreLoad method or creating a Page_PreLoad handler.
Load
The Load event is raised for the page first and then recursively for all child controls. The
controls in the control tree are created. This event can be handled by overloading the
OnLoad method or creating a Page_Load handler.
LoadComplete
The loading process is completed, control event handlers are run and page validation takes
place. This event can be handled by overloading the OnLoadComplete method or creating a
Page_LoadComplete handler.
PreRender
The PreRender event occurs just before the output is rendered. By handling this event,
pages and controls can perform any updates before the output is rendered.
PreRenderComplete
as the PreRender event is recursively fired for all child controls, this event ensures the
completion of the pre-rendering phase.
SaveStateComplete
State of control on the page is saved. Personalization, control state and view state
information is saved. The HTML markup is generated. This stage can be handled by
overriding the Render method or creating a Page_Render handler.
UnLoad
The UnLoad phase is the last phase of the page life cycle. It raises the UnLoad event for all
controls recursively and lastly for the page itself. Final cleanup is done and all resources and
references, such as database connections, are freed. This event can be handled by
modifying the OnUnLoad method or creating a Page_UnLoad handler.
Username Label and Textbox: Collects the string used to identify the user in the
membership system.
Password Label and Textbox: Collects the password for the specified user. The textbox
text is always obscured.
LoginButton: The button to submit the users request for authentication.
RememberMe: Configurable to display a checkbox giving the user the option to store a
persistent cookie on the user's machine.
Title and Instruction: Text to orient and guide the user through the process.
Links: Configurable links to help, password recovery and user registration information.
Validators: Required field Validators for the username and password textboxes.
For Example:
Item Template
AlternatingItem Template
Header Template
Footer Template
Separator Template
Write connection code and select command in code bihaind file like:
When you run this page so output will look like as:
For further info click on the link:
We can set the session on one of the following 2 types of configuration files:
2. Application Configuration file: It's applied for only application by application basis.
Session Mode
Off: We can disable the session mode for the entire application using the off mode.
According to performance and durability the difference between InProc,State Server and SQL Server
is:
1. Session[“KEY”] =”Value”;
Or
1. Session[index] = ”Value”;
2. Let’ s a have an example: using System;
3. using System.Collections.Generic;
4. using System.Linq;
5. using System.Web;
6. using System.Web.UI;
7. using System.Web.UI.WebControls;
8. namespace WebApp
9. {
10. public partial class WebForm1: System.Web.UI.Page
11. {
12. protected void Page_Load(object sender, EventArgs e)
13. {
14. if(!IsPostBack)
15. {
16. HttpContext.Current.Items["Value"] = "Sourav Kayal in ITEM";
17. HttpContext.Current.Session["Value"] = "Sourav Kayal in SESSION";
18. Response.Write((string)(HttpContext.Current.Items["Value"]) + "<br>");
19. Response.Write((string)(HttpContext.Current.Session["Value"]));
20. }
21. }
22. protected void Button1_Click(object sender, EventArgs e)
23. {
24. Response.Write((string)(HttpContext.Current.Items["Value"]) + "<br>");
25. Response.Write((string)(HttpContext.Current.Session["Value"]));
26. }
27. }
28. }
The Response.Redirect method redirects a request to a new URL and specifies the new URL while
the Server.Transfer method for the current request, terminates execution of the current page and
starts execution of a new page using the specified URL path of the page.
1. Response.Redirect("UserDetail.aspx");
2. Server.Transfer("UserDetail.aspx");
Before touching on more points I want to explain some HTTP status codes, these are important for
the understanding of the basic differences between these two. The HTTP status codes are the
codes that the Web server uses to communicate with the Web browser or user agent.
It is not difficult to add a directive to an ASP.NET page. It is simple to add directives to an ASP.NET
page. You can write directives in the following format:
<%@[Directive][Attributes]%>
See the directive format, it starts with "<%@" and ends with "%>". The best way is to put the
directive at the top of your page. But you can put a directive anywhere in a page. One more thing,
you can put more than one attribute in a single directive.
Examples: ASP.NET uses different HTTP handlers to serve different file types. For example, the
handler for web Page creates the page and control objects, runs your code, and renders the final
HTML.
Why we need to create our own HTTP Handler: Sometime we need to avoid ASP.NET full page
processing model, which saves lot of overheads, as ASP.NET web form model has to go through
many steps such as creating web page objects, persisting view state etc. What we are interested
into is to develop some low level interface that provides access to objects like Request and
Response but doesn't use the full control based web form model discussed above.
Examples:
1. Dynamic image creator - Use the System.Drawing classes to draw and size your own
images.
2. RSS - Create a handler that responds with RSS-formatted XML. This would allow you to add
RSS feed capabilities to your sites.
3. Render a custom image,
4. Perform an ad hoc database query,
5. Return some binary data.
All HTTP handlers are defined in the <httpHandlers> section of a configuration file which is nested in
the <system.web> element.
1. <httpHandlers>
2. <add verb="*" path="trace.axd" validate="true" type="System.Web.Handlers.TraceHandl
er" />
3. <add verb="*" path="*.config" validate="true" type="System.Web.HttpForbiddenHandler
" />
4. <add verb="*" path="*.cs" validate="true" type="System.Web.HttpForbiddenHandler" />
HTTP Handler
HTTP Handler is the process which runs in response to a HTTP request. So whenever user requests
a file it is processed by the handler based on the extension. So, custom http handlers are created
when you need to special handling based on the file name extension. Let's consider an example to
create RSS for a site. So, create a handler that generates RSS-formatted XML. Now bind the .rss
extension to the custom handler.
HTTP Modules
HTTP Modules are plugged into the life cycle of a request. So when a request is processed it is
passed through all the modules in the pipeline of the request. So generally http modules are used
for:
Adding the AdRotator web server control to your web application. first, select the AdRotator and drag
and drop the control to your web form. Map the XML file which contains the details about each and
every ad.
The advertisement file is an XML file. The following are some of the elements of this XML file.
XML code that has the details about the ads. The file Ads.xml looks like the code below:
1. <Advertisements>
2. <Ad>
3. <ImageUrl>adimages/2.jpg</ImageUrl>
4. <NavigateUrl>http://cat2.com</NavigateUrl>
5. <AlternateText>Cat 2</AlternateText>
6. <Impressions>30</Impressions>
7. </Ad>
8. <Ad>
9. <ImageUrl>adimages/3.jpg</ImageUrl>
10. <NavigateUrl>http://cat3.com</NavigateUrl>
11. <AlternateText>Cat 3</AlternateText>
12. <Impressions>20</Impressions>
13. </Ad>
14. <Ad>
15. <ImageUrl>adimages/4.jpg</ImageUrl>
16. <NavigateUrl>http://cat4.com</NavigateUrl>
17. <AlternateText>Cat 4</AlternateText>
18. <Impressions>10</Impressions>
19. </Ad>
20. </Advertisements>
ASP.NET 2.0 provides a feature known as Cross Page PostBack for a web form to post-back to a
different web form (other than itself)
Access source page info within the posted page: FindControl Method
The target web form resulting from the cross-page postback provides a non-null PreviousPage
property. This property represents the source page and provides reference to the source web form
and its controls.
The controls on the source page can be accessed via the FindControl method on the object returned
by the PreviousPage property of the target page.
At this point the target page does not have any knowledge of the source page. The PreviousPage
property is of the type Page. For accessing controls using FindControl, the developer has to
presume a certain structure in the source web form. This approach using FindControl has a few
limitations. FindControl is dependent on the developer to provide the ids of the controls to access.
The code will stop working if the control id is changed in the source web form. The FindControl
method can retrieve controls only within the current container. If you need to access a control within
another control, you need to first get a reference to the parent control.
Access source page info within the posted page: @PreviousPageType Directive
There is another more direct option to get access to the source page controls if the source page is
pre-determined. The @PreviousPageType directive can be used in the target page to strongly type
the source page. The directive specifies the source page using either the VirtualPath attribute or the
TypeName attribute. The PreviousPage property then returns a strongly typed reference to the
source page. It allows access to the public properties of the source page.
SourcePage.aspx:
TargetPage.aspx
Creating a GridView
Question 41: What is the difference between ASP.NET Web API and
WCF?
Answer: The ASP. NET Web API is a framework that uses the HTTP services and makes it easy to
provide the response to the client request. The response depends on the request of the clients. The
Web API builds the HTTP services, and handles the request using the HTTP protocols. The request
may be GET, POST, DELETE, PUT. We can also say that the ASP. NET Web API:
Is an HTTP service.
Is designed for reaching the broad range of clients.
Uses the HTTP application.
We use the ASP. NET Web API for creating the REST ful (Representational State Transfer)
services.
The following are some important points of the ASP. NET Web API:
The ASP. NET Web API supports the MVC application features that are controller, media
formatters, routing etcetera.
It is a platform for creating the REST services.
It is a framework for creating the HTTP services.
Responses can be formatted by the APIs MediaTypeFormatter into the Java Script Object
Notation (JSON) and Extencible Markup Language (XML) formats.
http://www.c-sharpcorner.com/UploadFile/2b481f/difference-between-Asp-Net-web-api-and-
wc
ASP.NET also adds two additional hidden input fields that are used to pass information back to the
server. This information consists of ID of the Control that raised the event and any additional
information if needed. These fields will empty initially as shown below,
The following actions will be taken place when a user changes a control that has the AutoPostBack
property set to true:
1. On the client side, the JavaScript _doPostBack function is invoked, and the page is
resubmitted to the server.
2. ASP.NET re-creates the Page object using the .aspx file.
3. ASP.NET retrieves state information from the hidden view state field and updates the
controls accordingly.
4. The Page.Load event is fired.
5. The appropriate change event is fired for the control. (If more than one control has been
changed, the order of change events is undetermined.)
6. The Page.PreRender event fires, and the page is rendered (transformed from a set of
objects to an HTML page).
7. Finally, the Page.Unload event is fired.
8. The new page is sent to the client.
AutoDetect: Session uses background cookie if cookies are enabled. If cookies are
disabled, then the URL is used to store session information.
UseDeviceProfile: Session uses background cookie if browser supports cookies else URL
is used.
"regenerateExpiredSessionId" is used to ensure that if a cookieless url is expired a new new url is
created with a new session. And if the same cookieless url is being used by multiple users an the
same time, they all get a new regenerated session url.
We define themes in a special App_Themes folder. Inside this folder is one or more subfolders
named Theme1, Theme2 etc. that define the actual themes. The theme property is applied late in
the page's life cycle, effectively overriding any customization you may have for individual controls on
your page.
1. Setting the theme at the page level: the Theme attribute is added to the page directive of the
page.
1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"Inherits
="Default" Theme="Theme1"%>
2. Setting the theme at the site level: to set the theme for the entire website you can set the
theme in the web.config of the website. Open the web.config file and locate the <pages>
element and add the theme attribute to it:
1. <pages theme="Theme1">
2. ....
3. ....
4. </pages>
3. Setting the theme programmatically at runtime: here the theme is set at runtime through
coding. It should be applied earlier in the page's life cycle ie. Page_PreInit event should be
handled for setting the theme. The better option is to apply this to the Base page class of the
site as every page in the site inherits from this class.
1. Page.Theme = Theme1;
Uses of Themes
1. Since themes can contain CSS files, images and skins, you can change colors, fonts,
positioning and images simply by applying the desired themes.
2. You can have as many themes as you want and you can switch between them by setting a
single attribute in the web.config file or an individual aspx page. Also you can switch between
themes programmatically.
3. Setting the themes programmatically, you are offering your users a quick and easy way to
change the page to their likings.
4. Themes allow you to improve the usability of your site by giving users with vision problems
the option to select a high contrast theme with a large font size.
Themes in ASP.NET
Response.Redirect
Server.Transfer
Server.Exceute
Cross page posting
We can compose web parts pages from "web parts", which can be web controls, user controls.
Component of Web Parts:
Web Part Zone can contain one or more Web Part controls.
This provides the layout for the Controls it contains. A single ASPX page can contain one or
more Web Part Zones.
A Web Part Control can be any of the controls in the toolbox or even the customized user
controls.
2. MasterPage cannot be directly accessed from the client because it just acts as a template for
the other Content Pages.
3. In a MasterPage we can have content either inside ContentPlaceHolder or outside it. Only
content inside the ContentPlaceHolder can be customized in the Content Page.
6. The content page content can be placed only inside the content tag.
7. Controls of MasterPage can be programmed in the MasterPage and content page but a
content page control will never be programmed in MasterPage.
8. A master page of one web application cannot be used in another web application.
9. The MasterPageFile property of a webform can be set dynamically and it should be done
either in or before the Page_PreInit event of the WebForm. Page.MasterPageFile =
"MasterPage.master". The dynamically set Master Page must have the
ContentPlaceHolder whose content has been customized in the WebForm.
10. The order in which events are raised: Load (Page) a Load (Master) a LoadComplete (Page)
i.e. if we want to overwrite something already done in Load event handler of Master then it
should be coded in the LoadComplete event of the page.
11. Page_Load is the name of method for event handler for Load event of Master. (it's
not Master_Load).
When client request to the server, server execute the stored procedure or function or select
statements on the Sql Server database then it returns the response to the browser. If we run again
same process will happen on the web server with sql server.
We can create data caching use Cache Keyword. It's located in the System.Web.Caching
namespace. It's just like assigning value to the variable.
We use the Enterprise Library when we want to build application blocks intended for the use of
developers who create complex enterprise level application.
This block provides the developers to create consistency for processing the error that occur
throughout the layers of Enterprise Application.
Caching Application Block allows developers to incorporate local cache in the applications.
Here I used the word “improve performance” in the sense to decrease the loading time of the page.
There are various reasons behind. Some of them we look into from the “backend side” (Database
side) and rest of them we need to take care in “front-end” ((UI) side.
For illustrative purpose, you have an ASP.NET Web site, one of the aspx page take much time to
load. Throughout this article, we are going to see how to decrease the loading time.
1. Try to check the Query performance that is how much time the query will take to execute and
pull the records from DB. Then use SQL Server Profiler and Execution plan for that query so
that you can come to a conclusion in which part it took much time.
2. Check in every table (who are all part of the query) Index is created properly.
3. If your query involves a complex stored procedure, which in turn use lot of joins, then you
should focus on every table. In some cases, sub-query perform better than the joins.
4. If your web page involves paging concepts, try to move the paging concepts to SQL Server. I
meant that based on the page count the SP will return the records, instead of bringing the
records as a whole.
5. SP.NET Interview Questions and Answers – Experienced
Developers
6. What is XHTML? Are ASP.NET Pages compliant with XHTML?
7. In simple words, XHTML is a stricter and cleaner version of HTML. XHTML stands for
EXtensible Hypertext Markup Language and is a W3C Recommendation.
8. Yes, ASP.NET 2.0 Pages are XHTML compliant. However the freedom has been given to the
user to include the appropriate document type declaration.
9. More info can be found at http://msdn2.microsoft.com/en-us/library/exc57y7e.aspx
10. Can I deploy the application without deploying the source code on the server?
11. Yes. You can obfuscate your code by using a new precompilation process called
‘precompilation for deployment’. You can use the aspnet_compiler.exe to precompile a site.
This process builds each page in your web application into a single application DLL and some
placeholder files. These files can then be deployed to the server.
12. You can also accomplish the same task using Visual Studio 2005 by using the Build->Publish
menu.
13. Does ViewState affect performance? What is the ideal size of a ViewState? How can you
compress a viewstate?
14. Viewstate stores the state of controls in HTML hidden fields. At times, this information can
grow in size. This does affect the overall responsiveness of the page, thereby affecting
performance. The ideal size of a viewstate should be not more than 25-30% of the page size.
15. Viewstate can be compressed to almost 50% of its size. .NET also provides
the GZipStreamorDeflateStream to compress viewstate. Another option is explained by Scott
Hanselmann over here.
16. How can you detect if a viewstate has been tampered?
17. By setting the EnableViewStateMac to true in the @Page directive. This attribute checks the
encoded and encrypted viewstate for tampering.
18. You can also view ViewState information as described in this article How to view information
in ViewState using ASP.NET 2.0 and 3.5
19. Can I use different programming languages in the same application?
20. Yes. Each page can be written with a different programming language in the same application.
You can create a few pages in C# and a few in VB.NET.
21. Can the App_Code folder contain source code files in different programming
languages?
22. No. All source code files kept in the root App_Code folder must be in the same programming
language.
23. Update: However, you can create two subfolders inside the App_Code and then add both C#
and VB.NET in the respective subfolders. You also have to add configuration settings in the
web.config for this to work.
24. How do you secure your connection string information?
25. By using the Protected Configuration feature.
26. How do you secure your configuration files to be accessed remotely by unauthorized
users?
27. ASP.NET configures IIS to deny access to any user that requests access to the Machine.config
or Web.config files.
28. How can I configure ASP.NET applications that are running on a remote machine?
29. You can use the Web Site Administration Tool to configure remote websites.
30. How many web.config files can I have in an application?
31. You can keep multiple web.config files in an application. You can place a Web.config file inside
a folder or wherever you need (apart from some exceptions) to override the configuration
settings that are inherited from a configuration file located at a higher level in the hierarchy.
32. I have created a configuration setting in my web.config and have kept it at the root level.
How do I prevent it from being overridden by another web.config that appears lower in
the hierarchy?
33. By setting the element's Override attribute to false.
34. What is the difference between Response.Write and Response.Output.Write?
35. As quoted by Scott Hanselman, the short answer is that the latter gives you String.Format-
style output and the former doesn't.
36. To get a detailed explanation, follow this link
37. What is Cross Page Posting? How is it done?
38. By default, ASP.NET submits a form to the same page. In cross-page posting, the form is
submitted to a different page. This is done by setting the ‘PostBackUrl’ property of the
button(that causes postback) to the desired page. In the code-behind of the page to which the
form has been posted, use the ‘FindControl’method of the ‘PreviousPage’ property to
reference the data of the control in the first page.
39. Can you change a Master Page dynamically at runtime? How?
40. Yes. To change a master page, set the MasterPageFile property to point to the .master page
during the PreInit page event.
41. How do you apply Themes to an entire application?
42. By specifying the theme in the web.config file.
<configuration>
<system.web>
</system.web>
</configuration>
43. How do you exclude an ASP.NET page from using Themes?
44. To remove themes from your page, use the EnableTheming attribute of the Page directive.
45. Your client complains that he has a large form that collects user input. He wants to
break the form into sections, keeping the information in the forms related. Which
control will you use?
46. The ASP.NET Wizard Control.
47. To learn more about this control, visit this link.
48. Do webservices support data reader?
49. No. However it does support a dataset.
50. What is use of the AutoEventWireup attribute in the Page directive ?
51. The AutoEventWireUp is a boolean attribute that allows automatic wireup of page events when
this attribute is set to true on the page. It is set to True by default for a C# web form whereas
it is set as False for VB.NET forms. Pages developed with Visual Studio .NET have this
attribute set to false, and page events are individually tied to handlers.
52. What happens when you change the web.config file at run time?
53. ASP.NET invalidates the existing cache and assembles a new cache. Then ASP.NET
automatically restarts the application to apply the changes.
54. Can you programmatically access IIS configuration settings?
55. Yes. You can use ADSI, WMI, or COM interfaces to configure IIS programmatically.
56. How does Application Pools work in IIS 6.0?
57. As explained under the IIS documentation, when you run IIS 6.0 in worker process isolation
mode, you can separate different Web applications and Web sites into groups known
as application pools. An application pool is a group of one or more URLs that are served by a
worker process or set of worker processes. Any Web directory or virtual directory can be
assigned to an application pool.
58. Every application within an application pool shares the same worker process. Because each
worker process operates as a separate instance of the worker process executable, W3wp.exe,
the worker process that services one application pool is separated from the worker process
that services another. Each separate worker process provides a process boundary so that
when an application is assigned to one application pool, problems in other application pools
do not affect the application. This ensures that if a worker process fails, it does not affect the
applications running in other application pools.
59. Use multiple application pools when you want to help ensure that applications and Web sites
are confidential and secure. For example, an enterprise organization might place its human
resources Web site and its finance Web site on the same server, but in different application
pools. Likewise, an ISP that hosts Web sites and applications for competing companies might
run each company’s Web services on the same server, but in different application pools. Using
different application pools to isolate applications helps prevent one customer from accessing,
changing, or using confidential information from another customers site.
60. In HTTP.sys, an application pool is represented by a request queue, from which the user-mode
worker processes that service an application pool collect the requests. Each pool can manage
requests for one or more unique Web applications, which you assign to the application pool
based on their URLs. Application pools, then, are essentially worker process configurations
that service groups of namespaces.
61. Multiple application pools can operate at the same time. An application, as defined by its URL,
can only be served by one application pool at any time. While one application pool is servicing
a request, you cannot route the request to another application pool. However, you can assign
applications to another application pool while the server is running.
62. Note: This ASP.NET Questions and Answers for Experienced Developers have been taken
from forums, my colleagues and my own experience of conducting interviews. I have tried to
mention the contributor wherever possible. If you would like to contribute, kindly use
the Contact form. If you think that a credit for a contribution is missing somewhere, kindly use
the same contact form and I will do the needful.
ASP.NET is a web application development framework for building web sites and web applications
that follows object oriented programming approach".
Following are the top 10 commonly asked Interview Questions with Answers on ASP.NET:
A postback is a request sent from a client to server from the same page user is already working with.
ASP.NET was introduced with a mechanism to post an HTTP POST request back to the same page.
It’s basically posting a complete page back to server (i.e. sending all of its data) on the same page.
So, the whole page is refreshed.
In the below diagram, when first request is made from client to server for a web page (say a simple
registration form), IsPostback property value will be false. It will be a GET request that may be
initiated by:
After user filled the returned form and presses a button (say submit button, or use JavaScript to
submit form), an HTTP Post request is made to server on same page with data as shown in point 3.
This time IsPostbackproperty value will be true. Server processes the request and returns a
response back to client.
Another concept related to this approach is "Callback" that is also asked sometimes during a
technical interview question. Click here to understand Postback Vs Callback in ASP.NET.
ASP.NET Web Forms uses Page controller pattern approach for rendering layout. In this approach,
every page has it's own controller, i.e., code-behind file that processes the request. On the other
hand, ASP.NET MVC uses Front Controller approach. In this approach, a common controller for all
pages, processes the requests.
Please follow for detailed information on WebForms Vs MVC.
ASP.NET page passes through a series of steps during its life cycle. Following is the high-level
explanation of life cycle stages/steps.
Initialization: Controls raise their Init event in this stage. Objects and variables are initializes for
complete lifecyle of request.
LoadViewState: is a post back stage and loads the view state for the controls that enabled its view
state property.
LoadPostBackData: is also a post back stage and loads the data posted for the controls and
updates them.
Load: In this stage, page as well as all the controls raise their Load event. Till this stage, all the
controls are initialized and loaded. In most of the cases, we are coding this event handler.
RaisePostBackEvent: is again a postback stage. For example, it's raise against a button click event.
We can easily put our code here to perform certain actions.
SaveViewState: Finally, controls state is saved in this stage before Rendering HTML.
Render: This is the stage where HTML is generated for the page.
Dispose: Lastly, all objects associated with the request are cleaned up.
In order to get other ASP.NET related details as per Microsoft Certification Exams, you can follow
here.
What is the difference between custom controls and user controls?
Custom controls are basically compiled code, i.e., DLLs. These can be easily added to toolbox, so it
can be easily used across multiple projects using drag and drop approach. These controls are
comparatively hard to create.
But User Controls (.ascx) are just like pages (.aspx). These are comparatively easy to create but tightly
coupled with respect to User Interface and code. In order to use across multiple projects, we need to
copy and paste to the other project as well.
As in the earlier question, we understood the concept of postback. So, in order to maintain the state
between postbacks, ASP.NET provides a mechanism called view state. Hidden form fields are used to
store the state of objects on client side and returned back to server in subsequent request (as
postback occurs).
If we see the view source for an ASP.NET web page, we will find that hidden form field with Id =
“__VIEWSTATE” something like the following:
In case of Response.Redirect, a new request is generated from client-side for redirected page. It's
a kind of additional round trip. As new request is generated from client, so the new URL is visible to
user in browser after redirection.
While in case of Server.Transfer, a request is transferred from one page to another without
making a round trip from client. For the end user, URL remains the same in browser even after
transferring to another page.
Please Briefly Explain the Usage of Global.asax?
Global.asax is basically an ASP.NET Application file. It’s a place to write code for Application-level
events such as Application start, Application end, Session start and end, Application error, etc. raised
by ASP.NET or by HTTP Modules.
There is a good list of events that are fired but following are few of the important events
in Global.asax:
Application_Init occurs in case of application initialization for the very first time.
Application_Start fires on application start.
Session_Start fires when a new user session starts.
Application_Error occurs in case of an unhandled exception generated from application.
Session_End fires when user session ends.
Application_End fires when application ends or time out.
In order to validate user input, ASP.NET provides validation server controls. All validation controls
inherit from BaseValidator class which contains the common validation properties and methods
like ControlToValidate, Enabled, IsValid, EnableClientScript, ValidationGroup,Valida
te(), etc.
Windows Authentication: This authentication method uses built-in windows security features to
authenticate user.
Forms Authentication: authenticate against a customized list of users or users in a database.
Passport Authentication: validates against Microsoft Passport service which is basically a centralized
authentication service.
What are Session state modes in ASP.NET?
In-Process is the default approach. It stores session state locally on same web server memory where
the application is running.
StateServer mode stores session state in a process other than the one where application is running.
Naturally, it has added advantages that session state is accessible from multiple web servers in a
Web Farm and also session state will remain preserved even web application is restarted.
SQLServer mode stores session state in SQL Server database. It has the same advantages as that of
StateServer.
Custom modes allows to define our custom storage provider.
Off mode disables session storage.
The HTTP protocol is the fundamental protocol of the World Wide Web. HTTP is a stateless
protocol means every request is from new user with respect to web server. HTTP protocol
does not provide you with any method of determining whether any two requests are made by
the same person.
Maintaining state is important in any web application. There are two types of state
management system in ASP.NET.
ASP.NET provides several techniques for storing state information on the client. These
include the following:
view state: ASP.NET uses view state to track values in controls between page requests. It
works within the page only. You cannot use view state value in next page.
control state: You can persist information about a control that is not part of the view state. If
view state is disabled for a control or the page, the control state will still work.
hidden fields: It stores data without displaying that control and data to the user’s browser.
This data is presented back to the server and is available when the form is processed. Hidden
fields data is available within the page only (page-scoped data).
Cookies: Cookies are small piece of information that server creates on the browser. Cookies
store a value in the user’s browser that the browser sends with every page request to the web
server.
Query strings: In query strings, values are stored at the end of the URL. These values are
visible to the user through his or her browser’s address bar. Query strings are not secure. You
should not send secret information through the query string.
Application State:
This object stores the data that is accessible to all pages in a given Web application. The
Application object contains global variables for your ASP.NET application.
Cache Object:
Caching is the process of storing data that is used frequently by the user. Caching increases
your application’s performance, scalability, and availability. You can catch the data on the
server or client.
Session State:
Session object stores user-specific data between individual requests. This object is same as
application object but it stores the data about particular user.
A cookie is a small amount of data that server creates on the client. When a web server
creates a cookie, an additional HTTP header is sent to the browser when a page is served to
the browser. The HTTP header looks like this:
Set-Cookie: message=Hello. After a cookie has been created on a browser, whenever the
browser requests a page from the same application in the future, the browser sends a header
that looks like this:
Cookie: message=Hello
Cookie is little bit of text information. You can store only string values when using a cookie.
There are two types of cookies:
Session cookies
Persistent cookies.
A session cookie exists only in memory. If a user closes the web browser, the session cookie
delete permanently.
A persistent cookie, on the other hand, can available for months or even years. When you
create a persistent cookie, the cookie is stored permanently by the user’s browser on the
user’s computer.
Creating cookie:
protected void btnAdd_Click(object sender, EventArgs e)
{
Response.Cookies[“message”].Value = txtMsgCookie.Text;
}
// Here txtMsgCookie is the ID of TextBox.
Cookie names are case sensitive. Cookie named message is different from setting a cookie
named Message.
The above example creates a session cookie. The cookie disappears when you close your
web browser. If you want to create a persistent cookie, then you need to specify an expiration
date for the cookie.
Response.Cookies[“message”].Expires = DateTime.Now.AddYears(1);
Reading Cookies
void Page_Load()
{
if (Request.Cookies[“message”] != null)
lblCookieValue.Text = Request.Cookies[“message”].Value;
}
// Here lblCookieValue is the ID of Label Control.
HTTP is a stateless protocol; it can't hold the user information on web page. If the user inserts
some information, and move to the next page, that data will be lost and user would not be
able to retrieve the information. For accessing that information we have to store information.
Session provides that facility to store information on server memory. It can support any type
of object to store. For every user, Session data stores separately which means session is
user specific.
Advantages:
- It stores user state and data that are accessible all over the application.
- It is an easy mechanism to implement and it can store any kind of object.
- Session is secured and transparent from user because session object is stored on the
server.
Disadvantages:
- Performance overhead in case of large number of user, because session data is stored in
server memory.
Master pages in ASP.NET works as a template that you can reference this page in all other
content pages. Master pages enable you to define the look and feel of all the pages in your
site in a single location. If you have done changes in master page, then the changes will
reflect in all the web pages that reference master pages. When users request the content
pages, they merge with the master page to produce output that combines the layout of the
master page with the content from the content page.
ContentPlaceHolder control is available only on master page. You can use more than one
ContentPlaceHolder control in master page. To create regions that content pages can fill in,
you need to define ContentPlaceHolder controls in master page as follows:
<asp:ContentPlaceHolder ID=”ContentPlaceHolder1” runat=”server”>
</asp:ContentPlaceHolder>
The page-specific content is then put inside a Content control that points to the relevant
ContentPlaceHolder:
<asp:Content ID=”Content1” ContentPlaceHolderID=”ContentPlaceHolder1” Runat=”Server”>
</asp:Content>
Note that the ContentPlaceHolderID attribute of the Content control points to the
ContentPlaceHolder that is defined in the master page.
The master page is identified by a special @ Master directive that replaces the @ Page
directive that is used for ordinary .aspx pages.
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="CareerRide.master.cs"
Inherits="CareerRide" %>
How can you access the Properties and Controls of Master Pages
from content pages?
You can access the Properties and Controls of Master Pages from content pages. In many
situations you need User’s Name in different content pages. You can set this value inside the
master page and then make it available to content pages as a property of the master page.
We will follow the following steps to reference the properties of master page from content
pages.
Step: 1
Step: 2
Add the @ MasterTypedeclaration to the .aspx content page to reference master properties in
a content page. This declaration is added just below the @ Page declaration as follows:
<%@ Page Title=" TEST" Language="C#" MasterPageFile="~/CareerRide.master"
AutoEventWireup="true" CodeFile="CareerRideWelcome.aspx.cs"
Inherits="CareerRideWelcome" %>
Once you add the @ MasterType declaration, you can reference properties in the master
page using the Master class. For example take a label control that id is ID="Label1"
Label1.Text= Master.UserName ;
For referencing controls in the Master Page we will write the following code.
To reference controls in a master page, call Master.FindControl from the content page.
Page navigation means moving from one page to another page in your web site and another.
There are many ways to navigate from one page to another in ASP.NET.
- Client-side navigation
- Cross-page posting
- Client-side browser redirect
- Client-Side Navigation
Client-side navigation:
Client-side navigation allows the user to navigate from one page to another by using client
side code or HTML. It requests a new Web page in response to a client-side event, such as
clicking a hyperlink or executing JavaScript as part of a button click.
Example:
Drag a HyperLink control on the form and set the NavigateUrl property to the desired
destination page.
HyperLinkControl: Source
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/Welcome.aspx"> Take a test
from CareerRide </asp:HyperLink>
Suppose, this control is placed on a Web page called CareerRide.aspx, and the HyperLink
control is clicked, the browser simply requests the Welcome.aspx page.
Example:
Take an HTML button control on web page. Following is the HTML code for the input button.
<input id="Button1" type="button" value="Go to next page" onclick="return Button1_onclick()" />
When the Button1 is clicked, the client-side method, Button1_onclick will be called. The
JavaScript source for the Button1_onclick method is as follows:
<script language="javascript" type="text/javascript">
function Button1_onclick()
{
document.location="NavigateTest2.aspx";
}
</script>
Cross-page posting:
Example:
Suppose that we have two pages, the first page is FirstPage.aspx and Second page is
SecondPage.aspx. The First Page has a Button and TextBox control and its ID is Button1 and
TextBox1 respectively. A Button control has its PostBackUrl property. Set this property to
“~/SecondPage.aspx”. When the user clicks on Button, the data will send to SecondPage for
processing. The code for SecondPage is as follows:
protected void Page_Load(object sender, EventArgs e)
{
if(Page.PreviousPage == null)
{
Label1.Text = "No previous page in post";
}
else
{
Label1.Text = ((TextBox)PreviousPage._
FindControl("TextBox1")).Text;
}
}
The page that receives the PostBack receives the posted data from the firstpage for
processing. We can consider this page as the processing page.The processing page often
needs to access data that was contained inside the initial page that collected the data and
delivered the PostBack. The previous page’s data is available inside the Page.PreviousPage
property. This property is only set if a cross-page post occurs.
The Page.Response object contains the Redirect method that can be used in your server-side
code to instruct the browser to initiate a request for another Web page. The redirect is not a
PostBack. It is similar to the user clicking a hyperlink on a Web page.
Example:
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect ("Welcome.aspx");
}
In client-side browser redirect method an extra round trip to the server is happened.
Server-side transfer:
In this technique Server.Transfer method is used. The Transfer method transfers the entire
context of a Web page over to another page. The page that receives the transfer generates
the response back to the user’s browser. In this mechanism the user’s Internet address in his
browser does not show the result of the transfer. The user’s address bar still reflects the
name of the originally requested page.
protected void Button1_Click(object sender, EventArgs e)
{
Server.Transfer("MyPage.aspx", false);
}
The Transfer method has an overload that accepts a Boolean parameter called preserve-
Form. You set this parameter to indicate if you want to keep the form and query string data.
- Orientation property of the Menu control sets the display of menu on a Web page to vertical
or horizontal.
- Originally the orientation is set to vertical.
- Client-side validations are done at the client's side with the help of JavaScript and VBScript.
This happens before the web page is sent to the server.
It explains the settings of a Web Parts control that can be included to a specified zone on a
Web page.
In order to enable the impersonation in the web.config file, take the following steps:
- Include the <identity> element in the web.config file.
- Set the impersonate attribute to true as shown below:
<identity impersonate = "true" />
- Globalization is a technique to identify the part of a Web application that is different for
different languages and separate it out from the web application while in localization you try to
configure a Web application so that it can be supported for a specific language or locale.
- These are the objects on ASP.NET pages that run when the Web page is requested.
- Some of these Web server controls, like button and text box, are similar to the HTML
controls.
- Some controls exhibit complex behavior like the controls used to connect to data sources
and display data.
- A HyperLink control does not have the Click and Command events while the LinkButton
control has them, which can be handled in the code-behind file of the Web page.
- The server directs the browser to put some files in a cookie. All the cookies are then sent for
the domain in each request.
- An example of cookie abuse could be a case where a large cookie is stored affecting the
network traffic.
- These are the controls defined by developers and work similar to other web server controls.
- They are a mixture of custom behavior and predefined behavior.
- Used in almost all organization, the Role-based security assign certain privileges to each
role.
- Each user is assigned a particular role from the list.
- Privileges as per role restrict the user's actions on the system and ensure that a user is able
to do only what he is permitted to do on the system.
- HTML server controls are similar to the standard HTML elements like those used in HTML
pages.
- They expose properties and events for programatical use.
- To make these controls programmatically accessible, we specify that the HTML controls act
as a server control by adding the runat="server" attribute.
1. Session Cookie
It resides on the machine of the client for a single session and works until the user logs out of
the session.
2. Persistent Cookie
It resides on the machine of a user for a specified period. This period can be set up manually
by the user.
How would you turn off cookies on one page of your website?
- Permanent cookies are stored on the hard disk and are available until a specified expiration
date is reached.
- To create a cookie that never expires set its Expires property equal to DateTime.maxValue.
Explain Culture and UICulture values.
- Culture value determines the functions like Date and Currency used to format data and
numbers in a Web page.
- UICulture value determines the resources like strings or images loaded in a Web application
for a Web page.
2. RangeValidator - It checks if the value in validated control is within the specified range or
not.
3. CompareValidator - Checks if the value in controls matches some specific values or not.
Early binding means calling a non-virtual method that is decided at a compile time while Late
binding refers to calling a virtual method that is decided at a runtime.
Static assemblies -
Dynamic assemblies -
- They are not saved on disk before execution rather they run directly from memory.
- They can be saved to disk after they have been executed.
Differentiate between Structure and Class.
Explain ViewState.
There are 3 types of Authentication namely Windows, Forms and Passport Authentication.
Forms authentication - It allows you to create your own list of users and validate their
identity when they visit the Web site.
- Server side scripting - All the script are executed by the server and interpreted as needed.
- Client side scripting means that the script will be executed immediately in the browser such
as form field validation, email validation, etc. It is usually carried out in VBScript or JavaScript.
- ASP.NET provides two session state management options - In-Process and Out-of-Process
state management.
- In-Process stores the session in memory on the web server.
- Out-of-Process stores data in an external data source. This data source may be a SQL
Server or a State Server service. Out-of-Process state management needs all objects stored
in session to be serializable.
ASP.NET application with Passport authentication implemented checks the user’s machine
for a current passport authentication cookie. If it is not available, ASP.NET directs the user to
a Passport sign-on page. The Passport service authenticates the user, stores an
authentication cookie on the user’s computer and direct the user to the requested page.
- User doesn’t have to remember separate user names and passwords for various Web sites
- User can maintain his or her profile information in a single location.
- Passport authentication also avail access to various Microsoft services, such as Passport
Express Purchase.
What is caching?
- Caching is the technique of storing frequently used items in memory so that they can be
accessed more quickly.
- By caching the response, the request is served from the response already stored in
memory.
- It’s important to choose the items to cache wisely as Caching incurs overhead.
- A Web form that is frequently used and does not contain data that frequently changes is
good for caching.
- A cached web form freezes form’s server-side content and changes to that content do not
appear until the cache is refreshed.
- The @OutputCache directive’s Duration attribute determines how long the page is cached.
- If the duration attribute is set to 60 seconds, the Web form is cached for 60 seconds; the
server loads the response in memory and retains that response for 60 seconds.
- Any requests during that time receive the cached response.
- Once the cache duration has expired, the next request generates a new response and
cached for another 60 seconds.
A web application resides in the server and serves the client's requests over internet. The
client access the web page using browser from his machine. When a client makes a request,
it receives the result in the form of HTML which are interpreted and displayed by the browser.
A web application on the server side runs under the management of Microsoft Internet
Information Services (IIS). IIS passes the request received from client to the application. The
application returns the requested result in the form of HTML to IIS, which in turn, sends the
result to the client.
- Web application exists in compiled form on the server so the execution speed is faster as
compared to the interpreted scripts.
- ASP.NET makes development simpler and easier to maintain with an event-driven, server-
side programming model.
- Being part of .Framework, it has access to all the features of .Net Framework.
- Content and program logic are separated which reduces the inconveniences of program
maintenance.
- ASP.NET makes for easy deployment. There is no need to register components because
the configuration information is built-in.
- To develop program logic, a developer can choose to write their code in more than 25 .Net
languages including VB.Net, C#, JScript.Net etc.
- Introduction of view state helps in maintaining state of the controls automatically between
the postbacks events.
Content files
Content files include static text, images and can include elements from database.
Program logic
Program logic files exist as DLL file on the server that responds to the user actions.
Configuration file
Configuration file offers various settings that determine how the application runs on the
server.
IIS starts ASP.NET worker process - worker process loads assembly in the memory - IIS
sends the request to the assembly - the assembly composes a response using program logic
- IIS returns the response to the user in the form of HTML.
Server controls
The server controls are Hypertext Markup Language (HTML) elements that include a
runat=server attribute. They 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 allow to connect to the database, execute command and retrieve data from
database.
System components
System components provide access to system-level events that occur on the server.
.NET Framework provides platform for developing windows and web software. ASP.NET is a
part of .Net framework and can access all features implemented within it that was formerly
available only through windows API. .NET Framework sits in between our application
programs and operating system.
.Net Framework Class Library: It provides common types such as data types and object
types that can be shared by all .Net compliant language.
The Common language Runtime: It provides services like type safety, security, code
execution, thread management, interoperability services.
An assembly exists as a .DLL or .EXE that contains MSIL code that is executed by CLR. An
assembly contains interface and classes, it can also contain other resources like bitmaps,
files etc. It carries version details which are used by the CLR during execution. Two
assemblies of the same name but with different versions can run side-by-side enabling
applications that depend on a specific version to use assembly of that version. An assembly is
the unit on which permissions are granted. It can be private or global. A private assembly is
used only by the application to which it belongs, but the global assembly can be used by any
application in the system.
The four parts of an assembly are:
Assembly Manifest - It contains name, version, culture, and information about referenced
assemblies.
Resources - Files such as BMP or JPG file or any other files required by application.
.Net allows developers to write program logic in at least 25 languages. The classes written in
one language can be used by other languages in .Net. This service of .Net is possible through
CTS which ensure the rules related to data types that all language must follow. It provides set
of types that are used by all .NET languages and ensures .NET language type compatibility.
It is the folder that contains web applications. The folder that has been published as virtual
folder by IIS can only contain web applications.
A web application starts when a browser requests a page of the application first time. The
request is received by the IIS which then starts ASP.NET worker process (aspnet_wp.exe).
The worker process then allocates a process space to the assembly and loads it. An
application_start event occurs followed by Session_start. The request is then processed by
the ASP.NET engine and sends back response in the form of HTML. The user receives the
response in the form of page.
The page can be submitted to the server for further processing. The page submitting triggers
postback event that causes the browser to send the page data, also called as view state to
the server. When server receives view state, it creates new instance of the web form. The
data is then restored from the view state to the control of the web form in Page_Init event.
The data in the control is then available in the Page_load event of the web form. The cached
event is then handled and finally the event that caused the postback is processed. The web
form is then destroyed. When the user stops using the application, Session_end event occurs
and session ends. The default session time is 20 minutes. The application ends when no user
accessing the application and this triggers Application_End event. Finally all the resources of
the application are reclaimed by the Garbage collector.
ASP.NET has introduced view state to preserve data between postback events. View state
can't avail data to other web form in an application. To provide data to other forms, you need
to save data in a state variable in the application or session objects.
Application State
Data stored in the application object can be shared by all the sessions of the application.
Application object stores data in the key value pair.
Session State
Session State stores session-specific information and the information is visible within the
session only. ASP.NET creates unique sessionId for each session of the application.
SessionIDs are maintained either by an HTTP cookie or a modified URL, as set in the
application’s configuration settings. By default, SessionID values are stored in a cookie.
Application_Start:
This event occurs when the first user visits a page of the application.
Application_End:
This event occurs when there are no more users of the application.
Application_BeginRequest:
This occurs at the beginning of each request to the server.
Application_EndRequest:
Occurs at the end of each request to the server.
Session_Start:
This event occurs every time when any new user visits.
Session_End:
Occurs when the users stop requesting pages and their session times out.
Page_Init
Page_Load
Page_PreRender
Page_Unload
Page_Disposed
Page_Error
Page_AbortTransaction
Page_CommitTransaction
Page_DataBinding
ASP.NET offers many server controls like button, textbox, DropDownList etc. Each control
can respond to the user's actions using events and event handler mechanism.
Cached events
These events are processed when a postback event occurs.
Validation events
These events occur just before a page is posted back to the server.
The session time-out value is specified in the web.config file within sessionstate element. You
can change the session time-out setting by changing value of timeout attribute of sessionstate
element in web.config file.
In ASP.NET, when IIS receives a request, IIS uses aspnet_isapi.dll to call the ASP.NET
worker process (aspnet_wp.exe). The ASP.NET worker process loads the Web application's
assembly, allocating one process space, called the application domain, for each application.
This is the how ASP.NET maintains process isolation for each Web application.
Define namespace.
Namespaces are the way to organize programming code. It removes the chances of name
conflict. It is quite possible to have one name for an item accidentally in large projects those
results into conflict. By organizing your code into namespaces, you reduce the chance of
these conflicts. You can create namespaces by enclosing a class in a Namespace...End
Namespace block.
You can use namespaces outside your project by referring them using References dialog box.
You can use Imports or using statement to the code file to access members of the
namespaces in code.
What are the options in ASP.NET to maintain state?
Cookies
A cookie is a small text file on the client machine either in the client’s file system or memory of
client browser session. Cookies are not good for sensitive data. Moreover, Cookies can be
disabled on the browser. Thus, you can’t rely on cookies for state management.
View State
Each page and each control on the page has View State property. This property allows
automatic retention of page and controls state between each trip to server. This means
control value is maintained between page postbacks. Viewstate is implemented using
_VIEWSTATE, a hidden form field which gets created automatically on each page. You can’t
transmit data to other page using view state.
Querystring
Query strings can maintain limited state information. Data can be passed from one page to
another with the URL but you can send limited size of data with the URL. Most browsers allow
a limit of 255 characters on URL length.
Application State
The data stored in the application object can be shared by all the sessions of the application.
Application object stores data in the key value pair.
Session State
Session State stores session-specific information and the information is visible within the
session only. ASP.NET creates unique sessionId for each session of the application.
SessionIDs are maintained either by an HTTP cookie or a modified URL, as set in the
application’s configuration settings. By default, SessionID values are stored in a cookie.
Database
Database can be used to store large state information. Database support is used in
combination with cookies or session state.
Server events
Server control events are handled in the server whereas HTML control events are handled in
the page.
State management
Server controls can maintain data across requests using view state whereas HTML controls
have no such mechanism to store data between requests.
Browser detection
Server controls can detect browser automatically and adapt display of control accordingly
whereas HTML controls can’t detect browser automatically.
Properties
Server controls contain properties whereas HTML controls have attributes only.
CompareValidator: This allows checking if data of one control match with other control.
1. Hyperlink control
2. Response.Redirect method
3. Server.Transfer method
4. Server.Execute method
5. Window.Open script method
To open a page in a new window, you have to use client script using onclick="window.open()"
attribute of HTML control.
Define caching.
Caching is the technique of storing frequently used items in memory so that they can be
accessed more quickly. Caching technique allows to store/cache page output or application
data on the client on the server. The cached information is used to serve subsequent
requests that avoid the overhead of recreating the same information. This enhances
performance when same information is requested many times by the user.
Define cookie.
A cookie is a small file on the client computer that a web application uses to maintain current
session information. Cookies are used to identity a user in a future session.
What is delegate?
A delegate acts like a strongly type function pointer. Delegates can invoke the methods that
they reference without making explicit calls to those methods. It is type safe since it holds
reference of only those methods that match its signature. Unlike other classes, the delegate
class has a signature. Delegates are used to implement event programming model in .NET
application. Delegates enable the methods that listen for an event, to be abstract.
Exceptions or errors are unusual occurrences that happen within the logic of an application.
The CLR has provided structured way to deal with exceptions using Try/Catch block.
ASP.NET supports some facilities to handling exceptions using events suck as Page_Error
and Application_Error.
What is impersonation?
Impersonation means delegating one user identity to another user. In ASP.NET, the
anonymous users impersonate the ASPNET user account by default. You can use <identity>
element of web.config file to impersonate user.
Example:
<identity impersonate="true"/>
The code that runs under the guidance of common language runtime (CLR) is called
managed code. The versioning and registration problem which are formally handled by the
windows programming are solved in .Net with the introduction of managed code. The
managed code contains all the versioning and type information that the CLR use to run the
application.
Merge modules are the deployment projects for the shared components. If the components
are already installed, the modules merge the changes rather than unnecessarily overwrite
them. When the components are no longer in use, they are removed safely from the server
using Merge modules facility.
Satellite assembly is a kind of assembly that includes localized resources for an application.
Each satellite assembly contains the resources for one culture.
Secured Socket Layer (SSL) ensures a secured web application by encrypting the data sent
over internet. When an application is using SSL facility, the server generates an encryption
key for the session and page is encrypted before it sent. The client browse uses this
encryption key to decrypt the requested Web page.
A session starts when the browser first request a resources from within the application. The
session gets terminated when either browser closed down or session time out has been
attained. The default time out for the session is 20 minutes.
Define Tracing.
Tracing is the way to maintain events in an application. It is useful while the application is in
debugging or in the testing phase. The trace class in the code is used to diagnose problem.
You can use trace messages to your project to monitor events in the released version of the
application. The trace class is found in the System.Diagnostics namespace. ASP.NET
introduces tracing that enables you to write debug statements in your code, which still remain
in the code even after when it is deployed to production servers.
ASP.NET preserves data between postback events using view state. You can save a lot of
coding using view state in the web form. ViewState serialize the state of objects and store in a
hidden field on the page. It retains the state of server-side objects between postbacks. It
represents the status of the page when submitted to the server. By default, view state is
maintained for each page. If you do not want to maintain the ViewState, include the directive
<%@ Page EnableViewState="false" %> at the top of an .aspx page or add the attribute
EnableViewState="false" to any control. ViewState exist for the life of the current page.
It is the process space within which ASP.NET application runs. Every application has its own
process space which isolates it from other application. If one of the application domains
throws error it does not affect the other application domains.
List down the sequence of methods called during the page load.
MSIL is the Microsoft Intermediate Language. All .Net languages' executable exists as MSIL
which gets converted into machine specific language using JIT compiler just before execution.
Response.Redirect vs Server.Transfer.
Server.Transfer is only applicable for aspx files. It transfers page processing to another page
without making round-trip back to the client's browser. Since no round trips, it offers faster
response and doesn't update client url history list.
Response.Redirect is used to redirect to another page or site. This performs a trip back to the
client where the client’s browser is redirected to the new page.
ASP.NET provides In-Process and Out-of-Process state management. In-Process stores the
session in memory on the web server. Out-of-Process Session state management stores data
in an external data source such as SQL Server or a State Server service. Out-of-Process
state management requires that all objects stored in session are serializable.
Cookie.Discard Property when true, instructs the client application not to save the Cookie on
the user's hard disk when a session ends.
What is AutoPostback?
AutoPostBack automatically posts the page back to the server when state of the control is
changed.
Explain login control and form authentication.
Login controls encapsulate all the features offered by Forms authentication. Login controls
internally use FormsAuthentication class to implement security by prompting for user
credentials validating them.
- Database connections
- Error Page setting
- Session States
- Error Handling
- Security
- Trace setting
- Culture specific setting
Destructors are called in reverse order of constructors. Destructor of most derived class is
called followed by its parent's destructor and so on till the topmost class in the hierarchy.
What is break mode? What are the options to step through code?
Break mode lets you to observe code line to line in order to locate error. VS.NET provides
following option to step through code.
- Step Into
- Step Over
- Step Out
- Run To Cursor
- Set Next Statement
Explain how to retrieve property settings from XML .config file.
Create an instance of AppSettingsReader class, use GetValue method by passing the name
of the property and the type expected. Assign the result to the appropriate variable.
Global Assembly Cache is the place holder for shared assembly. If an assembly is installed to
the Global Assembly Cache, the assembly can be accessed by multiple applications. In order
to install an assembly to the GAC, the assembly must have to be signed with strong name.
Managed code runs under the safe supervision of common language runtime. Managed code
carries metadata that is used by common language runtime to offer service like memory
management, code access security, and cross-language accessibility.
Unmanaged code doesn't follow CLR conventions and thus, can't take the advantages of
.Framework.
This means multiple version of same assembly to run on the same computer. This feature
enables to deploy multiple versions of the component.
Resource files contains non-executable data like strings, images etc that are used by an
application and deployed along with it. You can changes these data without recompiling the
whole application.
What is reflection?
Reflection is a mechanism through which types defined in the metadata of each module can
be accessed. The System.Reflection namespaces contains classes that can be used to
define the types for an assembly.
Satellite Assemblies are the special kinds of assemblies that exist as DLL and contain culture
specific resources in a binary format. They store compiled localized application resources.
They can be created using the AL utility and can be deployed even after deployment of the
application. Satellite Assemblies encapsulate resources into binary format and thus makes
resources lighter and consume lesser space on the disk.
What is CAS?
CAS is very important part of .Net security system which verifies if particular piece of code is
allowed to run. It also determines if piece of code have access rights to run particular
resource. .NET security system applies these features using code groups and permissions.
Each assembly of an application is the part of code group with associated permissions.
- It populates the table in the dataset from the data store and also pushes the changes in the
dataset back into the data store.
Methods of DataAdapter:
Fill - Populates the dataset object with data from the data source
FillSchema - Extracts the schema for a table from the data source
Update - It is use to update the data source with the changes made to the content of the
dataset
Impersonation is a technique to access application resources using the identity of some other
user.
2. Form Authentication: It’s a custom security based on roles and user accounts created
specifically for an application.
URL authorization:
URL authorization is performed by the UrlAuthorizationModule
It maps users and roles to URLs in ASP.NET applications.
File authorization:
File authorization is performed by the FileAuthorizationModule.
It checks the access control list of the .aspx or .asmx handler file to determine whether a user
should have access to the file.
Connection pool is created when we open connection first time. When a new connection is
created with same connection string as the first one, it reuses the same and existing
connection object from the pool without creating a new one.
If the connection string is different then a new connection pooling will be created, thus won't
use the existing connection object.
By default, we have connection pooling enabled in .Net. To disable connection pooling, set
Pooling = false in the connection string.
To enhance performance and reduce the load of creating new objects, instead re using
existing objects stored in memory pool. Object Pool is a container of objects that are for use
and have already been created. Whenever an object creation request occurs, the pool
manager serves the request by allocating an object from the pool. This minimizes the memory
consumption and system's resources by recycling and re-using objects. When the task of an
object is done, it is sent to the pool rather than being destroyed. This reduces the work for
garbage collector and fewer memory allocations occur.
Clean up activities are entrusted to .NET Garbage collector in .NET. But unmanaged
resources such as File, COM object etc. are beyond the scope of Garbage collector. For
these type of objects, we have Finalize method where clean up code for unmanaged
resources can be put.
Advantages:
Cookies are stored in client thus no burden as far as space is concern.
Cookies are light weight and involves no complexities while using.
Disadvantages:
Most browsers have put a check on the size of a cookie.
Cookies can be disabled on the client thus limiting the use of cookies.
Cookies are tampered prone and thus associate security concern.
Cookies can expire thus leading to inconsistency.
Next Page »
ASP.NET application life cycle and events processing
ASP.NET application life cycle - This section covers all about ASP.NET application life cycle and
events processing
ASP.Net Server Control vs HTML control
ASP.Net Server Control vs HTML control - This article includes differences between Server Control
and HTML control in ASP.NET.
ASP.NET Application and Session state variables, ways to preserve page data.
ASP.NET Application and Session - Here are the answers of interview questions on the topic
ASP.NET Application and Session state variables.