What is IIS?
IIS (Internet Information Services) is one of the
most powerful web servers from Microsoft that is used to host your ASP.NET Web
application. IIS has its own ASP.NET Process Engine to handle the ASP.NET request.
So, when a request comes from client to server, IIS takes that request and
processes it, and sends the response back to clients.
Internet Information Server (IIS) includes a set of
programs for building and administering Web applications, search engines, and
support for writing Web-based applications that access databases such as SQL
Server. With IIS, you can make your computer work as a Web server and
provides the functionality to develop and deploy ASP.NET Web applications on
the server. You can also set security for a particular Website for specific
Users and Computers in order to protect it from unauthorized access.
IIS helps organizations to increase Web sites and
application availability while lowering system administration and the cost of
deployment. IIS 7.5 supports HTTP, HTTPS, FTP, FTPS, SMTP and NNTP.
1. Worker Process
2. Application Pool
Worker
Process: Worker Process (w3wp.exe) runs the ASP.Net
application in IIS. This process is
responsible for managing all the requests and
responses that are coming from the client system. All the
ASP.Net functionality runs under the scope of the
worker process. When a request comes to the server
from a client, the worker process is responsible for
generating the request and response. In a single
word, we can say the worker process is the heart of the ASP.NET Web Application which runs on IIS.Worker
the process is the heart of the ASP.NET Web Application
which runs on IIS.
Application
Pool: The application pool is the container of the worker
process. Application pools are used
to separate sets of IIS worker processes that share
the same configuration. Application pools enable
better security, reliability, and availability for
any web application. The worker process serves as
the process boundary that separates each application
pool so that when one worker process or
application is having an issue or recycles, other
applications or worker processes are not affected.
This makes sure that a particular web application
doesn’t impact other web applications as they are
configured into different application pools.
IIS application pools also provide a bunch of
advanced settings. These impact the behavior of w3wp and your IIS worker
process. Including things like what Windows user account it runs as, auto
restarting of the process, auto shutdown, and more. It is also possible for one
IIS application pool to create multiple IIS worker processes in what is called
a web garden.
Now let’s have a look at how IIS process the request
when a new request comes up from a client.
If we look into the IIS Architecture, we can divide
them into Two-Layer
Kernel level
User-level
Now, Kernel mode is introduced with IIS 6.0, which contains HTTP.SYS. So whenever a request comes from Client to Server, it will hit HTTP.SYS First. HTTP.SYS is Responsible for pass the request to the particular Application pool
How
HTTP.SYS does come to know where to send the request?
This is not a random pick. Whenever we create a new
Application Pool, the ID of the Application Pool is being generated, and it’s
registered with the HTTP.SYS. So whenever HTTP.SYS Receives the request from
any web application, checks for the Application Pool, and based on the
application pool it sends the request further in. So, these were the first steps
of IIS Request Processing.
Till now, the Client Requested some information and the request came to the Kernel level of IIS means at HTTP.SYS. HTTP.SYS has
identified the application pool to send the request. Now, let’s see how this
request moves from HTTP.SYS to Application Pool. In User Level of IIS, we have
Web Admin Services (WAS) which takes the request from HTTP.SYS and pass it to
the respective application pool.
When the Application pool receives the request, it just
passes the request to the worker process (w3wp.exe). The worker process “w3wp.exe”
looks up the URL of the request to load the correct ISAPI extension. ISAPI extensions
are the IIS way to handle requests for different resources. Once ASP.NET is
installed, it installs its own ISAPI extension (aspnet_isapi.dll) and adds the
mapping into IIS.
When the Worker process loads the aspnet_isapi.dll, it
starts an HTTPRuntime, which is the entry point of an application. HTTPRuntime
is a class that calls the ProcessRequest method to start Processing the
request.
When this method is called, a new instance of
HTTPContext is created. Which is accessible using HTTPContext.Current Properties.
This object remains alive during the lifetime of the object requests. Using
HttpContext.Current we can access some other objects like Request, Response,
Session, etc.
After that HttpRuntime loads an HttpApplication
object with the help of HttpApplicationFactory class. Every request should pass
through the corresponding HTTPModule to reach to HTTPHandler, this list of a
module is configured by the HTTP application.
Now, the concept comes called “HTTPPipeline.” It is
called a pipeline because it contains a set of HttpModules ( For Both
Web. config and Machine. config level) that intercept the request on its way to
the HttpHandler. HTTP modules are classes that have access to the incoming
request. We can also create our HTTPModule if we need to handle anything during
upcoming requests and responses.
HTTP modules are classes that have access to the
incoming request. We can also create our HTTPModule if we need to handle
anything during upcoming requests and responses.
HTTP Handlers are the endpoints in the HTTP pipeline.
All request that is passing through the HTTPModule should reach HTTPHandler.
The HTTP Handler generates the output for the requested resource. So, when we
were requesting any aspx web pages, it returns the corresponding HTML
output.
All the request now passes from HTTP module to
respective HTTPHandler then the method and the ASP.NET Page life cycle starts.
This ends the IIS Request processing and starts the ASP.NET Page Lifecycle.
When the client requests some information from a
web server, the request first reaches HTTP.SYS of IIS. HTTP.SYS then sends the
request to a particular Application Pool. Application Pool then forwards the
request to the worker process to load the ISAPI Extension which will create an
HTTPRuntime Object to Process the request via HTTPModule and HTTP handler. After
that, the ASP.NET Page LifeCycle events start.
-----------------------------------------------------------------------------------------------------------------------------Asp.net
page life cycle:
When an ASP.NET page runs, the page goes through a life cycle in which it
performs a series of processing steps. These include initialization,
instantiating controls, restoring and maintaining state, running event handler
code, and rendering. The following are the various stages or events of the ASP.Net
page life cycle.
PreInit
Check the IsPostBack property to determine whether
this is the first time the page is being processed.
Create or re-create dynamic controls.
Set a master page dynamically.
Set the Theme property dynamically.
Note
If the request is a postback then the values of the controls have not yet been restored from the view state. If you set a control property at this stage, its value might be overwritten in the next event.
Init
This event fires after each control have been
initialized.
Each control's Unique ID is set and any skin
settings have been applied.
Use this event to read or initialize control
properties.
The "Init" event is fired first for the
bottom-most control in the hierarchy and then fired up the hierarchy until it
is fired for the page itself.
InitComplete
- Until
now the view state values are not yet loaded, hence you can use this event
to make changes to the view state that you want to ensure are persisted
after the next postback.
- Raised
by the Page object.
- Use this event for processing tasks that require all initialization to be complete.
On
Preload
- Raised
after the page loads view state for itself and all controls, and after it
processes postback data that is included with the Request instance.
- Before
the Page instance raises this event, it loads view state for itself and
all controls and then processes any Postbank data included with the
Request instance.
- Loads
View State: View State data are loaded to controls.
- Loads
Postback data: Postback data are now handed to the page controls.
Load
- The
Page object calls the On Load method on the Page object, and then
recursively does the same for each child control until the page and all
controls are loaded. The Load event of individual controls occurs after
the Load event of the page.
- This
is the first place in the page lifecycle that all values are restored.
- Most
code checks the value of IsPostBack to avoid unnecessarily resetting
state.
- You
may also call Validate and check the value of Is Valid in this method.
- You
can also create dynamic controls in this method.
- Use the On Load event method to set properties in controls and establish database connections
Control
Post Back Event(s)
- ASP.NET
now calls any events on the page or its controls that caused the PostBack
to occur.
- Use
these events to handle specific control events, such as a Button control's
Click event or a Textbox control's TextChanged event.
- In
a PostBack request, if the page contains validator controls, check the
IsValid property of the Page and of individual validation controls before
performing any processing.
- This is just an example of a control event. Here is the button click event that caused the PostBack.
Load
Complete
- Raised
at the end of the event-handling stage.
- Use
this event for tasks that require that all other controls on the page be
loaded.
OnPreRender
- Raised
after the Page object has created all controls that are required in order
to render the page, including child controls of composite controls.
- The
Page object raises the PreRender event on the Page object, and then recursively
does the same for each child control. The PreRender event of individual
controls occurs after the PreRender event of the page.
- The
PreRender event of individual controls occurs after the PreRender event of
the page.
- Allows
final changes to the page or its control.
- This
event takes place before saving ViewState, so any changes made here are
saved.
- For
example: After this event, you cannot change any property of a button or
change any ViewState value.
- Each
data-bound control whose DataSourceID property is set calls its DataBind
method.
- Use
the event to make final changes to the contents of the page or its
controls.
OnSaveStateComplete
- Raised
after view state and control state have been saved for the page and for
all controls.
- Before
this event occurs, ViewState has been saved for the page and for all
controls.
- Any
changes to the page or controls at this point will be ignored.
- Use this event to perform tasks that require the view state to be saved, but that do not make any changes to controls.
Render
Method
- This
is a method of the page object and its controls (and not an event).
- The
Render method generates the client-side HTML, Dynamic Hypertext Markup
Language (DHTML), and script that are necessary to properly display a
control at the browser.
UnLoad
- This
event is used for cleanup code.
- At
this point, all processing has occurred and it is safe to dispose of any
remaining objects, including the Page object.
- Cleanup
can be performed on:
- Instances
of classes, in other words, objects
- Closing
opened files
- Closing
database connections.
- This
event occurs for each control and then for the page.
- During
the unload stage, the page and its controls have been rendered, so you
cannot make further changes to the response stream.
- If
you attempt to call a method such as the Response. Write method then the
page will throw an exception.
ASP.NET provides us
with 2 ways to manage the state of an application. It is basically divided into 2 categories:
- Client-Side State Management.
- Server-Side State Management.
Client-Side State
Management:
1) View State:
View State can be used to maintain the
State at a page level. The term "Page Level" means that the
information is being stored for a specific page and until that specific page is
active (i.e. the page which is being currently viewed by the user). Once the
user is re-directed or goes to some other page, the information stored in the
View State gets lost.
It basically makes use of a "Dictionary Object" to store data, which means that the information is stored in a key and value pair. It stores this information in a hidden field on the page itself in a hashed format. A View State can store a string value only of a specific length. If the length is exceeded then the excess information is stored in another hidden field.
<input
type=""hidden"" id=""__VIEWSTATE""
name=""__VIEWSTATE""
value=""dDw3GTg2NTI5MDEDC0y3="">
protected void Page_Load(object
sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["PageHitCounter"]
= 0;
}
}
protected void
btnPageHitCounter_Click(object sender, EventArgs e)
{
ViewState["PageHitCounter"]
= Convert.ToInt32(ViewState["PageHitCounter"]) + 1;
Response.Write("The number of
postbacks are - " + ViewState["PageHitCounter"].ToString());
}
More detail:
When
a client makes a request for a .aspx page it will be processed at the server and the
result produced is concatenated as a string value along with some # values in
it. These concatenated values are converted as a base 64 format which is not secure
and unreadable format. We cannot read, it is simply encoded in base 64 format which
is not readable by the user. These base 64 values are stored in one or more hidden fields
by the server and sent to the client along with other form contents. When a user
adds/modifies, the content resubmits the form to the server. Server 1st reads the values of the hidden fields so that it retains the last given values (acts as a
stateful) and retains the same process with new and old values. This process is
repeated as long as the user working with the current page.
Advantages of using a
View State
- It is very simple to use.
- Data is stored in hashed format
and hence a layman won't be able to understand the value of the View State
(It still can be hacked by Hackers, so to make it more secure we should
try to store the value in an encrypted format.) It is customizable, as shown above.
Disadvantages of using
a View State
- Information is not encrypted,
so it can be easy for a Hacker to get its value.
- Cannot be used to store
sensitive data (eg: Passwords, Credit Card Pins, etc).
- Might make a page heavy if lots
of data is stored in View State.
Cookies:
It is
nothing but a text file that is stored on the client's machine.
When the
user sends a request to the server, the server creates a cookie and attaches a
header, and sends it back to the user along with the response. The browser
accepts the cookie and stores it at a specific location on the client's
machine. Even large sites like Gmail, Facebook, Yahoo use cookies.
Type of Cookies:
Persist
Cookie:
These cookies are stored on your
computer's hard disk. They stay on your hard disk and can be accessed by web servers until they are
deleted or have expired. It is saved as a text file in the file system of the
client computer usually under the Temporary Internet Files folder.
Persistent Cookies are Permanent Cookies stored as a text file in the hard disk
of the computer. A cookie that has not had expired time is known as a Persistence
cookie.
HttpCookie aCookie = new
HttpCookie("Session");
aCookie.Value =
DateTime.Now.ToString();
aCookie.Expires =
DateTime.Now.AddDays(1);
Response.Cookies.Add(aCookie);
Response.Cookies["UserName"].Value = "PrasannaK";
Response.Cookies["UserName"].Expires
= DateTime.Now.AddDays(1);
Non-Persist
Cookie – Non-persistent cookies also called Session cookies or In-memory cookies are saved only while your web
browser is running. They can be used by a web server only until you close your browser.
They are not saved on your disk.
(or)
A cookie that is available as long as the user is working with the current session is known as an In-memory key. A cookie has expired
time Which is called a Non-Persist Cookie
(or)
Non-Persistent cookies are temporary. They are also called in-memory cookies
and session-based cookies. These cookies are active as long as the browser
remains active, in other words, if the browser is closed then the cookies
automatically expire.
Response.Cookies["nameWithNPCookies"].Value
= "This is A Non Persistance Cookie";
HttpCookie aCookie = new
HttpCookie("Session");
aCookie.Value =
DateTime.Now.ToString();
aCookie.Expires =
DateTime.Now.AddDays(1);
Response.Cookies.Add(aCookie);
How to read a cookie:
if
(Request.Cookies["NonPersistance"] != null)
Label2.Text =
Request.Cookies["NonPersistance"].Value;
Cookie's common property
- Domain
=> Which is used to associate cookies to the domain.
- Secure
=> We can enable secure cookie to set true(HTTPs).
- Value
=> We can manipulate individual cookies.
- Values
=> We can manipulate cookies with key/value pair.
- Expires
=> Which is used to set expire date for the cookies.
Advantages of Cookie
- Its
clear text so the user can able to read it.
- We
can store user preference information on the client machine.
- It's an easy way to maintain.
- Fast
accessing.
- Store
information temporarily
- It's
just a simple small-sized text file
- Can
be changed depending on the requirements
- User
Preferred
- Requires
only a few bytes or KBs of space for creating cookies
Disadvantages of Cookie
- If the user clears the cookie information we can't get it back.
- No
security.
- Each
request will have cookie information on the page.
- A
user can disable cookies using browser settings.
- Since
the cookies are stored on the client's machine, there are chances that if
the client's machine is hacked then the hacker can view these cookie
values. Hence we should not store sensitive information in cookies.
How to clear the cookie
information?
- We
can clear cookie information from client machines on the cookie folder
- To
set expires to cookie object
userInfo.Expires = DateTime.Now.AddHours(1);
It will clear the
cookie with a one-hour duration.
Hidden Fields:
It is the also control that does not render anything on
the web page at the client browser but can be used to store some information on the
web page at a page level, which is similar to a View State. The value of the
Hidden Field is sent along in the HTTP Form Collection along with the value of
other controls.
Hidden field stores value at the page level.
Advantages
Very simple to use.
Hidden Fields store the value in the page itself;
hence do not use server resources.
Disadvantages
Will make a page heavy, if too many Hidden Fields
are used to store data.
Cannot store sensitive data, as the value that is
stored is neither hashed nor encrypted.
Query String:
The values are stored in the URL that is visible to the users. It is very simple to use and can be used to send data across pages. It stores information in a key-value pair. A "?" signature is used to append the key and value to the page URL.
This management technique basically makes use of the following,
Application State
Session State
Application
State
If the information that we want to be accessed or
stored globally throughout the application, even if multiple users access the
site or application at the same time, then we can use an Application Object for
such purposes.
It stores information as a Dictionary Collection in
key-value pairs. This value is accessible across the pages of the application/website.
There are 3 events of the Application which are as
follows
Application_Start
Application_Error
Application_End
In global.asax file:
<%@ Application Language="C#" %>
<script runat="server">
void Application_Start(object sender, EventArgs e)
{
Application["UserCount"] = 0;
}
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
}
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
}
void Session_Start(object sender, EventArgs e)
{
Application.Lock();
int count = (int)Application["UserCount"];
Application["UserCount"] = count + 1;
Application.UnLock();
}
void Session_End(object sender, EventArgs e)
{
Application.Lock();
int count = (int)Application["UserCount"];
Application["UserCount"] = count - 1;
Application.UnLock();
}
</script>
Session State
The session is one of the most common ways that is being
used by developers to maintain the state of the application. The Session
basically stores the values as a dictionary collection in key/value pairs. It is
a secure way of storing data since the data will never be passed to the
client.
For each and every user, a separate Session is created, and each and every Session has its Unique ID. This ID is being stored in the client's machine using cookies. When we store data to Session state, a session cookie named is ASP.NET_SessionId is created automatically. If there are multiple users who are accessing a web application, then for each user a separate Session is created. If a single user logs in and logs out the Session is killed, then if the same user again logs into the application, then a new Session ID is being created for the same user.
The Session has a default timeout value (20
minutes). We can also set the timeout value for a session on the web. config
file.
|
Session
Properties
|
Description |
|
CookieMode
|
It
specifies whether cookieless sessions are enabled. Possible values are
AutoDetect, Use Cookies, UseDeviceProfile, and Use Uri. |
|
Session
ID
|
It
provides a unique session identifier. It is secure enough and can't be
decoded or hampered. When clients communicate with the server, only the session id is
transmitted, between them. |
|
Count |
It
provides the number of items in Session state. |
|
IsCookieless
|
Provides
the information whether sessions are cookieless or not. |
|
IsNewSession
|
It
determines whether the session is new or not. |
|
IsReadOnly
|
It
determines whether the Session state is read-only. |
|
Keys |
Provides
the list of item names stored in Session state.
|
|
Mode |
It
determines the current Session state store provider. Possible values are
Custom, InProc, Off, SqlServer, and State Server. |
Abandon: It
is used to end a user session.
Clear: It
clears all items from Session state.
Remove: This method is used to remove a particular item from the Session state.
using System;
using System. Web;
public partial class _Default: System.Web. UI.Page
{
protected
void Page_Load(object sender, EventArgs e)
{
string
info;
info =
"CookieMode =: "+Session.CookieMode.ToString() +
"</br>"; ;
info
+= "Count =: "+ Session.Count.ToString() + "</br>"; ;
info
+= "IsCookieless =: " + Session.IsCookieless.ToString() +
"</br>"; ;
info
+= "IsNewSession =: " + Session.IsNewSession.ToString() +
"</br>"; ;
info
+= "IsReadOnly =: " + Session.IsReadOnly.ToString() +
"</br>"; ;
info
+= "Keys =: "+Session.Keys.Count + "</br>"; ;
info
+= "Mode =: "+Session.Mode.ToString() + "</br>"; ;
info += "SessionID =: " +
Session.SessionID.ToString() + "</br>"; ;
Label1.Text = info;
}
}
----o/P---
void Page_Load()
{
Label1.Text =
Application["UserCount"];ToString();
}
|
Session State |
Application State |
|
The session object is user-specific. |
It works at the application level rather
than the user level. |
|
Session state is stored in inProc and
outProc |
Application state is stored only in
the memory on the server. |
|
Session
object depends upon cookie or can be cookie-less. |
Application state does not depend
upon the client's cookies |
|
Session
state has scope to the current browser only. |
Application state does not depend upon
the current browser. |
|
A user gets session_id when he enters
into the website |
The ID is common throughout the
application |
|
The ID will be deleted when he leaves
the application |
The ID is common throughout the
application |
|
The ID is used to store a large
amount of data and can retrieve from one page to another page |
It is used to store all gobal.asax
& HTTP handlers. |
|
When the user re-enters the website
he will get with different session_id |
The ID is shared among all the users. |
There are various ways in which we can store a
session and they are as follows:
OFF
InProc
State Server
SQL Server
OFF
If
we do not want to use sessions in our application, then we can set the mode as
"OFF".
InProc Session Mode
This is the default mode that is used in ASP.NET to
store session variables.
The values are stored in the memory on the webserver or stores the session
value in the process in which the ASP.NET application is running or stores in
the application worker process (aspnet_wp.exe) in the application domain. The
Worker Process is dependent on the IIS server version. The memory location was
handled by the ASP.NET worker thread.
Since it is stored in the same process, it provides high performance as
compared to other modes.
It is handled by a worker process in the application pool.
It can be very useful for small websites where the no of users are very less
It does not require any configuration. It is the easiest option to implement because
you don’t need to configure anything.
<configuration>
<sessionstate mode="InProc"
cookieless="false" timeout="10"
stateConnectionString="tcpip=127.0.0.1:80808"
sqlConnectionString="Data Source=.\SqlDataSource;User
ID=userid;Password=password"/>
</configuration>
Advantages:
It is very fast among all the modes.
No need for serialization
Implementation is very easy
Disadvantages:
Though
it is the fastest, more session data more users can affect the performance
because of its memory.
We can’t use it in the Web garden or web farm.
It will lose the data if we restart the server.
State Server:
It is also known as out proc session mode.
It is basically for the serialization and
deserialization of objects
It is slower than InProc mode, as it stores the data
as an external process.
It is maintained on different systems and the
session state is serialized and stored in the memory in a separate process.
In StateServer session mode the data is stored
in the separate server as a stand-alone Window Service which is
independent of IIS. The State server could be located on the same server or on
a different server. Since in-state server session mode, the session data
exists on the different server so when the user tries to retrieve the
session, our application hits a different process this will increase the
cost of data access.
We use this state server session to avoid
unnecessary session data loss during the restart of the webserver, but need to
serialize the data before storing it in session mode.
Type service.msc->Asp.net state service->Automatic
IP->127.0.0.1 & port->42424(Default)
If we use this mode, then a separate Windows Service
which runs in a different process stores the Session. It basically isolates the
Session from the ASP.NET running process. It provides less performance as compared
to the InProc mode.
By default, the "Startup Type" of the ASP.NET state service is set to Manual; we need to set it to Automatic.
<configuration><sessionstate mode="stateserver" cookieless="false"
timeout="10"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="Data
Source=.\SqlDataSource;User ID=userid;Password=password"/>
</configuration>
Note:
Web Garden: Web application deployed on a server with multiple processors.A Web garden contains multiple ASP.NET worker processes. Each CPU in the SMP server handles a separate ASP.NET worker process.
Web Farm: Web application deployed on multiple servers.
A Web farm contains multiple ASP.NET worker processes. Each server in the group of servers handles a separate ASP.NET worker process.
Advantages:
It keeps the data separate from IIS, so
any issue with IIS does not harm session data
It is useful in web farm & web garden
Disadvantage:
It
is slow due to the serialization and deserialization.
Always need to running
Performance testing is required.
SQL
Server:
This mode stores the Session in SQL Server instead
of the server's memory also Independent of Application Domain. If our
application is stored on multiple server machines, then it becomes difficult to
use the "Inproc" mode since the request can go to any server for
processing. So if we want to use sessions in such cases, then we can store the
Session in SQL Server so that it becomes centralized and can be accessed by any
server during the request process. It is the most secure way of storing
Sessions but gives the lowest performance for an application. This mode is
slower than State Server Session mode but can be shared between several web
servers but this mode is more reliable. This mode also ensures that the Session
Data is preserved if the application restarts.
It is more reliable & secures session state
management.
The session data is serialized & stored in sql server database.
Best option is used in web form
<configuration>
<sessionstate mode="sqlserver" cookieless="false"
timeout="10"
stateConnectionString="tcpip=127.0.0.1:4 2424"
sqlConnectionString="Data Source=.\SqlDataSource;User
ID=userid;Password=password"/>
</configuration>
Advantages:
Session data does not affect if we restart IIS
It is most reliable & secure session management.
It keeps the data located centrally it can be
accessible from other application.
Disadvantage:
It is very slow
Session data is handled in different servers, so we
have to take care of the SQL server.
It should be running.
Custom mode session mode:
Custom mode stores Session state in a custom location.
If we set Session Mode="off" in web.config, Session will be
disabled for the application. For this we need to configure web.config in
following way.
<configuration>
<system.web>
<sessionState
mode="Off"></sessionState>
</system.web>
</configuration>
|
Session
State Mode |
State
Provider |
|
InProc |
In-Memory
Object |
|
StateServer |
Aspnet_state.exe |
|
SQLServer |
Database |
|
Custom |
CustomProvider |
Cookieless Session State
If
a user disables cookies in the browser, then the Session state doesn’t work because
by default, the Session state depends on cookies. The ASP.NET Framework uses the
ASP.NET_SessionId cookie identifier to identify the user while browsing the
web.
If
you want that Session state should work even when cookies are disabled, then
you can use cookieless sessions.
You
can enable cookieless sessions by adjusting the sessionState element in the web
configuration file.
<configuration>
<system.web>
<sessionState cookieless="AutoDetect"
regenerateExpiredSessionId="true" />
</system.web>
</configuration>---------------------------------------------------------------------------------------------------------------------------------------------------------------------
What
is Caching in Asp.net
It
is used to display the output quickly for a specified amount of time is known as caching.
Caching
is a technique to improve the access time when multiple users
access a website simultaneously, or a single user accesses a website multiple
times. It decreases server round trips for fetching data from the database by
persisting data in the memory.
1) Page caching
Data
caching
Fragment
caching
Page Caching:
It
is also known as output caching which enables you to cache a complete page in
the memory.
If
caching is used in the page and any user requests the same page, the page is
retrieved from the cache. It will reduce the load of the server and increases
performance.
Page Output Caching is used to fetch information or data at page level
It
is implemented in either of the following 2 ways.
At
design time using o/p caching directive
At
runtime using the HTTP policy class.
<%@
OutputCache Duration = 5 VaryByParam = "ID" or “*” %>
By
default, when you use Caching the page is cached on the following location.
·
Browser
·
Proxy
servers
·
Webserver
OutputCache
directive supports the following important attributes.
·
VaryByParam
·
VaryByHeader
·
VaryByCustom
·
VaryByControl
· Location
Duration
Data Caching
Practically,
page output caching is difficult to cache the entire page in applications but
regarding to programmatic requirements if we can perform caching, it will be
very useful
It is the most flexible type of caching.
Data
Caching is used to fetch the information of an application quickly based on the
requirements. A cache object is just like an application object which can be accessed anywhere in the application. The lifetime of the cache is equivalent to the lifetime of the application.
Caching data can dramatically improve the performance of an application by
reducing database contention and round-trips.
We
need to cache those data, which is accessible to all users and which is very
common data.
It
is a full feature cache engine that enables you to store & retrieve the
data between multiple HTTP requests & multiple sessions within the same
application.
Three
ways to add the data or object into cache. They are
1) Cache 2) Cache. Add 3) Cache. Insert
- Add: It
adds a new item to the cache.
- Get: It
returns a particular item from the cache.
- Insert: It
is used to insert a new item into the cache. This method replaces the
already exists item.
- Remove: This
method is used to remove an item from the cache.
·
Cache["Key"]="Item";
Fragment Caching
This
allows a specific portion of the page to be cached, rather than caching the whole
page.
It
is very useful in situations like where we can have a page that contains both
static and dynamic content.
<%@ OutputCache Duration = 10 VaryByParam = "None" %> ----------------------------------------------------------------------------------------------------------------------------Difference
between Response. Redirect and Server. Transfer in asp.net?
|
Response. Redirect |
Server. Transfer |
|
It
is used in both aspx and HTML pages |
It
is only used for aspx pages as it will not work on HTML pages |
|
It
is used to redirect the external websites |
It
is used to transfer to another webpage of the same website i.e. another .aspx page
on the same server. |
|
URL is changed for the new page and update
the address bar and adds it to the Browser History, On your browser, you can
click back. |
URL
remains the same. It does not change the address bar, we cannot hit back. |
|
There
is a round-trip |
Data
is getting loaded in the same browser. There is no round-trip |
|
It enables to see the new redirected URL
where it is redirected in the browser (and be able to bookmark it if it’s
necessary). |
It doesn’t
show the real URL where it redirects the request in the user's Web Browser.
|
|
Do
not need to preserve Query String and Form Variables from the original request |
Preserve Query String and Form
Variables (optionally)
|
--------------------------------------------------------------------------------------------------------------------------------
Difference between Authentication and Authorization in asp.net?
Authentication: It is the process of finding whether the user is valid or not.
Authentication
is the process of verifying the identity of a user by obtaining some sort of
credentials and using those credentials to verify the user's identity. If the
credentials are valid, the authorization process starts. The authentication process
always proceeds to the Authorization process.
The ASP.NET authentication scheme is used to identify users who view an ASP.NET application. An ASP.net
application has two separate authentication levels because all requests coming
through IIS before it handled by ASP.NET. After IIS authentication schemes
ASP.NET implements additional authentication schemes. They are:
- Windows
Authentication
- Forms
Authentication
- Passport
Authentication
This mode works as the default authentication. It can work with any format like Basic/Windows Integrated/Digest/Anonymous.
It is used for only intranet applications(within LAN)
Forms: Direct users to a login web form that collects username and password information and then authentication the user against a user list or DB that the application maintains.
Passport: This is a 3rd party authentication service provided by Microsoft. It can be used for internet applications and single-time login for internet applications and single-time login for multiple websites. Ex: If you log in for multiple websites.Ex: If you log in for Gmail, no need to log in for orkut. directly you can access them.
The mode attribute specifies the
authentication scheme.
<authentication mode="[Windows|Forms|Passport|None]" >
Authorization: It is the process of holding the rights for particular tasks.
Authorization is the process of allowing an authenticated users to access the resources by checking whether the user has access rights to the system. Authorization helps you to control access rights by granting or denying specific permissions to an authenticated user.
Asp.Net
Authorization
ASP.NET
allows two ways to authorize access to a given resource, they are URL authorization
and File authorization
URL authorization
URL
authorization maps users and roles to URLs in ASP.NET applications
File authorization
File
authorization validate the ACL (access control list) of the .aspx or .asmx
handler file to determine whether a user should have access to the file.
<authorization>
<allow
roles="Administrators" />
<deny users="*" />
</authorization>
-----------------------------------------------------------------------------------------------------------------------------
|
Web.Config |
Machine.Config
|
|
This is automatically created when you
create an ASP.Net web application project. |
This is automatically installed when
you install Visual Studio. Net. |
|
This is also called an application configuration
file. |
This is also called machine-level
configuration file, or Per-server basis file. |
|
This file inherits the setting from the
machine.config |
This file is at the highest level in
the configuration hierarchy. |
|
We
can create multiple web. config in our site |
Only one machine.config file exists on
a server. |
|
Located
in the root can be created in subfolder also |
Located
in the .NET framework |
|
They are maintained by application developers |
They
are maintaining by admins. |
--------------------------------- --------------------------------- --------------------------------- -----------------------
|
Client-side
scripting |
Server-side
scripting |
|
A client is
executed using a browser or which runs on the user browser. |
The server is executed @server using server-side resources. |
|
Source code is
visible to the user. |
Source code is
not visible to the user because its output of server-side is an HTML page. |
|
It usually
depends on the browser and its version. |
In this, any
server-side technology can be useful and it does not depend on the client. |
|
It runs on the user’s
computer. |
It runs on the web
server. |
|
It does not
provide security for data. |
It provides more
security for data. |
|
HTML, CSS and JavaScript
are used. |
PHP, Python,
Java, Ruby are used. |
----------------------------------------------------------------------------------------------------------------------------Features of Asp.net
It is user friendly
Exclusive rich set of controls
Smart or Intelligent Controls
Rendering: The process of converting the Asp.net process into browser understandable format or HTML is known as renderring.
Better State Management
Rapid Application development-----------------------------------------------------------------------------------------------------------------------------
|
ASP |
ASP.NET |
|
ASP is the
interpreted language. |
ASP.NET is the
compiled language. |
|
ASP uses ADO
(ActiveX Data Objects) technology to connect and work with databases. |
ASP.NET uses
ADO.NET to connect and work with databases. |
|
ASP is partially
object-oriented. |
ASP.NET is fully
object-oriented. |
|
ASP Pages have
the file extension .asp. |
ASP.NET Pages
have the file extension .aspx.
|
|
ASP doesn’t have
the concept of inheritance. |
ASP.NET inherit
the class written in code behind. |
|
ASP pages use
scripting language. |
ASP.NET uses a full-fledged
programming language.
|
|
Error handling is
very poor in ASP. |
Error handling is
very good in ASP.NET. |
|
GET |
POST |
|
In the GET method,
values are visible in the URL. |
In the POST method,
values are not visible in the URL. |
|
GET has a
limitation on the length of the values, generally 255 characters. |
POST has no
limitation on the length of the values since they are submitted via the body
of HTTP. |
|
GET performs are
better compared to POST because of the simple nature of appending the values
in the URL. |
It has lower
performance as compared to the GET method because of time spent in including POST
values in the HTTP body. |
|
This method
supports only string data types. |
This method
supports different data types, such as string, numeric, binary, etc. |
|
GET results can
be bookmarked. |
POST results
cannot be bookmarked. |
|
GET request is
often cacheable. |
The POST request
is hardly cacheable. |
|
GET Parameters to remain in web browser history. |
Parameters are
not saved in web browser history. |
Main differences:
In the GET
method, values are visible in the URL while in the POST method, values are NOT visible
in the URL.
GET has
a limitation on the length of the values, generally, 255 characters whereas POST
has no limitation on the length of the values since they are submitted via the
body of HTTP.
GET
method supports only string data types while POST method supports different
data types, such as string, numeric, binary, etc.
GET
request is often cacheable while POST request is hardly cacheable.
Types of
Validation in asp.net:
There
are six types of validation controls in ASP.NET
- RequiredFieldValidation
Control
- CompareValidator
Control
- RangeValidator
Control
- RegularExpressionValidator
Control
- CustomValidator
Control
- ValidationSummary
|
Response.Write() |
Response.Output.Write() |
|
It writes the text stream |
It writes the HTTP Output
Stream. |
|
It can't allow the formatted
output. |
It allows us to print
formatted output |
|
to display only string and
you cannot display any other data type values like
int, date, etc.Conversion(from one data type to another) is not allowed. |
you can display any type of
data like int, date, string, etc., by giving index values. |
--------------------------------------------------------------------------------------------------------------------------------Response. Expires
This
property specifies the number of minutes before a page cached in the browser
expires i.e. if the user returns to the same page before the specified number
of minutes the cached version of the page is displayed. (Or)
Response.
Expires specifies the length of the time the page is in the cache, from the time
request has been served from the server. For instance, if I set it to 20 minutes,
counting from the initial response to the client it would exist till 20
minutes.
Response.ExpiresAbsolute
Using
this property we can set the date and/or time at which the page cached in the
browser expires.
(Or)
Response.ExpiresAbsolute
would be the exact time at which the page in cache expires. For instance, if I
set to May 31, 2020, 13:30:15, till this time the page would be in cache.
-----------------------------------------------------------------------------------------------------------------------------
|
URL |
URI |
|
URL stands for
Uniform Resource Locator. |
URI stands for
Uniform Resource Identifier. |
|
URL is a subset
of URI that specifies where a resource exists and the mechanism for
retrieving it. |
A URI is a
superset of URL that identifies a resource either by URL or URN (Uniform
Resource Name) or both. |
|
The main aim is
to get the location or address of a resource |
The main aim of
URI is to find a resource and differentiate it from other resources using
either name or location. |
|
URL is used to
locate only web pages |
Used in HTML, XML, and other files XSLT (Extensible Style sheet Language Transformations) and
more. |
|
The scheme must
be a protocol like HTTP, FTP, HTTPS, etc. |
In URI, the
scheme may be anything like a protocol, specification, name, etc. |
|
Protocol
information is given in the URL. |
There is no
protocol information given in URI. |
|
Example of URL: https://google.com |
Example of URI: |
|
It contains
components such as protocol, domain, path, hash, query-string, etc. |
It contains
components like scheme, authority, path, query, fragment component, etc. |
|
All URLs can be
URIs |
Not all URIs are
URLs since a URI can be a name instead of a locator. |
--------------------------------------------------------------------------------------------------------------------------------
What are dependencies in cache & types of dependencies?
When you add an item to the cache, you can define
dependency relationships that can force that item to be removed from the cache
under specific activities of dependencies. For example, if the cache object is
dependent on the file and when the file data changes you want the cache object to
be updated. Following are the supported dependency:-
- File dependency: - This allows you to invalidate a
specific cache item when a disk-based file or files change.
- Time-based expiration: - This allows you to
invalidate a specific cache item depending on predefined time.
- Key dependency:-Allows you to invalidate a specific cache item depending on when another cached item changes.
What
is the HTTP handler and module in asp.net?
An
ASP.NET HTTP handler is a process (frequently referred to as the
"endpoint") that runs in response to a request made to an ASP.NET Web
application. The most common handler is an ASP.NET page handler that processes
.aspx files. When users request an .aspx file, the request is processed by the
page through the page handler. You can create your own HTTP handlers that
render custom output to the browser.
By default ASP.Net handlers have .ashx file extension.
ASP.Net has a number of
built-in HTTPHandlers which handle different files like .aspx, .asmx based on an extension of files. In spite of these built-in HTTPHandlers, you can always
create your own custom handlers to handle some specific extension of files.
Custom HTTPHandlers.
You can create your own HTTP handlers and
register them for request handling on the web. config using <HttpHandlers/>
element. To create a custom HTTP handler you have to create a class and need to
implement the IHttpHandler interface. IHttpHandler has 2 abstract methods and 1
property that can be defined in your custom class.
Methods
in Http Handler:
The following are the methods in Http
Handlers.
|
Method Name |
Description |
|
ProcessRequest |
Used to call Http
Requests. |
|
IsReusable |
To check the
reusability of same instance handler with a new request of same type. |
ProcessRequest(HttpContext context)
This is a method that is called once the
request is received. This method gets the HttpContext object as a parameter and
can use the same for writing custom logic. Using the HttpContext object you can
access the request and response objects to write the custom processing logic.
IsReusable
This is a property that if it is set to true,
the same object will be used for processing further requests of the same type.
If it is set to false the handler object is disposed of after request.
Configuring
HTTP Handlers
The <httpHandlers> configuration section
handler is responsible for mapping incoming URLs to the IHttpHandler or
IHttpHandlerFactory class. It can be declared at the computer, site, or
application level. Subdirectories inherit these settings.
Administrators use the <add> tag
directive to configure the <httpHandlers> section. <Add> directives
are interpreted and processed in a top-down sequential order. Use the following
syntax for the <httpHandler> section handler:
<httpHandlers>
<add verb="[verb list]" path="[path/wildcard]" type="[COM+
Class], [Assembly]" validate="[true/false]" />
<remove verb="[verb list]" path="[path/wildcard]" />
<clear />
</httpHandlers>
Customized
HTTP Handler
By customizing HTTP handlers, new
functionalities can be added to the Web Server. Files with new extensions like
.text for a text file can be handled by Web Server by using HTTP handlers. The
future of customization can lead to hosting .jsp pages in IIS by finding
adequate ISAPI extensions.
Register
your custom HTTPHandler in web.config
<HttpHandler>
<add verb="*" , path=
"*.cscorner", type=""/>
<HttpHandler>
An
HTTP module is an assembly that is called on every request that is made to your
application. HTTP modules are called as part of the ASP.NET request pipeline
and have access to life-cycle events throughout the request. HTTP modules let
you examine incoming and outgoing requests and take action based on the
request. HTTPModules handles
application events.
- BeginRequest()
- EndRequest()
- AuthenticateRequest()
You can create your own custom HTTP Modules using the IHttpModule interface. This interface contains 2 methods that can be implemented in your custom Module class. These methods are,
Init()
Takes the Http Application object as a parameter that allows HttpModule to register events.
Dispose()
To dispose of the Module
object before garbage collector.
Typical uses for custom
HTTP handlers include the following:
·
RSS feeds To
create an RSS feed for a Web site, you can create a handler that emits
RSS-formatted XML. You can then bind a file name extension such as .rss to the
custom handler. When users send a request to your site that ends in .rss,
ASP.NET calls your handler to process the request.
·
Image server If
you want a Web application to serve images in a variety of sizes, you can write
a custom handler to resize images and then send them to the user as the
handler's response.
Typical uses for HTTP modules
include the following:
·
Security Because
you can examine incoming requests, an HTTP module can perform custom
authentication or other security checks before the requested page, XML Web
service, or handler is called. In Internet Information Services (IIS) 7.0
running in Integrated mode, you can extend forms authentication to all content
types in an application.
·
Statistics and
logging Because HTTP modules are called on every request, you
can gather request statistics and log information in a centralized module,
instead of in individual pages.
·
Custom headers or
footers Because you can modify the outgoing response, you can
insert content such as custom header information into every page or XML Web
service response.
<HttpModules> <add
name="somename" type="custom HTTP module"/> </HttpModules>
---------------------------------------------------------------------------------------------------------------------------------Difference between Web Application and Website in
ASP.NET?
Web
Application
1. If we create any class files/functions those
will be placed anywhere in the applications folder structure and it is precompiled
into one single DLL.
2. In web applications we have a chance to select only
one programming language during the creation of the project either C# or VB.NET.
3. Whenever we create a Web Application it will
automatically create project files (.csproj or .vbproj).
4. We need to pre-compile the site before
deployment.
5. If we want to deploy a web application project we
need to deploy only .aspx pages there is no need to deploy code behind files
because the pre-compiled dll will contain these details.
6. If we make a small change in one page we need to
re-compile the entire site.
WebSite
1. If we create any class files/functions those will
be placed in the ASP.NET folder (App_Code folder) and it's compiled into several
DLLs (assemblies) at runtime.
2. On the website we can create pages in multi
programming languages that means we can create one-page code in C# and another
page code in vb.net.
3. Web Sites won’t create any .csproj/.vbproj files
in the project
4. No need to recompile the site before deployment.
5. We need to deploy both the .aspx file and code-behind
file.
6. If we make any code changes those files only will
upload there is no need to re-compile the entire site-----------------------------------------------------------------------------------------------------------------------------
Q) Difference between user control and custom control in asp.net
User control:
1) User control can be used for the Reusable purpose only.
2) Once you create a User control that can be accessed in the current project.
3) User control extension is .ascx file.
4) It can be visible in Solution Explorer.
5) It is Locally used. If you want to use this control on any page just drag and drop from Solution or Register that particular page like
<%@ Register TagPrefix="Scott" TagName="header" Src="Controls/Header.ascx" %>
<%
Custom Control:
1) Custom control can be used for Globale purposes like Toolbox controls.
2) Custom control can create an extension file is .dll.
3) It can Add to Toolbox like
Right click on toolbox add->choose items->select path of file.
4) Custom control If you want to use it in any form just you can drag and drop like a normal control.-----------------------------------------------------------------------------------------------------------------------------
What is tracing in asp.net?
Tracing is an activity
to follow the execution path and display the diagnostic information related to a
specific Asp.Net web page or application that is being executed on the webserver. Tracing can be enabled in the development environment as well as in the
production environment.
In Asp.Net Tracing is
disabled by default. Trace statements are executed and shown only when tracing
is enabled. You can enable tracing in two levels.
Page-Level Tracing
Application Level
Tracing
You can enable
individual pages as well as you can enable your application's Web. config file
to display trace information. When you enabled it application level, it displays
all pages trace information unless the page explicitly disables tracing.
Page-Level Tracing
We can control whether
tracing is enabled or disabled for an Asp.Net page with the Trace attribute of
the @ Page directive.
<%@ Page
Title="" Language="C#" MasterPageFile="~/MasterPage.master"
AutoEventWireup="true" CodeFile="Default.aspx.cs"Inherits="chat_Default"
Trace="true"%>
Also followed by the above
directive, you can add other property TraceMode=" SortByCategory or
SortByTime"
SortByCategory: Set TraceMode to SortByTime to sort trace
messages in the order in which they are processed.
SortByTime: Set TraceMode to SortByCategory to sort trace messages by the
categories.
Now press F5 to run
the application, you will see the immediate trace record on an existing page
that you have set Trace and TraceMode.
You can see the traced
record in the Trace Viewer as well; you will learn this in 'Application Level
Tracing'.
Application Level Tracing
When we enable
application level tracing, trace information is gathered and processed for each
page in that application. We can enable application level tracing by using the
trace element in the Web.config file.
<configuration>
<system.web>
<trace enabled="true"
pageOutput="true" requestLimit="50"
localOnly="false"
mostRecent="true"traceMode="SortByTime" />
</system.web>
</configuration>
By default,
application-level tracing can be viewed only on the local Web server computer.
The above configuration enables an application trace configuration that
collects trace information for up to 50 requests.
Enabled: Set it true to enable tracing for the application; otherwise,
false. The default is false. You can override this setting for individual pages
by setting the Trace attribute in the @ Page directive of a page to true or
false.
PageOutput: Set it true to display trace both in pages and in the trace
viewer (trace. axd); otherwise, false. The default is false.
RequestLimit: The number of trace requests to store on the
server. The default is 10.
LocalOnly: Set it true to make the trace viewer (trace.axd) available only
on the host Web server; otherwise, false. The default is true.-----------------------------------------------------------------------------------------------------------------------------
Q)How to secure Connection Strings
The best way to secure the database connection
string is to encrypt the value within the configuration
file. The application would then load the encrypted
value from the config file, decrypt the value, and
then use the decrypted value as the connection
string to connect to the database.t is always
recommended to encrypt the connection string of your
application because the data we have there is
highly sensitive. It must be secured.
The connection string in the Web. config file
contains sensitive information of the database such as
connection string parameters. To avoid these problems
you can improve the security of sensitive
information stored in a connection string by using
built-in protected configuration model functionality
to encrypt or decrypt few sections of a web. config
file.
How
to encrypt the connection string in ASP.NET?
You can encrypt the connection string section of a
web. config file by using the aspnet_regiis.exe command-line tool, so it is never stored as plain
text. This file is located in the %systemroot%\Microsoft.NET\Framework\versionNumber
folder and you can use with -pef option. Consider you have an application named as MyWebApp. You can encrypt the
connectionStrings section of the Web. config file by using
aspnet_regiis.exe as follows :
aspnet_regiis.exe -pef "connectionStrings"
"/MyWebApp"
-pef indicates that the application is built as a File
System website and second argument connectionStrings indicates the name of the configuration section needs to be encrypted and the third
the argument is the physical path where the web. config
file is located.
If you are using IIS based web application the
command will be,
aspnet_regiis.exe -pe "connectionStrings"
-app "/MyWebApp"
The -pe option, passing it the string
"connectionStrings" to encrypt the connectionStrings element.
The -app option, passing it the name of your
application.
After running the tool successfully .. you will receive a message "Encrypting configuration section...Succeeded!"
How
to decrypt the connection string in ASP.NET?
When you want to decrypt the encrypted Web. config
file, run the aspnet_regiis.exe tool with the -pd
option. The syntax is the same as encrypting the Web. config file contents with the -pe option except that you do not specify a protected configuration provider.
-----------------------------------------------------------------------------------------------------------------------------
Q)Adding a Favicon to Your Website
The favicon, also known as a shortcut icon, little
icon, or website icon that browsers display next to a page's title on a browser
tab, or in the address bar next to its URL. So, many recent browsers display it
as a visual reminder of the Web site identity in the address bar or in tabs.
How
to add a Favicon to my site?
Adding a Favicon to your Web site is a simple task.
Just add an .ico image file that is either 16x16 pixels or 32x32 pixels in the
webroot. Then, link to it in the header of your page like the following:
<head>
<title>My Site</title>
<link
rel="icon" type="image/ico"
href="http://www.mysite.com/favicon.ico"/>
</head>
Limitations
There are several limitations to the approaches
described above. Some limitations are listed below:
This approaches only work in HTML or XHTML
Keep in mind that for a user with a slow modem a
favicon.ico may increase the page loading time by a few seconds if it is too
large, so don't overdo it.-----------------------------------------------------------------------------------------------------------------------------
Difference between Session and Caching?
What is Caching?
Caching is a technique where we can store frequently
used data, and web pages are stored temporarily on the local hard disk for
later retrieval. Each request will use the same cache for different users. One
of the more common items stored in a cache in a Web application environment is
commonly displayed database values; by caching such information, rather than
relying on repeated database calls, the demand on the Web server and database
server's system resources are decreased and the Web application's scalability
increased.
What is a session?
The session is a period of time that is shared between
the web application and the user. It refers to a limited time of communication
between two systems. Some sessions involve a client and server, while other
sessions involve two personal computers. Each user that is using the web
application has their own session. Session variables will use different
session variables for each different user. Since session variables are stored
on the Web server's memory, storing large objects in a user's session on a site
with many simultaneous users can lead to reduced memory on the Web server
Differences:
Session data is stored at the user level but caching
data is stored at the application level and shared by all the users.
Sessions may not improve performance whereas Cache
will improve site performance.
Items in the cache can expire after given time to cache
while items in the session will stay till the session expires.
Sessions may change from user to user whereas a
single Cache will be maintained for the entire application.
Cache won’t maintain any state, whereas Sessions
will maintain a separate state for every user.
-----------------------------------------------------------------------------------------------------------------------------
QWhat is Cross Page Posting?
It means you are posting form data from one page to
another page.
By default Asp.net web form page ,button and other
controls that cause post back submits current page back to itself.
Some Cross page posting techniques,
Using PostBackUrl property
<form id="form1" runat="server">
<asp:TextBox ID="txtName" name="data"
runat="server" />
<asp:Button Text="ClickPostBack" runat="server"
PostBackUrl="~/Display.aspx" />
</form>
Server.Transfer
with Query String
protected void btnclick_Click(object sender, EventArgs
e)
{
Server.Transfer("Display.aspx?Name=Vikas&Work=Developer");
}
-----------------------------------------------------------------------------------------------------------------------------
Other FAQ's:
Q) Which is the parent class of the Web server
control?
The System.Web. UI.Control class is the parent class
for all Web server control.
Q) Why do we need nested master pages in a Web site?
When we have several hierarchical levels in a Web site, then we use nested master pages in the Web site.
Q)Can you have a web application running without a web. Config file?
Yes. You can run an asp.net application without web.config file. If you do not configure any settings on the web. config file then it will take the machine. config file for default configurations. However, it will not allow users to debug, even if you are running it in debug mode.
Q)Which namespace is used to implement debug and trace methods?
The
Systems. Diagnostics namespace includes Trace and Debug classes.
Q)Where the assembly is stored in asp.net?
Private assemblies are stored in the project's bin folder to use in that particular project, whereas public or shared assemblies are stored in GAC(global assembly cache) so that it is available to every project.
Q)How to access session variables from any class in ASP.NET?
Access
the Session via the threads HttpContext:
System.Web.HttpContext.Current.Session["loginId"]
Q)How long the items in ViewState exists?
ViewState
exists till your current page exists. This includes postbacks. Viewstate become
nothing once
it
redirects or transfers to another page.
Q)In which event of page cycle is the ViewState available?
ViewState
is loaded into memory between init and load. In-Page Init only Partially gets
loaded. In-Page load, ViewState complete. So the whole loading is available in Page
load only.
Q)Which is the only event provided by the Cache object?
CacheItemRemoved
event is the only event provided by the Cache object.
Q)Which delegate can be used to notify the application when items are removed from the cache?
onRemoveCallback
is used to notify the application when items are removed from the cache.
Q)How can we prevent browsers from caching an ASPX page?
Response.Cache.SetNoStore();
Q)How to open a page in a new window?
You can
use Javascript in code behind to open a page in a new window.
Response.Write("<script>
window.open('http://net-informations.com/','_blank'); </script>");
Q)What is the default timeout for a Cookie?
The
default Expires value for a cookie is not a static time, but it creates a
Session cookie. Setting the Expires property to MinValue makes this a session
Cookie, which is its default value. This will stay active until the user
closes their browser/clears their cookies. You can override this as required.
Q)How to turn off cookies for a page?
You
don't have to change anything in your ASP.NET application to enable cookieless
sessions, except the following configuration setting on the web. config file
<sessionState cookieless="true" />
Q)How
would you create a permanent cookie?
Set its
Expires property equal to DateTime.maxValue, which means cookies never Expires.
Q)What is the difference between a page theme and a global theme?
Page
theme applies to particular web pages of the project. It is stored inside a
subfolder of the App_Themes folder while the Global theme applies to all the web
applications on the webserver. It is stored inside the Themes folder on a Web
server.
Q)Which method do you use to kill explicitly a user session?
Session.Abandon()
Session.Remove()
- It will kill the session for the specific user.
Session.Clear()
- To remove all keys with the session as well as you can also use it to remove
specific keys from the session.
Q)Which is the parent class of the Web server control?
The System.Web. UI. Control class is the parent class for all Web server control.
Q)Why do
we need nested master pages in a Web site?
When we
have several hierarchical levels in a Web site, then we use nested master pages
in the Web site.
Q)How can you dynamically add user controls to a page?
It is
possible to load User Controls onto a page by making use of the LoadControl
method.
TestUserControl
tuc = (TestUserControl)LoadControl("TestUserControl.ascx");
Once the
User Control has been loaded, it can be added to the page by adding it to the
Controls collection.
form1.Controls.Add(tuc);
Q)What are the Navigations technique in ASP.NET?
Response.Redirect
Server.Transfer
Server.Execute
Cross
page posting
Q)Can I deploy the application without deploying the source code on the server?
Yes. You
can deploy the asp.net application without deploying the source code on the
server by Deploy the compiled version. You can use 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.
Q)How can you display all validation messages in one control?
You can
use the ValidationSummary control to displays all validation messages in one
control. It is possible to set the HeaderText to something like "(*)
Fields are required" for your validation summary.
Q)Which method is used to force all the validation controls to run?
The
Page.Validate() method is used to force all the validation controls to run and
to perform validation.
Q)How can I show the entire validation error message in a message box on the client-side?
Invalidation summary set "ShowMessageBox" to true.
Q)What data type does the RangeValidator control support?
Currency
Date
Double
Integer
String
Q)Which control will you use to ensure that the values in two different controls match?
CompareValidator.
It compares the value entered by the user in an input control with the value
entered in another input control.
Q)What is the difference between a HyperLink control and a LinkButton control?
Hyperlink
control is an HTML control, whenever it is clicked the page navigates to the
target page. ASP.NET Link Button control is a server control, whenever the user
clicks on it, the request is redirected back to the server and in its response, the page is navigated to the target page.
Q)How information about the user's locale can be accessed?
The
information regarding a user's locale can be accessed by using the
System. Web. UI.Page.Culture property.
Q)How do you sign out from forms authentication?
The
method FormsAuthentication.SignOut() is used for sign-out forms
authentication.
Q)What is the difference between a default skin and a named skin?
A
default skin automatically applies to all controls of the same type when a
theme is applied to a page. While a named skin does not automatically apply to
controls by type. Instead, you explicitly apply a named skin to a control by
setting the control's SkinID property.
Q)Which protocol is used to call a Web service?
Simple
Object Access Protocol (SOAP) is the preferred protocol. SOAP defines the
XML-based message format that Web service-enabled applications use to
communicate and inter-operate with each other over the Web.
Q)What is the file extension of the web service?
ASMX
(.asmx) is extension for Webservices.
Q)How do you register JavaScript for web controls ?
You can
register javascript for controls using
<CONTROL
-name > .Attribtues.Add(scriptname,scripttext) method.
Q)What is WSDL?
A WSDL
is an XML document that describes a web service. It actually stands for Web
Services Definition Language. It is a way to describe services and how they
should be bound to specific network addresses. It describes the contract between
service & client. WSDL has three parts:
Q)Definitions
Operations
Service
bindings
Q)What is a formatter?
A
formatter is an object that is responsible for encoding and serializing data
into messages on one end and deserializing and decoding messages into data on
the other end.
Q)What is the default authentication mode for IIS?
Anonymous
is the default authentication mode for IIS.
Q)Which objects are used to create foreign keys between tables?
DataRelation
Q)Can a dll run as a stand-alone application?
You
can't run dll at all. You can create exe and add your dll as a reference.
Q)What is the extension of a web user control file?
The filename extension for the user control is .ascx.
Q)What is the use of @ Register directives?
@Register
directive provides information to the complier about any custom control added
to page.
< %@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
Q)What is Virtual Directory?
A virtual directory is a directory name that you specify in IIS and map to a physical directory on a local server's hard drive or a directory on another server (remote server). You can use Internet Information Services Manager to create a virtual directory for an ASP.NET Web application that is hosted in IIS.
How to Set Master Page dynamically?
Yes. You can assign a master page dynamically during
the PreInit stage. Because the master page and content page are merged during
the initialization stage of page processing, a master page must be assigned
before then.
void Page_PreInit(Object sender, EventArgs e)
{
this.MasterPageFile = "~/NewMaster.master";
}
Q)What is the Global. asax file?
Global. asax is an optional file that is used to
handling higher-level application events such as Application_Start,
Application_End, Session_Start, Session_End, etc. It is also popularly known as
ASP.NET Application File. This file resides in the root directory of an
ASP.NET-based application. If a user requests the
Global. asax file, the request is rejected. External users cannot view the file.
The Global. asax file
is parsed and dynamically compiled by ASP.NET. You can deploy this file as an
assembly in the \bin directory of an ASP.NET application.
What kind of
application event is global. asax can handle:
Methods corresponding to events that fire on each request
Application_BeginRequest()
– fired when a request for the web application comes in.
Application_AuthenticateRequest
–fired just before the user credentials are authenticated. You can specify your
own authentication logic over here.
Application_AuthorizeRequest()
– fired on successful authentication of user’s credentials. You can use this
method to give authorization rights to users.
Application_ResolveRequestCache()
– fired on successful completion of an authorization request.
Application_AcquireRequestState()
– fired just before the session state is retrieved for the current request.
Application_PreRequestHandlerExecute()
- fired before the page framework begins before executing an event handler to
handle the request.
Application_PostRequestHandlerExecute()
– fired after HTTP handler has executed the request.
Application_ReleaseRequestState()
– fired before current state data kept in the session collection is serialized.
Application_UpdateRequestCache()
– fired before the information is added to the output cache of the page.
Application_EndRequest()
– fired at the end of each request
Methods corresponding
to events that do not fire on each request
Application_Start() –
fired when the first resource is requested from the webserver and the web
application starts.
Session_Start() –
fired when the session starts on each new user requesting a page.
Application_Error() –
fired when an error occurs.
Session_End() – fired
when the session of a user ends.
Application_End() –
fired when the web application ends.
Application_Disposed()
- fired when the web application is destroyed.
Q) What are
the types of ASP Objects?
You can
create various types of objects in ASP?
Response
Object
Application
Object
Request
Object
Session
Object
Server
Object
Error
Object
File
System Object
File
Object
ADO
Object
Drive
Object
List all
different types of directives in Asp.Net?
@
Assembly
@
Control
@
Implements
@ Import
@ Master
@
MasterType
@
OutputCache
@ Page
@
PreviousPageType
@
Reference
@
Register
-----------------------------------------------------------------------------------------------------------------------------
How to
get row cell value grid view c#
protected void GridView1_RowEditing(object sender,
GridViewEditEventArgs e)
{
//following will iterate all rows
for each (GridViewRow row in GridView1.Rows)
{
string value = row.Cells[DesiredcolumnIndex].Text;
}
//following will give the value of single row that is being edited
int i
= e.NewEditIndex;
string
value = GridView1.Rows[i].Cells[DesiredcolumnIndex].Text;
}-----------------------------------------------------------------------------------------------------------------------------
ASP.NET Grid View - Events and its Description
Event
Name Description
DataBinding Occurs
when the server control binds to a data source. (Inherited from Control.)
DataBound Occurs
after the server control binds to a data source. (Inherited from
BaseDataBoundControl.)
Disposed Occurs
when a server control is released from memory, which is the last stage of the
server control lifecycle when an ASP.NET page is requested. (Inherited from
Control.)
Init Occurs
when the server control is initialized, which is the first step in its lifecycle.
(Inherited from Control.)
Load Occurs
when the server control is loaded into the Page object. (Inherited from
Control.)
PageIndexChanged Occurs
when one of the pager buttons is clicked, but after the GridView control
handles the paging operation.
PageIndexChanging Occurs
when one of the pager buttons is clicked, but before the GridView control
handles the paging operation.
PreRender Occurs
after the Control object is loaded but prior to rendering. (Inherited from
Control.)
RowCancelingEdit Occurs
when the Cancel button of a row in edit mode is clicked, but before the row
exits edit mode.
RowCommand Occurs
when a button is clicked in a GridView control.
RowCreated Occurs
when a row is created in a GridView control.
RowDataBound Occurs
when a data row is bound to data in a GridView control.
RowDeleted Occurs
when a row's Delete button is clicked, but after the GridView control deletes
the row.
RowDeleting Occurs
when a row's Delete button is clicked, but before the GridView control deletes
the row.
RowEditing Occurs
when a row's Edit button is clicked, but before the GridView control enters
edit mode.
RowUpdated Occurs
when a row's Update button is clicked but after the GridView control updates
the row.
rowupdating Occurs
when a row's Update button is clicked, but before the GridView control updates
the row.
SelectedIndexChanged Occurs
when a row's Select button is clicked, but after the GridView control handles
the select operation.
SelectedIndexChanging Occurs when a row's Select button is clicked, but before the
GridView control handles the select operation.
Sorted Occurs
when the hyperlink to sort a column is clicked, but after the GridView control
handles the sort operation.
Sorting occurs
when the hyperlink to sort a column is clicked, but before the GridView control
handles the sort operation.
Unload Occurs
when the server control is unloaded from memory. (Inherited from Control.)------------------------------------------------------------------------------------------------------------------------
Difference between the master page and user control in
asp.net?
Master Page: A master page provides the layout and
functionality to other pages.
User
Control:
A User Control is a reusable page or control with an
extension of .ascx and created similar
to an .aspx page but the difference is that a User Control does not render on
its own, it requires an .aspx page to be rendered.
User Controls are very useful to avoid repetition of
code for similar requirements. Suppose I need a calendar control in my
application with some custom requirements in multiple pages, then instead of
creating the control repetitively you can create it once and use it on multiple
pages.
Key
points
The User Control page structure is similar to the
.aspx page but a User Control does not need to add an entire HTML structure
such as body, head and form.
A User Control has an .ascx extension.
A User Control is derived from the UserControl class
whereas an .aspx page is derived from the Page class.
A User Control does not render on its own, it needs
an .aspx page.
To use a User Control in an .aspx page you need to
register the control in the .aspx page.
The key is that Master Pages provide the common
content that should be applied to all pages in a site; or at least, all pages
that use it. For example, it's very common to require a logo, a menu, etc, on
all pages, and a master page is ideal for this; you design the master page with
these common elements on them and then every page automatically gets this
content too.
A user control is intended for reusable content,
wrapping up small bundles of functionality that is to be reused on multiple
pages. For example, wrapping a few labels and text boxes (name, address, post
code,e tc), which are required on several, but not all pages.
Master Pages are used to provide the consistent
layout and common behaviour for multiple pages in your applications.then u can
add the Contenetplaceholder to add child pages custom contenet.
User Controls:Sometimes u need the functionality in
ur web pages which is not possible using the Built-In Web server controls then
user can create his own controls called user controls using asp.net builtin
controls.User controlsn are those with .aspx extensions and u can share it in
the
application.
Master
Page:
Register the User Control on .aspx
page
To use a User Control in an .aspx we need to register it using the Register page directive, the
register page directive has the
following properties:
Assembly: This is an optional
property used to register the assembly, for example, Ajax control toolkit.
Namespace: This property is used to
specify the namespace.
Src: Used to set the source of User
Control.
TagName: Used to provide the name
for the User Control used on a page similar to a TextBox or label, you can define any name.
TagPrefix: This is used to specify
the prefix name of User Control which is similar to ASP. You can
define any prefix name.
Normal Aspx:
<%@ Page Language="C#"
AutoEventWireup="true" COdefile="desfault.aspx.cs"
Inherits="%>
Web UserControl:
<%@ Register
Src="~/Usercontrol.ascx" TagPrefix="uc"
Tagname="Student"%>
------------------------------------------------------------------------------------------------------------------------
---
No comments:
Post a Comment