Vous êtes sur la page 1sur 37

ASP .

Net Page Life Cycle

1. OnInit (Init) Initializes each child control of the current

2. LoadControlState: Loads the ControlState of the control. To use this


method the control must call the Page.RegisterRequiresControlState method in
the OnInit method of the control.

3. LoadViewState: Loads the ViewState of the control.

4. LoadPostData: Is defined on interface IPostBackDataHandler. Controls that


implement this interface use this method to retrieve the incoming form data and
update the control s properties accordingly.

5. Load (OnLoad): Allows actions that are common to every request to be


placed here. Note that the control is stable at this time; it has been
initialized and its state has been reconstructed.

6. RaisePostDataChangedEvent: Is defined on the interface IPostBackData-Handler.


Controls that implement this interface use this event to raise change events in
response to the Postback data changing between the current Postback and the
previous Postback. For example if a TextBox has a TextChanged event and
AutoPostback is turned off clicking a button causes the Text-Changed event to
execute in this stage before handling the click event of the button which is
raised in the next stage.

7. RaisePostbackEvent: Handles the client-side event that caused the Postback


to occur

8. PreRender (OnPreRender): Allows last-minute changes to the control. This


event takes place after all regular Post-back events have taken place. This
event takes place before saving ViewState so any changes made here are saved.

9. SaveControlState: Saves the current control state to ViewState. After this


stage any changes to the control state are lost. To use this method the
control must call the Page.RegisterRequiresControlState method in the OnInit
method of the control.

10. SaveViewState: Saves the current data state of the control to ViewState.
After this stage any changes to the control data are lost.
11. Render: Generates the client-side HTML Dynamic Hypertext Markup Language
(DHTML) and script that are necessary to properly display this control at the
browser. In this stage any changes to the control are not persisted into
ViewState.

12. Dispose: Accepts cleanup code. Releases any unman-aged resources in this
stage. Unmanaged resources are resources that are not handled by the .NET common
language runtime such as file handles and database connections.

13. UnLoad
Authentication Levels

Windows authentication enables you to identify users without creating a custom


page. Credentials are stored in the Web server s local user database or an Active
Directory domain. Once identified you can use the user s credentials to gain access
to resources that are protected by Windows authorization.

Forms authentication enables you to identify users with a custom database such
as an ASP.NET membership database. Alternatively you can implement your own
custom database. Once authenticated you can reference the roles the user is in to
restrict access to portions of your Web site.

Passport authentication relies on a centralized service provided by Microsoft.


Passport authentication identifies a user with using his or her e-mail address and a
password and a single Passport account can be used with many different Web sites.
Passport authentication is primarily used for public Web sites with thousands of
users.

Anonymous authentication does not require the user to provide credentials.

<authentication mode "Forms/Passport/Windows"/> In web.config file

Virtual functions implement the concept of polymorphism are the same as in C#, except that
you use the override keyword with the virtual function implementaion in the child class. The
parent class uses the same virtual keyword. Every class that overrides the virtual method will
use the override keyword.
class Shape
{
public virtual void Draw()
{
Console.WriteLine("Shape.Draw") ;
}
}

class Rectangle : Shape


{
public override void Draw()
{
Console.WriteLine("Rectangle.Draw");
}
}
Page PostingHow do you post a current page to different ASPx page?

ASP.NET provides the following ways for you to build redirection into your Web pages:
• Using hyperlinks on pages.
• Configuring cross-page posting, which enables you to specify an alternate target page
when the current page is submitted.
• Redirecting programmatically by forcing the browser to request a different page.
• Redirecting programmatically by transferring control to a different page in the same Web
application.
we know Http is an state-less protocol which is required for interaction between
clinet and server .

so there is an need to remeber state of request raised by an web browser so that


web server can recognize you have already previously visited or not.

There are two types of state management techniques:


a) Client side state management
b) Server - side statemanagement

Using cookies comes under clinet side statemanagement .In HttpResponse we write
Cookie containing sessionId and other information within it.

when a browser made a request to the web server the same cookie is sent to the
server where server recognize the session id and get other information stored to it
previously.

Cons:
1)Cookie should contain non sensitive data as one can easily read cookies and they
result of which your security may be tampered .
2) Cookie should not contain large amount of information as they are sent back and
forth with request and response in between client and server which may cause your

Performance degradation

A cookie is stored on the client's machine by their web browser software. There are good levels
of compatibility in browser implementations so using them is generally hassle-free. When a web
server receives an HTTP request it responds with an HTTP response. To set a cookie we include
information in an HttpResponse that instructs the browser to save a cookie on the client's system.
Future HttpRequests will then include details of this and other cookies.
Be very clear about cookies; when you call HttpCookie.Add the cookie is not added to anything
except a collection in the HttpResponse that will be sent back to the web browser. The cookie is
only stored on the client's machine when the browser has successfully processed the instruction
to save the cookie that it received in an HttpResponse. We at the server can only check that
cookie has been saved when we receive another HttpRequest as we can then see whether the
request includes our cookie.
Note as well that cookies are strings and are invariably quite short (you cannot save objects in
cookies).
Attempt Free Asp.Net Interview Question Answer Online Test and check your
performance

What is the use of indexes and what are the types of indexes available in SQL
Server?
Indexes are used to find data quickly when a query is processed in any relational database.
Indexes improve performance by 10 to 500 times.
Index can improve the performance in following operations:
• Find the records matching with WHERE clause

UPDATE Books SET Availability = 1 WHERE SubjectId =12


DELETE FROM Books WHERE Price <10
SELECT * FROM Books WHERE Price BETWEEN 50 AND 80
• Sorting the result with ORDER BY

SELECT * FROM Books ORDER BY Price DESC


• Grouping records and aggregate values

SELECT Count(*) as Units, Price FROM Books GROUP BY Price


There are two types of indexes available in SQL Server: clustered and non-clustered
Clustered index
Clustered index physically reorders the records of a table. Therefore a table can have only one
clustered index. Usually a clustered index will be created on the primary key of a table.
Non – Clustered Index
Non – Clustered index are stored in the order of the index key values, but the information in the
table is stored in a different order. Means logical sorting of data not Physical. In SQl Server 2005
a table can have 249 non-clustered indexes.
Composite Indexes
A composite index is an index on two or more columns. Both clustered and non-clustered
indexes can be composite indexes. If you have composite index on Price and BookName then
take can take advantage of it like this:
SELECT BookName, Price FROM Products ORDER BY UnitPrice BookName, Price DESC
Attempt Free Asp.Net Interview Question Answer Online Test and check your
performance
Showing newest posts with label C#. Show older posts
Showing newest posts with label C#. Show older posts
Value types VS Reference types C#
What is difference between Value types and Reference types in VB.NET or C# (Value types
VS Reference types)

C# provides two types—class and struct, class is a reference type while the other is a value type.
Here is difference between Value types and Reference types.

Value types directly contain their data which are either allocated on the stack or allocated in-line
in a structure. Reference types store a reference to the value's memory address, and are allocated
on the heap. With reference types, an object is created in memory, and then handled through a
separate reference—rather like a pointer.

Reference types can be self-describing types, pointer types, or interface types. Primitive types
such as int, float, bool and char are value types.

Variables that are value types each have their own copy of the data, and therefore operations on
one variable do not affect other variables. Variables that are reference types can refer to the same
object; therefore, operations on one variable can affect the same object referred to by another
variable.

Value types have a default implied constructor that initializes the default value. Reference types
default to a null reference in memory.

Value types derive from System.ValueType. Reference types derive from System.Object.

Value types cannot derive a new type from an existing value type, except for structs. Reference
types can derive a new type from an existing reference type as well as being able to implement
interfaces.

1 comments
Tags: C#, Microsoft .NET Framework
Explain the delegates in C#.
Delegates in C# are objects which points towards a function which matches its signature.
Delegates are reference type used to encapsulate a method with a specific signature. Delegates
are similar to function pointers in C++; however, delegates are type-safe and secure.
Here are some features of delegates:
• A delegate represents a class.
• A delegate is type-safe.
• We can use delegates both for static and instance methods
• We can combine multiple delegates into a single delegate.
• Delegates are often used in event-based programming, such as publish/subscribe.
• We can use delegates in asynchronous-style programming.
• We can define delegates inside or outside of classes.
Syntax of using delegates

//Declaring delegate
delegate void SampleDelegate(string message);

// declare method with same signature:


static void SampleDelegateMethod(string message) { Console.WriteLine(message); }

// create delegate object


SampleDelegate d1 = SampleDelegateMethod;

// Invoke method with delegate


d1("my program");
What is the difference between abstract class and interface?
We use abstract class and interface where two or more entities do same type of work but in
different ways. Means the way of functioning is not clear while defining abstract class or
interface. When functionality of each task is not clear then we define interface. If functionality of
some task is clear to us but there exist some functions whose functionality differs object by
object then we declare abstract class.
We can not make instance of Abstract Class as well as Interface. They only allow other classes
to inherit from them. And abstract functions must be overridden by the implemented classes.
Here are some differences in abstract class and interface.
• An interface cannot provide code of any method or property, just the
signature. we don’t need to put abstract and public keyword. All the methods
and properties defined in Interface are by default public and abstract. An
abstract class can provide complete code of methods but there must exist a
method or property without body.

• A class can implement several interfaces but can inherit only one abstract
class. Means multiple inheritance is possible in .Net through Interfaces.

• If we add a new method to an Interface then we have to define


implementation for the new method in every implemented class. But If we
add a new method to an abstract class then we can provide default
implementation and therefore all the existing code might work properly.

1 comments
Tags: Interview Question Answer, Object Oriented Programming
What is the use of Master Pages in Asp.Net?
A master page in ASP.Net provides shared HTML, controls, and code that can be used as a
template for all of the pages of a website.
Every master page has asp:contentplaceholder control that will be filled by the content of the
pages that use this master page.
You can create a master page that has header and footer i.e. a logo, an image, left navigation bar
etc and share this content on multiple pages. You need not to put these things on every aspx
page.

0 comments
Tags: ASP.NET 2.0, Interview Question Answer
What is the difference between .Net Remoting and Asp.Net Web Services?
• ASP.NET Web Services Can be accessed only over HTTP but .Net Remoting
Can be accessed over various protocols like TCP, HTTP, SMTP etc.

• Web Services are based on stateless service architecture but .Net Remoting
support for both stateful and stateless environment.

• Web Services support heterogeneous environments means interoperability


across platforms but .Net remoting requires .Net on both server and client
end.

• .NET Remoting provides the fast communication than Web Services when
we use the TCP channel and the binary formatter.

• Web services support only the objects that can be serialized but .NET
Remoting can provide support to all objects that inherit MarshalByRefObject.

• Web Services are reliable than .Net remoting because Web services are
always hosted in IIS.

• Web Services are ease to create and deploy but .Net remoting is bit
complex to program.

0 comments
Tags: .Net Remoting, Interview Question Answer, Web Services
Newer Posts Older Posts Home

Subscribe to: Posts (Atom)


Explore me on WiZiQ

Twitter Updates

Followers

Subscribe To
Posts

Atom

Posts

All Comments

Atom

All Comments

My Blogs
• Project Management Tips

Popular Tags
• Interview Question Answer (8)
• Object Oriented Programming (5)
• Microsoft .NET Framework (4)
• ASP.NET Architecture (3)
• Database (3)
• C# (2)
• Microsoft SQL Server 2008 (2)
• sql query (2)
• .Net Remoting (1)
• ADO.NET (1)
• ASP.NET 2.0 (1)
• ASP.NET 3.5 (1)
• ASP.NET Controls (1)
• Asp.Net Performance Tips (1)
• Asp.Net Programming (1)
• Microsoft SQL Server (1)
• SQL Server (1)
• Web Services (1)
• XML (1)
• state management (1)

What is the purpose of connection pooling in ADO.NET?


Connection pooling enables an application to use a connection from a pool of connections that
do not need to be re-established for each use. Once a connection has been created and placed in a
connection pool, an application can reuse that connection without performing the complete
connection creation process.

By default, the connection pool is created when the first connection with a unique connection
string connects to the database. The pool is populated with connections up to the minimum pool
size. Additional connections can be added until the pool reaches the maximum pool size.

When a user request a connection, it is returned from the pool rather than establishing new
connection and, when a user releases a connection, it is returned to the pool rather than being
released. But be sure than your connections use the same connection string each time. Here is
the Syntax

conn.ConnectionString = "integrated Security=SSPI; SERVER=192.168.0.123;


DATABASE=MY_DB; Min Pool Size=4;Max Pool Size=40;Connect Timeout=14;";
What is the use of XSLT?
XSLT stands for Extensible Stylesheet Language Transformations. This language used in
XSL style sheets to transform XML documents into other XML documents.

XSLT is based on template rules which specify how XML documents should be processed. An
XSLT processor reads both an XML document and an XSLT style sheet. Based on the
instructions the processor finds in the XSLT style sheet, it produce a new XML document. With
XSLT we can also produce HTML or XHTML from XML document. With XSLT we can
add/remove elements and attributes, rearrange and sort elements, hide and display elements from
the output file. Converting XML to HTML for display is probably the most common application
of XSLT today.

Introduction
In this article, we will take a closer look at how ASP.NET pages post back to themselves, and
how to customize this feature in our web applications.

function __doPostBack(eventTarget, eventArgument)


One of the most important features of the ASP.NET environment is the ability to declare controls
that run on the server, and post back to the same page. Remember the days of classic ASP? We
would create a form which would accept the user's input, and then we would most probably have
to create another page that would accept all those inputs, either through HTTP GET or POST,
and perform some kind of validation, display and action. Sometimes, even a third page was
necessary to perform our actions. This wasted a lot of time and complicated things when you had
to make a change. But of course, this is not necessary any more with ASP.NET. There is no need
to create second pages that accept the inputs of the first, process them and so on. Form fields and
other controls can be declared to run on the server, and the server simply posts the page back to
itself and performs all the validation, display and actions. Our life as web developers has become
a million times better. But how exactly is this done?
When a control is declared to run on the server, a VIEWSTATE is created which remembers the
ID of that control, and the method to call when an action is performed. For example, let's say we
input this HTML on a page:
<script language="VB" runat="server">
Sub Test_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
'enter your code to perform
End Sub
</script>
<html>
<body>
<form runat="server" id="myForm">
<asp:linkbutton id="Test" runat="server" text="Create Text
file" onclick="Test_Click" />
</form>
</body>
</html>
This is a very simple page. We declare only one web control, a linkbutton, to run
on the server, with an ID of Test and we assign a method called Test_Click to run
when the link is clicked on the page. The linkbutton has to be wrapped inside a form
that runs on the server as well. We save the above as an ASPX page and then we
browse to it. The HTML that gets created looks like this:
State Management Techniques in ASP.NET

This article discusses various options for state management for web applications developed
using ASP.NET. Generally, web applications are based on stateless HTTP protocol which
does not retain any information about user requests. In typical client and server
communication using HTTP protocol, page is created each time the page is requested.

Developer is forced to implement various state management techniques when developing


applications which provide customized content and which "remembers" the user.
Here we are here with various options for ASP.NET developer to implement state
management techniques in their applications. Broadly, we can classify state management
techniques as client side state management or server side state management. Each
technique has its own pros and cons. Let's start with exploring client side state management
options.
Client side State management Options:

ASP.NET provides various client side state management options like Cookies, QueryStrings
(URL), Hidden fields, View State and Control state (ASP.NET 2.0). Let's discuss each of
client side state management options.
Bandwidth should be considered while implementing client side state management options
because they involve in each roundtrip to server. Example: Cookies are exchanged between
client and server for each page request.
Cookie:

A cookie is a small piece of text stored on user's computer. Usually, information is stored as
name-value pairs. Cookies are used by websites to keep track of visitors. Every time a user
visits a website, cookies are retrieved from user machine and help identify the user.

Let's see an example which makes use of cookies to customize web page.

if (Request.Cookies["UserId"] != null)
lbMessage.text = "Dear" + Request.Cookies["UserId"].Value + ", Welcome to our
website!";
else
lbMessage.text = "Guest,welcome to our website!";
If you want to store client's information use the below code
Response.Cookies["UserId"].Value=username;
Advantages:
• Simplicity
Disadvantages:
• Cookies can be disabled on user browsers
• Cookies are transmitted for each HTTP request/response causing overhead on
bandwidth
• Inappropriate for sensitive data
Hidden fields:

Hidden fields are used to store data at the page level. As its name says, these fields are not
rendered by the browser. It's just like a standard control for which you can set its
properties. Whenever a page is submitted to server, hidden fields values are also posted to
server along with other controls on the page. Now that all the asp.net web controls have
built in state management in the form of view state and new feature in asp.net 2.0 control
state, hidden fields functionality seems to be redundant. We can still use it to store
insignificant data. We can use hidden fields in ASP.NET pages using following syntax
protected System.Web.UI.HtmlControls.HtmlInputHidden Hidden1;

//to assign a value to Hidden field


Hidden1.Value="Create hidden fields";
//to retrieve a value
string str=Hidden1.Value;
Advantages:
• Simple to implement for a page specific data
• Can store small amount of data so they take less size.
Disadvantages:
• Inappropriate for sensitive data
• Hidden field values can be intercepted(clearly visible) when passed over a network
View State:

View State can be used to store state information for a single user. View State is a built in
feature in web controls to persist data between page post backs. You can set View State
on/off for each control using EnableViewState property. By default, EnableViewState
property will be set to true. View state mechanism poses performance overhead. View state
information of all the controls on the page will be submitted to server on each post back. To
reduce performance penalty, disable View State for all the controls for which you don't need
state. (Data grid usually doesn't need to maintain state). You can also disable View State for
the entire page by adding EnableViewState=false to @page directive. View state data is
encoded as binary Base64 - encoded which add approximately 30% overhead. Care must be
taken to ensure view state for a page is smaller in size. View State can be used using
following syntax in an ASP.NET web page.
// Add item to ViewState
ViewState["myviewstate"] = myValue;

//Reading items from ViewState


Response.Write(ViewState["myviewstate"]);

Advantages:
• Simple for page level data
• Encrypted
• Can be set at the control level
Disadvantages:
• Overhead in encoding View State values
• Makes a page heavy
Query strings:
Query strings are usually used to send information from one page to another page. They are
passed along with URL in clear text. Now that cross page posting feature is back in asp.net
2.0, Query strings seem to be redundant. Most browsers impose a limit of 255 characters on
URL length. We can only pass smaller amounts of data using query strings. Since Query
strings are sent in clear text, we can also encrypt query values. Also, keep in mind that
characters that are not valid in a URL must be encoded using Server.UrlEncode.
Let's assume that we have a Data Grid with a list of products, and a hyperlink in the grid
that goes to a product detail page, it would be an ideal use of the Query String to include
the product ID in the Query String of the link to the product details page (for example,
productdetails.aspx?productid=4).
When product details page is being requested, the product information can be obtained by
using the following codes:
string productid;
productid=Request.Params["productid"];
Advantages:
• Simple to Implement
Disadvantages:
• Human Readable
• Client browser limit on URL length
• Cross paging functionality makes it redundant
• Easily modified by end user
Control State:
Control State is new mechanism in ASP.NET 2.0 which addresses some of the shortcomings
of View State. Control state can be used to store critical, private information across post
backs. Control state is another type of state container reserved for controls to maintain their
core behavioral functionality whereas View State only contains state to maintain control's
contents (UI). Control State shares same memory data structures with View State. Control
State can be propagated even though the View State for the control is disabled. For
example, new control Grid View in ASP.NET 2.0 makes effective use of control state to
maintain the state needed for its core behavior across post backs. Grid View is in no way
affected when we disable View State for the Grid View or entire page
Server Side State management:
As name implies, state information will be maintained on the server. Application, Session,
Cache and Database are different mechanisms for storing state on the server.
Care must be taken to conserve server resources. For a high traffic web site with large
number of concurrent users, usage
of sessions object for state management can create load on server causing performance
degradation
Application object:
Application object is used to store data which is visible across entire application and shared
across multiple user sessions. Data which needs to be persisted for entire life of application
should be stored in application object.
In classic ASP, application object is used to store connection strings. It's a great place to
store data which changes infrequently. We should write to application variable only in
application_Onstart event (global.asax) or application.lock event to avoid data conflicts.
Below code sample gives idea
Application.Lock();
Application["mydata"]="mydata";
Application.UnLock();
Session object:
Session object is used to store state specific information per client basis. It is specific to
particular user. Session data persists for the duration of user session you can store session's
data on web server in different ways. Session state can be configured using the <session
State> section in the application's web.config file.
Configuration information:

<sessionState mode = <"inproc" | "sqlserver" | "stateserver">


cookieless = <"true" | "false">
timeout = <positive integer indicating the session timeout in minutes>
sqlconnectionstring = <SQL connection string that is only used in the SQLServer mode>
server = <The server name that is only required when the mode is State Server>
port = <The port number that is only required when the mode is State Server>
Mode:

This setting supports three options. They are InProc, SQLServer, and State Server

Cookie less:
This setting takes a Boolean value of either true or false to indicate whether the Session is a
cookie less one.
Timeout:
This indicates the Session timeout vale in minutes. This is the duration for which a user's
session is active. Note that the session timeout is a sliding value; Default session timeout
value is 20 minutes

SqlConnectionString:
This identifies the database connection string that names the database used for mode
SQLServer.

Server:
In the out-of-process mode State Server, it names the server that is running the required
Windows NT service: aspnet_state.

Port:

This identifies the port number that corresponds to the server setting for mode State
Server. Note that a port is an unsigned integer that uniquely identifies a process running
over a network.
You can disable session for a page using EnableSessionState attribute. You can set off
session for entire application by setting mode=off in web.config file to reduce overhead for
the entire application.
Session state in ASP.NET can be configured in different ways based on various parameters
including scalability, maintainability and availability
• In process mode (in-memory)- State information is stored in memory of web server
• Out-of-process mode- session state is held in a process called aspnet_state.exe that
runs as a windows service.
• Database mode – session state is maintained on a SQL Server database.
In process mode:

This mode is useful for small applications which can be hosted on a single server. This
model is most common and default method to store session specific information. Session
data is stored in memory of local web server
Configuration information:
<sessionState mode="Inproc"
sqlConnectionString="data source=server;user id=freelance;password=freelance"
cookieless="false" timeout="20" />
Advantages:
• Fastest mode
• Simple configuration
Disadvantages:
• Session data will be lost if the worker process or application domain recycles
• Not ideal for web gardens and web farms
Out-of-process Session mode (state server mode):

This mode is ideal for scalable and highly available applications. Session state is held in a
process called aspnet_state.exe that runs as a windows service which listens on TCP port
42424 by default. You can invoke state service using services MMC snap-in or by running
following net command from command line.
Net start aspnet_state
Configuration information:

<sessionState mode="StateServer"
StateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;user id=freelance; password=freelance"
cookieless="false" timeout="20"/>
Advantages:
• Supports web farm and web garden configuration
• Session data is persisted across application domain recycles. This is achieved by
using separate worker process for maintaining state
Disadvantages:
• Out-of-process mode provides slower access compared to In process
• Requires serializing data
SQL-Backed Session state:
ASP.NET sessions can also be stored in a SQL Server database. Storing sessions in SQL
Server offers resilience that can serve sessions to a large web farm that persists across IIS
restarts.

SQL based Session state is configured with aspnet_regsql.exe. This utility is located in .NET
Framework's installed directory
C:\<windows>\microsoft.net\framework\<version>. Running this utility will create a
database which will manage the session state.
Configuration Information:
<sessionState mode="SQLServer"
sqlConnectionString="data source=server;user id=freelance;password=freelance"
cookieless="false" timeout="20" />
Advantages:
• Supports web farm and web garden configuration
• Session state is persisted across application domain recycles and even IIS restarts
when session is maintained on different server.
Disadvantages:
• Requires serialization of objects
Choosing between client side and Server side management techniques is driven by various
factors including available server resources, scalability and performance. We have to
leverage both client side and server side state management options to build scalable
applications.
When leveraging client side state options, ensure that little amount of insignificant
information is exchanged between page requests.
Various parameters should be evaluated when leveraging server side state options including
size of application, reliability and robustness. Smaller the application, In process is the
better choice. We should account in the overheads involved in serializing and deserializing
objects when using State Server and Database based session state. Application state should
be used religiously.

Beginners Introduction to State Management Techniques


in ASP.NET
By N a v a n e e t h | 23 Dec 2008

This article discusses the state management techniques used in ASP.NET. We


discuss: QueryString, Cookie, Session, Profile, Static Variables and Application state.

Is your email address OK? You are signed up for our newsletters but your
email address has not been reconfirmed in a long time. To make this warning go
away please click here to have a confirmation email sent so we can confirm your
email address and continue sending you your newsletters. Alternatively, you can
update your subscriptions.
Top of Form
/w EPDw UKMTAy

/w EWCALn17PqD

• Download source - 24.7 KB

Table of Contents
• Introduction
• HTTP protocol and the Need for State Management Techniques
• QueryString
○ QueryString Encoding
○ Reading QueryString Safely
○ Pros and Cons
○ Producing Hackable URLs
○ Securing QueryString
• Cookies
○ Some Useful Properties you Must Know Before Using Cookies
○ Multi-Valued Cookies
○ A Practical Example
○ Security Constraints
○ Pros and Cons
• Session State
○ How Session Works?
○ Session Timeout
 Session Timing out Frequently
○ Where Session is Stored?
○ Usage and Best Practices
 Wrapping Session in a Strongly Typed Class
 Base Page Class Approach
• Application State
○ Understanding Session and Application Events
○ A Practical Example
• Keeping State in Static (shared in VB) Variables
• Profiles
• Hacking viewstate
• Conclusion
• History

Introduction
Recently Code Project started a beginners walkthrough for web development, an initiative for
organizing all the information required for web development under one article. I think it will be
helpful for beginners to get guidelines for web development. This article is my contribution to
the ASP.NET section where I describe the state management techniques and best practices
used when developing with ASP.NET.

HTTP Protocol and the Need for State Management Techniques


Hyper Text Transfer Protocol (HTTP) is a communication protocol which is implemented in the
"World Wide Web(WWW)". It is a request/response style protocol. Clients (browsers, spider,
etc) will request to a server (web server) and the server responds to these requests. HTTP uses
TCP protocol for communication. It connects to a specific port (default is 80) to the server and
communicates via that port. Once the response is received completely, client programs will be
disconnected from the server. For each request, client programs have to acquire a connection
with servers and do all the request cycles again.
ASP.NET files are just text files which will be placed in the server and served upon the request.
When a request comes for a page, the server will locate the requested file and ask the ASP.NET
engine to serve the request. The ASP.NET engine will process the server tags and generate
HTML for it and return back to the client. HTTP is a stateless protocol and the server will
abandon the connection once the request is served.
Since HTTP is stateless, managing state in web applications is challenging. State management
techniques are used to maintain user state throughout the application. Managing state in a
stand-alone application is trivial as they don't have a request/response nature. Information you
want to maintain over the lifetime of a web applications depends on your context. It can be from
simple numbers to very complex objects.
Understanding the state management techniques play a major role in creating efficient web
applications. ASP.NET is very rich in state management techniques. The following are the
commonly used state management techniques.
• QueryString
• Cookies
• Cache
• ViewState
• Session state
• Application state
• Static variables
• Profiles
Cache and ViewState are already explained in the previous sections and this article will not
cover it.
QueryString
This is the most simple and efficient way of maintaining information across requests. The
information you want to maintain will be sent along with the URL. A typical URL with a query
string looks like

Collapse

www.somewebsite.com/search.aspx?query=foo
The URL part which comes after the ? symbol is called a QueryString. QueryString has two
parts, a key and a value. In the above example, query is the key and foo is its value. You can
send multiple values through querystring, separated by the & symbol. The following code shows
sending multiple values to the foo.aspx page.

Collapse

Response.Redirect("foo.aspx?id=1&name=foo");
The foo.aspx page will get the values like in the following table.
Valu
Key
e

id 1

nam
foo
e

The following code shows reading the QueryString values in foo.aspx

Collapse

string id = Request.QueryString["id"];
string name = Request.QueryString["name"];
Request.QueryString has two overloaded indexers. One accepts the key name and another a
zero-based index. The latter is useful when you don't know the query string names. If you try to
get a value which is not in the QueryString collection, you will get a NULL reference.
QueryString Encoding
The URL RFC [^] states that, a URL can have only ASCII characters. So all the other characters
should be encoded when you pass through the URL. The .NET Framework provides the
HttpServerUtility.UrlEncode class to encode the URL.
The following code shows how name and id is passed to foo.aspx page as encoded.

Collapse

string id = "1";
string name = "foo#";
string url = string.Format("foo.aspx?{0}&{1}", Server.UrlEncode(id),
Server.UrlEncode(name));
Response.Redirect(url);
// decoding can be done using it's counter part
HttpServerUtility.UrlDecode()

string id = Server.UrlDecode(Request.QueryString["id"]);
string name = Server.UrlDecode(Request.QueryString["name"]);
Note: HttpServerUtility is available to your code in all webforms through the Page.Server
property. Also you only need to encode those values which have non-ASCII characters, not all
the values.
Reading QueryString Safely
I have seen many people use code as shown below to read values from a QueryString collection

Collapse

// Bad practice - Don't use!


Request.QueryString["id"].ToString();
This is hilarious. Request.QueryString[key] returns a string and has no need to convert it
again to string. Another problem with the above code is, Request.QueryString[key] will
return NULL if the specified key not found in the collection. In such cases, calling
Request.QueryString[key].ToString() will lead to a NullReferenceException. The
following code shows reading a QueryString value safely.

Collapse

string queryStringValue = Request.QueryString["key"];


if (string.IsNullOrEmpty(queryStringValue)) {
// querystring not supplied. Do necessary action
}
else
// Querystring supplied. continue execution

Pros and Cons


Query string is lightweight and will not consume any server resources. It is very easy to use and
it is the most efficient state management technique. However, it has many disadvantages.
• You can pass information only as a string. If you need to pass objects in any
case through QueryString, methods explained in this excellent article [^] will
work. But it involves more effort.
• URL length has limitations. So you can't send much information through URL.
• Information passed is clearly visible to everyone and can be easily altered.
Producing Hackable URLs
URLs should be hackable, which means that, a user should be able to easily navigate from page
to page by modifying the QueryString values. But you need to make sure that your website's
security is not getting compromised by implementing this. A good example for hackable URLs is
on MSDN. Consider the following

Collapse
// System.Object classes documentation for .NET 1.1
http://msdn.microsoft.com/en-us/library/system.object(VS.71).aspx

// System.Object classes documentation for .NET 2.0. Just change the 71 to 80


http://msdn.microsoft.com/en-us/library/system.object(VS.80).aspx
This helps users to navigate between pages more easily.
Securing QueryString
Since values in QueryString can be tampered easily, it is a programmer's job to ensure that it has
valid values. You might be wondering, if QueryString is insecure, then why try to secure it
instead of using some secure state management techniques? In some cases, you can't avoid
using QueryString and you will be forced to send sensitive information through that. Consider a
user email validation system. When user registers, the system will send a mail with a link to
activate the user account. In this case, we have to pass some identification for the user account
along with the URL. Since user account information is sensitive, we have to encrypt the
QueryString value in the email validation link.
Consider a Edit.aspx?pid= page which allows to edit your personal details. You need to ensure
the person id supplied has a valid type, integer in this case. The following code shows how this is
done

Collapse

string queryStringValue = Request.QueryString["pid"];


if (string.IsNullOrEmpty(queryStringValue)) {
// querystring not supplied. Do necessary action
}
else {
// Querystring supplied. continue execution
int personId;
if(!int.TryParse(queryStringValue,out personId))
// invalid type specified. Alert user
}
Then you may need to check whether the currently logged user is authorized to edit this record.

Collapse

int personId;
if (int.TryParse(queryStringValue, out personId)) {
// check the edit permissions here
}
System.Security.Cryptography namespace has classes which help to encrypt strings. You can
pass the encrypted string through the URL, so that it is tamperproof and secure up to a certain
extent.

Cookies
A cookie is a small file which is stored in the visitor's hard disk drive. This is helpful for storing
small and trivial information. According to the RFC [^] , a cookie can have a maximum size of
4KB. The web server creates a cookie, attaches an additional HTTP header to the response, and
sends it to the browser. The browser will then create this cookie in a visitor's computer and
includes this cookie for all further requests made to the same domain. Servers can read the
cookie value from the request and retain the state.
The server adds the following to the HTTP header for creating a cookie

Collapse

Set-Cookie: key=value
The browser reads the above value and creates cookies at the user's end. It adds the cookie value
to the request like

Collapse

Cookie: key=value
Note: The location where the cookie is stored is completly controlled by the browser. Sometimes
it may keep the cookie in its memory instead of creating a file.
Creating and using a cookie is trivial in ASP.NET. The HttpCookie class is a key/value
collection which allows storing string values. The following code shows how to create a cookie
and send it to the client. Cookies are added using Response property and retrieved using
Request.

Collapse

Response.Cookies["id"].Value = "10";
Since no expiry time specified, a cookie added like the above method will be cleared by the
browser immediately when it is closed. If you would like to keep the cookie for a long time, you
have to use the HttpCookie.Expires property set with an expiration date. The following code
shows how to do that.

Collapse

// this cookie expires after one day from the date it is set
// browser will take care about removing the cookies after the expiry time
Response.Cookies["id"].Value = "10";
Response.Cookies["id"].Expires = DateTime.Now.AddDays(1);
Once you set the cookie, the browser will include it for every request. You read the cookie from
the Request.Cookies collection by specifying cookie name. Consider the following code

Collapse

// for safety, always check for NULL as cookie may not exist
if (Request.Cookies["id"] != null) {
string userId = Request.Cookies["id"].Value;
Response.Write("User Id value" + userId);
}
Cookies are managed by the browser and will take care about removing expired cookies. If you
need to remove a cookie before the expiry period, you have to create a cookie with the same
name and with an expiry date that is already passed. This will make browser think that the cookie
is expired and will be removed immediately. Here is how you do that
Collapse

Response.Cookies["id"].Expires = DateTime.Now.AddDays(-1);

Some Useful Properties you Must Know Before Using Cookies


Property
Description
name

Specifies which domain is associated with this cookie. Default is the


Domain
current domain. See security constraints later in this article

Expires A DateTime value specifies the expiry time of the cookie

Cookies can be accessed using java script. Setting this property prevents
HttpOnly
cookies being accessed from java script

Secure Set this if cookies are transmitted over SSL

Name Cookie name

Value Cookie value (string)

Multi-valued Cookies
RFC states that a browser should not store more than 20 cookies from a domain. Multi-Valued
cookie is very handy when you have more items to keep in cookie. To create a multi-valued
cookie, you instantiate the HttpCookie instance and set it's values. Consider the following code

Collapse

HttpCookie cookie = new HttpCookie("user");


cookie["name"] = "Foo";
cookie["age"] = "22";
cookie.Expires = DateTime.Now.AddDays(1);
Response.Cookies.Add(cookie);
Here is how you read it

Collapse

HttpCookie cookie = Request.Cookies["user"];


// for safety, always check for NULL. If cookie doesn't exist, it will be
NULL
if (cookie != null) {
string name = cookie["name"];
string age = cookie["age"];
}
else
// Cookie not exist

A Practical Example
You might have noticed the "Remember me next" time option in most of the websites. This is
done using cookies. The following steps will be involved when you choose this option.
• When the user checks the "Remember me next time" option, create a cookie
with a value to identify the user (eg: user id).
• When the page loads, check for cookie existence. If it exists, read the cookie
value.
• Authenticate the value and create a session.
Security Constraints
Since cookies are stored in the visitors computer, to prevent it from harming the system,
browsers ensure some security constrains to cookies. THe following points explain the security
constraints:
• Cookies are specific to domains, which mean that a cookie set from
"DomainA" is not accessible to "DomainB". Browsers store the domain with
each cookie and will ensure it won't be sent to another domain.
• Other restriction is in size. Browsers will not allow storing cookies for more
than 4KB from a domain.
• Browsers provides the option to disable cookies
Proper design of the application can avoid malicious attacks through cookies. Consider a website
which sets the current user id in a cookie for retaining the user account information in subsequent
visits. Since the cookie is kept in the visitor's system as plain text, the user can always goto the
folder where the cookie is kept and change the user id to some other value. When the website is
requested again, it will use the new user id which will give the hacker access to the new account.
While cookies are mostly used for storing account information, they are really not intended for
such use. You should always take precautions to avoid hacks like the above by encrypting the
values before keeping in cookie.
Pros and Cons
A cookie is a very handy and easily usable state management technique. It is useful when you
want to keep small information that is needed for long periods of time. The processing overhead
of cookies is much less compared to sessions. However, it has the following disadvantages:
• Cookies have a size limitation of 4KB. Storing huge information is not
possible.
• Cookies can be easily tampered as they are kept in the client's machine. So
additional security checking has to be done when using them.
• The user can disable cookies.

Session State
A cookie is very simple and is not suitable for sophisticated storage requirements. Session state
is a workaround for this problem and it gives a method to keep more complex objects securely.
ASP.NET allows programmers to keep any type of objects in session. Data stored in session will
be kept in server memory and it is protected as it will never get transmitted to a client. Every
client that uses the application will have separate sessions. Session state is ideal for storing user
specific information.
The following code shows storing a string value in session.

Collapse

Session["name"] = "Navaneeth";
Session accepts a System.Object type. So you need a type cast when reading. Reading values
from session is like

Collapse

string name = Session["name"] as string;


// null checking is needed as session may not exist
if(!string.IsNullOrEmpty(name))
// use the name here
Values stored in sessions can be removed by several methods. The following table shows
different methods used.
Method Description

Cancels the session and fires end event. This is used


Session.Abandon()
when you are done with the session.

Session.Clear() / Clears all contents of the session. This will not end the
Session.RemoveAll() session

Session.Remove(string) Removes the session name supplied.

How Session Works?


ASP.NET maintains a unique id which is called as "session id" for each session. This id is
generated using a custom algorithm and it is unique always. Session id will be sent to the client
as a cookie and the browser resends this upon each request. ASP.NET uses this session id to
identify the session object. The following code shows how to get the session id

Collapse

string sessionId = Session.SessionID;


If you haven't stored anything in the session, ASP.NET will generate a different session id for
each request. Once a session has contents, the session id will not change. Session id is the only
information which is sent to the client about sessions. As said before, ASP.NET sends session id
in a cookie named ASP.NET_SessionId. But this will not work if cookies are disabled by the
visitor. In such cases, ASP.NET passes session id through the URL. This behaviour can be
controlled by adding the following section to web.config file under the system.web section.

Collapse

<sessionState
cookieless="UseUri" />
Note: ASP.NET AJAX extensions won't work as expected if this is enabled.
Session Timeout
Each session will have a timeout value (default 20Mins). If the page is not getting any requests
within the timeout limit specified, ASP.NET will assume that the user has left the application
and it immediately terminates the session and fires the End event. This helps the server to
cleanup unused sessions and gives room for new requests. Timeout value can be changed from
web.config file or through code. Timeout value is specified in minutes.

Collapse

<sessionState
timeout="60" />

or

Session.Timeout = 60;

Session Timing out Frequently


I have seen many questions on discussion forums which state, "My session timeout is 60
minutes and it is timing out before that." Well, ASP.NET will clear session when any of the
following happens
• ASP.NET worker process recycles frequently. When this happens, it will clear
all active sessions.
• When files like web.config or application assemblies are modified, ASP.NET
will recyle the worker process.
Where Session is Stored?
ASP.NET allows three types of session storage which are described below
Storage
Mode Configuration Description Pros/Cons
location

InProc <sessionState ASP.NET This is the As the InProc


mode="InProc" /> process default session mode keeps data
es storage. Session in same
memory data will be processes
area kept in the memory area,
server memory. any impacts
InProc mode is happened for the
a high ASP.NET worker
Storage
Mode Configuration Description Pros/Cons
location

performant as it
reads from the
same processes
memory and it
allows you to
keep all .NET process will
types. If session affect the
mode is not session data.
specified,
ASP.NET will
use InProc as
the default
mode.

StateServer
mode provides
a basic level of
isolation for the
data storage. It
runs as a
It is less
separate
performant
windows service
compared to
<sessionState Server and keeps the
InProc mode. But
mode="StateServer" memory session data out
StateSer this helps you to
stateConnectionString= as a of ASP.NET
ver "tcpip=Yourservername:42424" seprate process avoid loosing
/> session data
process memory area.
when ASP.NET
To access
worker process
session,
restarts.
ASP.NET
process has to
communicate
with this
external
process.

SQL <sessionState In SQL If you still need • Slow data


Server mode="SQLServer" server more resillient access
sqlConnectionString="..." />
databas storage,
• Allows to
e SQLServer store only
mode is the serializabl
choice. It allows
Storage
Mode Configuration Description Pros/Cons
location

to keep session
data in
SQLServer. This
is helpful when
your web e types
application is
hosted in a
webfarm.

If any of the above discussed methods are not satisfying your storage requirements, ASP.NET
allows to specify a custom storage provider. This [^] article shows how to do this.
Usage and Best Practices
Incorrect usage of session will blow up your application. The most common error users make is
the NULL reference exceptions when using sessions. Consider the following code

Collapse

// bad code ! don't use


string name = Session["name"].ToString();
This code is problematic as session["name"] may not exist or may be NULL and ToString()
will be called on that NULL reference which will throw the common "Object reference not set to
an instance of the object" error.
Another problem with session is that it is not strongly typed. Session keeps System.Object type
which means every .NET type can be kept in session. Consider the following code

Collapse

Session["age"] = "I can store a value that is not number!";


Since it is not strongly typed, Session["age"] can contain any value and you will have
problems when using this. Also, you may make typing mistakes when typing the session names.
This will also lead to unexpected behaviours. The following section describes workarounds for
these problems.
Wrapping Session in a Strongly Typed Class
To workaround the above problems, we can create a strongly typed wrapper classes around the
session and route all calls to session through this wrapper. Consider a simple scenario where you
need to keep user details like name, age, email validated etc in a session. We create a class to
represent all required fields. See the following code

Collapse

public class PersonSession


{
// This key is used to identify object from session
const string KEY = "personDetails";

public PersonSession(int id,string name,int age,bool emailValidated)


{
this.Id = id;
this.Name = name;
this.Age = age;
this.HasEmailValidated = emailValidated;
}

public static PersonSession GetPersonSession() {


return HttpContext.Current.Session[KEY] as PersonSession;
}

public static void CreatePersonSession(PersonSession person) {


HttpContext.Current.Session[KEY] = person;
}

public int Id { get; private set; }


public string Name { get; private set; }
public int Age { get; private set; }
public bool HasEmailValidated { get; private set; }
}
The above given class abstracts the session access and provides a clear interface to access the
session contents safely. The static methods CreatePersonSession and GetPersonSession can
be used to create and get details of a person from session. The following code shows how to
store person details into session.

Collapse

PersonSession person = new PersonSession(int.Parse(txtPersonId.Text),


txtName.Text, int.Parse(txtAge.Text), chkEmailValidated.Checked);
PersonSession.CreatePersonSession(person);
To retrieve person details, you need to do

Collapse

PersonSession person = PersonSession.GetPersonSession();


// if session not exist, this will return NULL
if (person != null) {
// person exist. Use person's properties to get values
}
Note: HttpContext.Current.Session is needed when accessing from a class that is not
derived from System.Web.UI.Page.
Base Page Class Approach
Assume that you need to prevent users from seeing your page unless person details exists in
session. You may end up doing the following code for all the pages that needs to be secured.

Collapse

protected void Page_Load(object sender, EventArgs e)


{
PersonSession person = PersonSession.GetPersonSession();
// if session not exist, this will return NULL
if (person == null) {
// session not exist. Redirect user to login page
}
}
Writing the above code in all pages that needs session is redundant. It is very tough to make a
change if something got changed in the session wrapper class-PersonSession. The recommended
approach is to keep a base page class which is derived from System.Web.UI.Page and all your
pages which need PersonSession should inherit from this base page class. This allows you to
do the session checking in the base class and redirect the user if required. The following diagram
shows this approach.
We create two classes NormalPage and SecuredPage both derived from System.Web.UI.Page.
SecuredPage overrides the OnInit method which looks like this:

Collapse

protected override void OnInit(EventArgs e) {


base.OnInit(e);
// check the person details existance here
PersonSession person = PersonSession.GetPersonSession();
if (person == null) {
Response.Redirect("NotLogged.aspx");
}
else
this.Person = person;
}
If person details are not found in the session, it redirects to the NotLogged.aspx page and it sets
the Person property if session exists. Classes which derive from this class can use this Person
property to access the person details. Usage of this class is pretty straightforward. See the
following code.

Collapse

public partial class AuthenticatedPage : SecuredPage


{
protected void Page_Load(object sender, EventArgs e)
{
lblMessage.Text = "Session exist";
lblMessage.Text += string.Format("Person Id : {0}",Person.Id);
lblMessage.Text += string.Format("Person Name : {0}", Person.Name);
lblMessage.Text += string.Format("Person Age : {0}", Person.Age);
lblMessage.Text += string.Format("Email validated? : {0}",
Person.HasEmailValidated);

}
}
Note: We are not using NormalPage here. If you have any particular behaviour common for all
non-authenticated pages, this class is the best place to add that.
That's all about sessions. When using it, try not to abuse sessions. Overusing sessions may
degrade your application performance.

Application State
ASP.NET implements application state using the System.Web.HttpApplicationState class. It
provides methods for storing information which can be accessed globally. Information stored on
application state will be available for all the users using the website. Usage of application state
is the same as sessions. The following code shows storing a value in an application variable and
reading from it.

Collapse

Application["pageTitle"] = "Welcome to my website - ";

// Reading the value from application variable


string pageTitle;
if (Application["pageTitle"] != null)
pageTitle = Application["pageTitle"].ToString();

Understanding Session and Application Events


Before we discuss the practical usage of application state, you should get a basic knowledge
about the events associated with application and session. These events can be seen in the
global.asax file. See the following table for the details.
Event name Description

Application_St This event executes when application initializes. This will execute
art when ASP.NET worker process recycles and starts again.

Application_E
Executes when the application ends.
nd

Session_Start Executes when a new session starts.

Executes when session ends. Note : this event will be fired only if you
Session_End
are using InProc as session mod.

A Practical Example
The most common usage of application variables is to count the active number of visitors that are
browsing currently. We can utilize session_start and session_end events to do this. The
following code shows how this is done.
Collapse

void Application_Start(object sender, EventArgs e)


{
// Application started - Initializing to 0
Application["activeVisitors"] = 0;

void Session_Start(object sender, EventArgs e)


{
if (Application["activeVisitors"] != null) {
Application.Lock();
int visitorCount = (int)Application["activeVisitors"];
Application["activeVisitors"] = visitorCount++;
Application.UnLock();
}
}
You might have noticed Application.Lock() and Application.UnLock() calls. ASP.NET is
multithreaded and this is required to synchronize data when multiple visitors access the site at
the same time.
Application state is not providing any timeout method like session. Application state will be
available until the application ends. So one should be very careful when using application state.
You should explicitly cleanup the values stored when you are finished using it.

Keeping State in Static (shared in VB) Variables


Static variables will have a lifetime until the application domain where it is hosted ends.
ASP.NET hosts each website in a separate application domain to provide isolation with other
websites hosted on the same server.
Consider you have a page where all product details are displayed. Product details are fetched
from the database and filled into custom collection and returned back to the page. To avoid
fetching product details all time for each visitors, we can load it when it is requested for the first
time and keep it in a static variable to serve for the next requests. Consider the following
Product and ProductServices class.

Collapse

class Product
{
public Product(int id,string name) {
this.Id = id;
this.Name = name;
}
public int Id { get; private set; }
public string Name { get; private set; }
}

class ProductService
{
static List<Product> products = null;
static readonly object locker = new object();
public static List<Product> GetAllProducts() {
// If product is NULL, loading all products and returning
if (products != null) {
lock (locker) {
if (products != null) {
// fill the products here
}
}
}
return products;
}
}
The above given code is self explanatory. The variable products will have a lifetime until the
application domain unloads. When ProductService.GetAllProducts() is called for the first
time, it fills the collection and return. For the further requests, it will just return the collection
which is already filled.
Values kept in static variables are accessible to all visitors in the website. So you should take
extra care when writing methods like the above. You need locking because multiple visitors may
call the GetAllProducts method at the same time.
The above given example is an implementation of the " Singleton pattern [^] ".

Profiles
Session data is lost when the visitor leaves the webpage. What if you need to persist all the user
information for a long time? ASP.NET Profile is the answer. It provides a neat way to persist
information for a long time. Creating a profile is trivial. You only need a few entries in the
web.config file as seen below

Collapse

<profile>
<properties>
<add name="Id" type="Int32"/>
<add name="Name"/>
<add name="Age" type="Int32"/>

</properties>
</profile>
ASP.NET generates a strongly typed class for accessing profile data. Data type for the properties
are chosen depending upon the type value. Default type is string if no type is specified.
Following code shows setting values and reading back from profile.

Collapse

Profile.Name = txtName.Text;
Profile.Id = int.Parse(txtPersonId.Text);
Profile.Age = int.Parse(txtAge.Text);

// to read profile value, use

int age = Profile.Age;


string name = Profile.Name;
int id = Profile.Id;
ASP.NET keeps the profile data in SQLServer database. If no databases are available in the
project, it creates a database file in the app_data directory when it is used for the first time.
Profiles are implemented using the provider pattern. SQLProfileProvider is the default profile
provider. Profiles use windows authentication by default. Profile object can be used with any
authentication modes supported by ASP.NET.
Profile is very handy in many situations. However, it has the following drawbacks
• It allows to keep only serializable types
• Reading data from profile requires database access which can potentially
make your application less performant. If your website uses profiles heavily,
you have to cache the results to avoid unncessary database calls.
This is a high level overview of profile. There are many other features profile offers
such as groups, anonymous access etc. Explaining whole profile detail is beyond the
scope of this article. Check this [^] MSDN article for more details.

Hacking ViewState
ViewState is already explained in the previous section [^] . Articles that talk about viewstate
always say, it is less secure and not good for keeping secure information. Let us see how a
viewstate value can be hacked.
Data kept in Viewstate is serialized using LosFormater, a less known class used for
serialization. LosFormatter is helpful to serialize simple types and it produces ASCII string
representation of the object graph. The following code shows using LosFormatter.

Collapse

[Serializable]
class Customer
{
public Customer(int age,string name) {
this.Age = age;
this.Name = name;
}
public int Age { get; set; }
public string Name { get; set; }
}

string Serialize() {

// Creating customer object


Customer customer = new Customer(25,"Navaneeth");

// formatting
LosFormatter formatter = new LosFormatter();
using (StringWriter output = new StringWriter()) {
formatter.Serialize(output, customer);
return output.ToString();
}
}
The above code serializes the object graph and produces an ASCII string which can be
transmitted over HTTP.
The following code shows decrypting viewstate values.

Collapse

object HackViewstate(string viewStateValue) {


LosFormatter formatter = new LosFormatter();
return formatter.Deserialize(viewStateValue);
}
The following figure shows the contents of the object which is deserialized

This gives you a clear explanation of why secured data should not be kept on viewstate.

Conclusion
This article tackled the state management techniques used in ASP.NET. You have learned
what is HTTP protocol and the need for state management. We discussed the stateless
architecture of HTTP protocol and how a website works.
In the second section, we discussed QueryString and how it helps to maintain information across
different pages. We also discussed about hackable URLs and some best practices for using it.
The third section discussed the usage of cookies. We have seen the pros and cons of cookies. We
also discussed multi-valued cookies which helps to overcome the number of cookies a website
can set. Security constraints and a practical example have also been discussed.
The next section discussed "Session state" which provides more sophisticated storage. We
have seen how session works, session modes and best practices for using it. We have also
discussed about session timeout and cookie-less sessions.
"Application state" is discussed in the next section. Discussed about the events which are
associated with session state and application state. We have seen a practical example where
application state is very handy. Then we discussed about storing the state in static(shared in
VB) variables. We have seen the lifetime of a static variables and how locking is used to
synchronize access between multiple threads. Profiles are very handy when you need to persist
information for long periods of time. We have discussed profiles in the next section and seen
simple usage of profiles.
Finally, we discussed viewstate hacking techniques and proved secured information should not
be kept on viewstate. We discussed about the serialization class LosFormatter and how it
works.
That's all about this article. I hope you will find it helpful. I'd appreciate if you rate this article
and leave your feedback below.
Thank you for reading, happy coding!
Bottom of Form

Vous aimerez peut-être aussi