Vous êtes sur la page 1sur 40

The surest way to write a sluggish Web application is to perform file or database accesses on every request.

Every developer
knows that reading and writing memory is orders of magnitude faster than reading and writing files and databases. Yet it's
surprising how many of the same developers build ASP and ASP.NET pages that hit a file or database on each and every page
access.

(continued)

Take, for example, the ASP.NET page in Figure 1. Each time the page is fetched, its Page_Load method opens a text file named
Quotes.txt, reads it line by line, and stores the lines in an ArrayList. It then selects a random item from the ArrayList and writes
it to the page using a Label control. Because Quotes.txt contains a collection of famous (and not-so-famous) quotations, each
page refresh displays a randomly selected quotation on the page, as shown in Figure 2.

Figure 1: DumbQuotes.aspx

<%@ Import Namespace="System.IO" %>

<html>
<body>
<asp:Label ID="Output" RunAt="server" />
</body>
</html>

<script language="C#" runat="server">


void Page_Load (Object sender, EventArgs e)
{
ArrayList quotes = new ArrayList ();
StreamReader reader = null;

try {
reader = new StreamReader (Server.MapPath
("Quotes.txt"));

for (string line = reader.ReadLine (); line != null;


line = reader.ReadLine ())
quotes.Add (line);

Random rand = new Random ();


int index = rand.Next (0, quotes.Count);
Output.Text = (string) quotes[index];
}
finally {
if (reader != null)
reader.Close ();
}
}
</script>

Figure 2: DumbQuotes.aspx in action


Click here for larger image

So what's wrong with this picture? Nothing-unless, that is, you value performance. Each time DumbQuotes.aspx is requested, it
reads a text file from beginning to end. Consequently, each and every request results in a physical file access.

Simple as it is, DumbQuotes.aspx can benefit greatly from the ASP.NET application cache. The ASP.NET application cache is a
smart in-memory repository for data. It's smart because it allows items entrusted to it to be assigned expiration policies, and
also because it fires notifications when it removes items from the cache, affording applications the opportunity to refresh the
cache by replacing old data with new. It's also flexible. It's capable of caching instances of any type that derives from
System.Object, from simple integers to complex types that you define yourself.

Syntactically, using the ASP.NET application cache couldn't be simpler. Pages access it through the Cache property that they
inherit from System.Web.UI.Page; Global.asax files access it through the Cache property of the Context property inherited from
System.Web.HttpApplication. The statement

Context.Cache.Insert ("MyData", ds);

in Global.asax adds a DataSet named ds to the application cache and keys it with the string "MyData." The statement

Cache.Insert ("MyData", ds);

does the same in an ASPX file.

An item placed in the application cache this way remains there indefinitely. Other forms of the Insert method support more
advanced cache usage. The following statement places an item in the cache and specifies that the item is to be automatically
removed after 5 minutes:

Cache.Insert ("MyData", ds, null,


DateTime.Now.AddMinutes (5), Cache.NoSlidingExpiration);
As an alternative, you can assign a sliding expiration by passing a TimeSpan value in Insert's fifth parameter and
Cache.NoAbsoluteExpiration in the fourth:

Cache.Insert ("MyData", ds, null,


Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes (5));

A sliding expiration causes an item to expire when it has not been accessed (retrieved from the cache) for a specified period of
time.

A third option is to use Insert's third parameter to establish a dependency between an item added to the cache and an object in
the file system. When a file or directory that is the target of a dependency changes-when the file is modified, for example-
ASP.NET removes the item from the cache. The following example initializes a DataSet from an XML file, adds the DataSet to the
application cache, and creates a dependency between the DataSet and the XML file so that the DataSet is automatically removed
from the cache if someone modifies the XML file:

DataSet ds = new DataSet ();


ds.ReadXml (Server.MapPath ("MyFile.xml"));
Cache.Insert ( "MyData",
ds,
new CacheDependency (Server.MapPath ("MyFile.xml")));

Used this way, a CacheDependency object defines a dependency between a cached item and a file. You can also use
CacheDependency to create a dependency between two cached items. Simply pass an array of key names identifying the item or
items on which your item depends in the second parameter to CacheDependency's constructor. If you don't want to establish a
file or directory dependency also, pass null in the constructor's first parameter.

Cache.Insert also lets you assign priorities to items added to the application cache. When memory grows short, ASP.NET uses
these priorities to determine which items to remove first. If you don't specify otherwise, an item's priority is
CacheItemPriority.Normal. Other valid CacheItemPriority values, in order of lowest to highest priorities, are Low, BelowNormal,
AboveNormal, High, and NotRemovable. Priority values are specified in Insert's sixth parameter. The following statement inserts
a DataSet named ds into the application cache, sets it to expire 1 hour after the last access, and assigns it a relatively high
priority so that items with default or lower priority will be purged first in low-memory situations:

Cache.Insert ("MyData", ds, null,


Cache.NoAbsoluteExpiration, TimeSpan.FromHours (1),
CacheItemPriority.AboveNormal, null);

Specifying a CacheItemPriority value equal to NotRemovable is the only way to ensure that an item added to the cache will still
be there when you go to retrieve it. That's important, because it means code that retrieves an item from the application cache
should always verify that the reference returned isn't null-unless, of course, the item was marked NotRemovable.

But perhaps the ASP.NET application cache's most important feature is its support for cache removal callbacks. If you'd like to be
notified when an item is removed, pass a CacheItemRemovedCallback delegate to Insert identifying the method you want
ASP.NET to call when it removes the item from the cache, as demonstrated here:

DataSet ds = new DataSet ();


ds.ReadXml (Server.MapPath ("MyFile.xml"));
Cache.Insert ("MyData", ds,
new CacheDependency (Server.MapPath ("MyFile.xml")),
Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration,
CacheItemPriority.Default,
new CacheItemRemovedCallback (RefreshDataSet));
This example initializes a DataSet from an XML file, inserts the DataSet into the application cache, configures the DataSet to
expire when the XML file changes, and registers RefreshDataSet to be called if and when the DataSet expires. Presumably,
RefreshDataSet would create a brand new DataSet containing updated data and insert it into the application cache.

So how could the application cache benefit DumbQuotes.aspx? Suppose that instead of reading Quotes.txt in every request,
DumbQuotes.aspx read it once-at application startup-and stored it in the application cache. Rather than read Quotes.txt,
Page_Load could retrieve a quotation directly from the cache. Furthermore, the cached data could be linked to Quotes.txt and
automatically deleted if the file changes, and you could register a callback method that refreshes the cache when the data is
removed. That way, the application would incur just one physical file access at startup and would never access the file again
unless the contents of the file change.

That's exactly what happens in SmartQuotes.aspx, shown in Figure 3. On the outside, SmartQuotes.aspx and DumbQuotes.aspx
look identical, producing exactly the same output. On the inside, they're very different. Rather than fetch quotations from
Quotes.txt, SmartQuotes.aspx retrieves them from the application cache. Global.asax's Application_Start method (Figure 4)
reads Quotes.txt and primes the cache on application startup, while RefreshQuotes refreshes the cache if Quotes.txt changes.
RefreshQuotes is a static method. It must be if ASP.NET is to call it after the current request-the one that registers
RefreshQuotes for cache removal callbacks-has finished processing.

Figure 3: SmartQuotes.aspx

<html>
<body>
<asp:Label ID="Output" RunAt="server" />
</body>
</html>

<script language="C#" runat="server">


void Page_Load (Object sender, EventArgs e)
{
ArrayList quotes = (ArrayList) Cache["Quotes"];

if (quotes != null) {
Random rand = new Random ();
int index = rand.Next (0, quotes.Count);
Output.Text = (string) quotes[index];
}
else {
// If quotes is null, this request arrived after the
// ArrayList was removed from the cache and before a
new
// ArrayList was inserted. Tell the user the server
is
// busy; a page refresh should solve the problem.
Output.Text = "Server busy";
}
}
</script>

Figure 4: Global.asax

<%@ Import NameSpace="System.IO" %>

<script language="C#" runat="server">


static Cache _cache = null;
static string _path = null;

void Application_Start ()
{
_cache = Context.Cache;
_path = Server.MapPath ("Quotes.txt");

ArrayList quotes = ReadQuotes ();

_cache.Insert ("Quotes", quotes, new CacheDependency


(_path),
Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration,
CacheItemPriority.Default,
new CacheItemRemovedCallback (RefreshQuotes));
}

static void RefreshQuotes (String key, Object item,


CacheItemRemovedReason reason)
{
ArrayList quotes = ReadQuotes ();

_cache.Insert ("Quotes", quotes, new CacheDependency


(_path),
Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration,
CacheItemPriority.Default,
new CacheItemRemovedCallback (RefreshQuotes));
}

static ArrayList ReadQuotes ()


{
ArrayList quotes = new ArrayList ();
StreamReader reader = null;

try {
reader = new StreamReader (_path);
for (string line = reader.ReadLine (); line != null;
line = reader.ReadLine ())
quotes.Add (line);
}
finally {
if (reader != null)
reader.Close ();
}
return quotes;
}
</script>

Because high volume


CursorTypes, LockTypes, and CursorLocations
By Mike Hillyer

Introduction

One of the most common sources of trouble for the beginning VB / MySQL developer seems to revolve
around which cursor location to use. Related to the cursor location problem is the choice of cursor type and
lock type. The purpose of this article is to assist the Visual Basic developer in choosing the proper cursor
location, cursor type, and lock type to use when programming Visual Basic (or VB) applications that use
MySQL as a back-end database through ADO and Connector/ODBC (MyODBC).

This article will assume that the reader is using the MySQL RDBMS, but should apply to developers using
other database management systems. For an overview of why MySQL is a good choice for Visual Basic
developers, see the Why VB/MySQL article on this site. This sample requires the latest version of
Connector/ODBC (MyODBC), available for download here (currently 3.51.06).

On the Visual Basic side, I recommend you have service pack 5 installed for VB, which you can download
here. Additionally, the latest version of MDAC (Microsoft Data Access Components) should be installed,
and can be found here (currently 2.7 SP1). Finally, this article applies to ADO 2.7 and VB6. It is not
applicable to ADO.NET under VB.NET (Unless you reference ADODB in your project and use it for
database access).

What Are Cursors?

In ADO, when we talk about cursors, we are essentially talking about a set of rows. When you execute a
query that returns rows of data, such as SELECT * FROM mytable, the resulting data is handled using a
cursor. A cursor can be located either on the client with the adUseClient argument, or on the server with the
adUseServer argument. In addition, the are 4 types of cursor: adOpenForwardOnly, adOpenStatic,
adOpenDynamic, and adOpenKeyset.

The different types and locations will be discussed in further detail below. Your choice of cursor type and
cursor location will affect what you are able to do with the data you retrieve, and how changes made to the
data by other users are reflected in your copy of the data.

Cursor Location

The ADODB.Connection object (the ADO object used to broker all data exchanges between the VB
application and the MySQL server) has a property known as CursorLocation which is used to set/retrieve
the cursor location that will be used by any recordset objects that access their data through the connection
object.

The CursorLocation property can only be set while the connection is closed, and the property will be
inherited by any recordset objects that access their data through the given connection object. Recordset
objects can also explicitly set a cursorlocation different than the connection objects cursorlocation as long as
it is set before the recordset is open. The two options available for this property are adUseClient and
adUseServer, with adUseServer being the default property.

adUseServer

When using the adUseServer server-side cursorlocation, responsibility for handling the data generated by a
query lies with the database server. MySQL itself does not support server-side cursors, so the data handling
is actually done by the Connector / ODBC driver. The benefit of server-side cursors is that we gain access to
the dynamic cursor type. This allows us to see any changes to the data that are made by other users in the
data our application is accessing.

For example: let's say we are selling tickets to a concert with our application, we need to know that a given
seat is available for sale in real-time to ensure we do not double-book the seat. With a server-side cursor, we
can be sure that the data we are manipulating is the most current possible. In addition, we have the ability to
lock the data we are working on as we edit it, to make sure our changes are going to be posted to the
database successfully.

With a server-side cursor (adUseServer), we have access to the adOpenDynamic and adOpenForwardOnly
cursor types, and all four of the recordset lock types, which will be discussed below.

It should be noted that using a server-side cursor, and the adOpenDynamic cursor in particular, will result in
a significant performance loss, and should be avoided if at all possible. In addition, certain functionality,
such as the RecordCount property of a Recordset and the GetChunk and Appendchunk function for handling
BLOB data, will fail or return abnormal results when used with a server-side cursor.

adUseClient

Client-side cursors, specified with the adUseClient keyword, are handled internally by ADO. These cursors
offer more functionality than their server-side counterparts, and also result in less load being placed on the
server. Most advanced ADO functionality is designed for use with client-side cursors, and I personally use
client-side cursors for all my applications (with one exception).

When using a client-side adUseClient cursor, only the adOpenStatic cursor is available, and we cannot use
the adLockPessimistic lock type (see below).

Client-side cursors also help decrease load on our MySQL server, since with a static cursor data is sent to
the client and then the server has no further communications with the client. This allows your server to scale
a lot better than with server-side cursors.

Cursor Types

In addition to the two cursor locations, there are four cursor types, three of which are supported under
Connector/ODBC:

• adOpenStatic (Client-Side)
• adOpenForwardOnly (Server-Side)
• adOpenDynamic (Server-Side)

The different cursor types support different functionality and features, and I will now discuss each one in
detail. The fourth cursor type, adOpenKeySet, is not currently supported by MySQL / MyODBC.

adOpenStatic

The static cursor is the only cursor type that is currently available when using adUseClient as your cursor
location. With a static cursor, the server will send the result set to the client, after which there will be no
further communication from the server to the client. The client may communicate with the server to send
changes back to the server. This makes the static cursor more resource-intensive for the client and less
resource-intensive for the server, as the result set is stored in the client's memory instead of the server's.

If a different client makes changes to the underlying data after the query results are sent, the original client
will receive no notification of the change. A static cursor is bi-directional, meaning that your application can
move forwards and backwards through the recordset. The following methods are available to a recordset
using a static cursor and the adLockOptimistic lock type (more on lock types later):

• AddNew • MoveNext
• Delete • MoveLast
• Find • Resync
• MoveFirst • Update

• MovePrevious • UpdateBatch

The static cursor will also show an accurate value for the RecordCount property of your recordset, and
supports the getchunk and appendchunk methods for dealing with BLOB data. If you are having trouble
with either of these problems, explicitly setting your connection's cursorlocation to adUseClient should
solve them.

One handy feature of the static cursor is the ability to fetch data asynchronously. When data is fetched
asynchronously., a separate thread is started to handle row retrieval, and your VB application can begin
processing returned rows immediately. An in depth article on asynchronous data fetching is pending, but to
activate this feature, simple use the adFetchAsync option during your recordset.open method call.

If you specify any cursor type other than adOpenStatic when opening a recordset with an adUseClient
cursor location, it will be automatically converted to a static cursor.

adOpenForwardOnly

The adForwardOnly cursor type is the fastest performing cursortype, and also the most limited. The
forward-only cursor does not support the RecordCount property, and does not support the MovePrevious
methods of the recordset object.

The most efficient way to access data for display to the screen out output to a file is to use a
adOpenForwardOnly cursor with a adLockReadOnly lock type when opening a recordset. This combination
is often referred to as a Firehose Cursor. A firehose cursor bypasses a lot of handling code between the client
and server and allows for very fast data access when moving sequentially through the resulting rows.

The following recordset methods are supported when using a forward-only cursor with an optimistic lock:

• AddNew
• Delete
• Find
• Update
• UpdateBatch

In addition, the forward-only cursor type supports non-caching queries. While an asynchronous query
allows data to be worked on immediately, it offers no memory benefits when accessing large resultsets, as
all rows eventually wind up in memory, taxing system resources when accessing a large number of rows, or
a medium number of rows when BLOB data is involved.

With MySQL and Connector/ODBC, we can specify option 1048576 in our connection string or check off
the option "Don't Cache Results" in the ODBC manager in order to specify to the ODBC driver that it
should only retrieve one row at a time from the server. With this option set, memory usage on the client is
limited as only one row at a time is stored in memory. With every call to the recordset's MoveNext method,
the previous row is discarded and the next row is queried from the server.

adOpenDynamic

While the forward-only cursor is the most efficient of the cursor types, the dynamic cursor, specified but
adOpenDynamic, is the least efficient. Because of it's inefficiency, dynamic cursor support must be manually
activated by using option 32 in your connection string, or by checking "Enable Dynamic Cursor" in the
ODBC manager. Without this option enabled, any cursortype other than forward-only with be automatically
converted to a static cursor, with it enabled, all cursor types other than forward-only will be converted to
dynamic.

Why is a dynamic cursor so slow? As there is no native support for dynamic, server-side cursors in MySQL,
every call to a row-moving method(MoveNext, MovePrevious, etc.) results in the Connector/ODBC driver
converting your method call to a SQL query, posting the query, and returning the resulting row. This also
means that for a dynamic cursor to work properly, your underlying table needs a primary key column to
determine the next/previous row with. As such, dynamic cursors are not recommended unless absolutely
necessary.

The dynamic cursor supports the following recordset methods when opened with a optimistic lock:

• AddNew
• Delete
• Find
• MoveFirst
• MovePrevious
• Update
• UpdateBatch

While Dynamic cursors can be beneficial for multi-user applications, it is best to avoid them when possible,
and work around multi-user issues when possible by calling the resync and requery methods when
possible, and executing UPDATE queries that increment and decrement count values instead of using the
recordset to do updates (i.e. rather than getting an inventory count in a recordset, incrementing it in VB, and
doing a recordset.update, use the connection object to execute a query similar to UPDATE inventory SET
count = count - 1 WHERE itemcode = 5)

Lock Types

While cursor locations and cursor types specify how our data is going to be handled, the lock type property
specifies how we are going to lock the underlying data to protect any changes we make and ensure they are
processed. There are four different lock types, and the locktype is set in the recordset object as part of the
open method (it can also be set using the LockType property of the recordset object). The four locktypes are:
adLockReadOnly (default), adLockOptimistic, adLockPessimistic, and adLockBatchOptimistic. All
four locktypes are available to a server-side cursor, the adLockPessimistic locktype is unavailable to a
client-side cursor.

adLockReadOnly

The default lock type is adLockReadOnly. A read-only lock is the most efficient when accessing data, as
there is no checking for data changes and therefore no extra traffic between the client and server while
loading records.

As the name implies, using a read-only lock will block you from making any changes to the table. If you
find yourself with an error message like "Current recordset does not support updating", then you need to
change away from the default adLockReadOnly lock type.

adLockOptimistic

An optimistic lock is used for modifications that either happen in a low-concurrency environment, or where
having multiple users making changes to the same records is not a major concern. With an optimistic lock,
the table or row locks will occur when the update method of the recordset object is called. This will ensure
the change is successfully made, but will not prevent other users from changing the underlying data while
you are modifying it in VB.

The adLockOptimistic lock type is typically your best choice when deciding on a table lock for a non-
read-only situation. In almost all my applications, the only two lock types I use are adLockReadOnly and
adLockOptimistic.

adLockBatchOptimistic

When using the adBatchOptimistic lock type, your changes will be cached locally until the recordset's
UpdateBatch method is called. When UpdateBatch is called, all changes will be pushed to the server in a
group. This can make the bulk insert of a large number of records more efficient. (Note: Calling ALTER
TABLE mytable DISABLE KEYS before a large batch of inserts, followed by ALTER TABLE mytable
ENABLE KEYS after the batch completes, can dramatically speed up the batch insert process, as MySQL can
rebuild an index faster than it can add one entry at a time).

adLockPessimistic

In a situation of high concurrency, with multiple users modifying the same data, you may need a pessimistic
lock type. With asLockPessimistic, the underlying rows (or table) will be locked as soon as you begin
making changes to the current record, and will not be unlocked until the Update method is called.

While this will ensure that you do not have overlapping changed with other users, it could cause
performance issues, especially with a MyISAM table, with features table-level locking only. Make sure that
the changes are immediately followed by the recordset's update method, and that there is no break for user
input between a change and the update in order to ensure no long breaks (and potentially canceled locks by
the database) in the operation of the database.

While adLockPessimistic has it's place, the same advice I gave regarding dynamic cursors applies: avoid
it when possible, as it is very resource intensive and involves a lot more work both on the client and server
side.

Conclusion

While there are a large number of potential CursorType/CursorLocation combinations, the ones that are
currently available to the MySQL/VB developer are: adUseClient/adOpenStatic,
adUseServer/adOpenForwardOnly, and adUseServer/adOpenDynamic.

For most uses, adUseClient/adOpenStatic is your best choice, with adLockReadOnly as your lock type for
any read-only operations (export to a file, load rows to a listview, combobox, etc.) and adLockOptimistic as
your lock type for any read/write operations.

adOpenDynamic and adLockPessimistic are best suited for high-concurrency situations where you need to
ensure that multiple users do not corrupt each other's data. While these offer the most current views of data
and the most restrictive locking, they do so at a severe price as far as performance is concerned.

The combination of adUseServer/adOpenForwardOnly/adLockReadonly offers the best performance overall


for operations like populating controls and exporting to files. When combined with option 1048576 (Don't
cache query results), adOpenForwardOnly also provides excellent memory efficiency, as only one record at
a time is loaded into memory. Be awate that if a locktype other than adLockReadOnly is used, memory
usage will slowly build as rows are loaded into memory and kept in case they are needed for an update or
cancel statement. The one row at a time operation is only present with an
adLockReadOnly/adOpenForwardOnly combination.
SESSSION
Technologies: ASP.NET 1.0,Visual
ASP.NET Session State C# .NET
By Ganesh Nataraj September 21, 2005 Total downloads :
Total page views : 33910
Session state is nothing more than memory in the shape of a Rating 4/5
dictionary or hash table, e.g. key-value pairs, which can be set and :
read for the duration of a user's session. This article has been 4 times
rated :

Print Post a comment Rate Share


Add to Technorati

Digg This

Add to del.icio.us

Kick It

Email to a friend Bookmark Similar Articles Author's other articles


creates two tables and several stored procedures. ASP.NET uses both the tables and the procedures to
store data in SQL Server. I would recommend reading through state.sql to learn more about what it is
doing.

The state.sql file can be found in


[system drive]\winnt\Microsoft.NET\Framework\[version]\

Applying the state.sql script

To apply the state.sql script, use the command line tool SQL Server provides: osql.exe. Using an sa
equivalent SQL user, the syntax below is used:

osql -S [server name] -U [user] -P [password] <state.sql

Note: A lightweight version of SQL Server is installed when the .NET SDK is installed.

Here's what you should see:

Figure 2. Using the SQL Server command line tool to apply state.sql script

After running osql, start and stop SQL Server; part of what state.sql added were some start-up stored
procedures that need to be run. Next, modify the configuration settings to set the mode to sqlserver
and modify the sqlconnectionstring to identify the appropriate SQL Server serving the ASPState
database. For example:

<configuration>
<sessionstate
mode="sqlserver"
cookieless="false"
timeout="20"
sqlconnectionstring="data source=MySqlServer;
user id=ASPState;
password=1Gr8State"
server="127.0.0.1"
port="42424" />
</configuration>
Exporting the data from database to XML using C#
by nitin singla on Feb 06, 2009

Memory out of exception error while Exporting huge data from database to XML using C#

Comments: 1 Views: 2113


application there is a utility for exporting the data from database to XML file and then import the
same in another system.

The system is designed using .NET Framework 3.5.

The utility is now failing when trying to export the data around 100000 rows in table. It is giving
out of memory exception.

The code snippet is as follows

private void ExportTableAsXml(ref XmlNode rootElement,Hashtable


externalParameters)
{

DataTable result = null;


if (commandTypeField == CommandType.StoredProcedure)
{
}
else if (commandTypeField == CommandType.Text)
{

DataSet resultDataSet =
xdo.ExecDataSetSQL(sqlStatementField);
if (resultDataSet != null &&
resultDataSet.Tables.Count > 0)
result = resultDataSet.Tables[0];
}

XmlNode containerElement = rootElement;


if (result != null && result.Rows.Count != 0)
{

if (containerNameField != string.Empty)
containerElement =
rootElement.OwnerDocument.CreateElement(containerNameField);

if (!ResultIsXml)
ConvertTableToXml(ref containerElement,
result);
else
{
StringBuilder xmlBuilder = new
StringBuilder();
if (result.Columns.Count == 1)
{
foreach(DataRow row in result.Rows)
What are web services?

• Web service is the way to publish application's function on web that can be accessible
to the rest of the world.
• Web services are the components that can be used by other applications
• ASP.NET offers easy way to develop web services, just precede the functions with a
special WebMethod ()> attribute in order them to work as Web Service.
• Web services are discovered using UDDI directory services.
• Web services are built on XML standard and use SOAP protocol that allows them to
communicate across different platforms and programming languages.
• Web services platform elements are
SOAP (Simple Object Access Protocol)
UDDI (Universal Description, Discovery and Integration)
WSDL (Web Services Description Language)
• The web services are built on internet standards that are not platform or language
specific.
• The .Net framework provides in-built classes to build and consume web services.

This is the syntax for creating a cookies.


HttpCookie SiteCookies = new HttpCookie("UserInfo");
SiteCookies["UserName"] = "Pradeep";
SiteCookies["sitename"] = "dotnetRed";
SiteCookies["Expire"] = "5 Days";
SiteCookies= DateTime.Now.AddDays(5);
Response.Cookies.Add(SiteCookies);
Now syntax to remove this cookie:-
HttpCookie SiteCookies= new HttpCookie("UserInfo");
siteCookies= DateTime.Now.A
ddDays(-1);
Response.Cookies.AddSiteCookies

| | | | | | | | | | | | | | | | | |

Power Search
If your SQL Server is exposed to the Internet, then hackers are probing it. This article shows how to
SQL Server database that's being used with a Web application
[Read This Article] [Top]

Enrico Di Cesare provides a solution for hiding and securing querystring values that pass
through a url.
[Read This Article] [Top]

Feel intimidated by .NET? This article by Rob Chartier is designed to ease any level VBScripter (AS
15 Seconds
.NET by clarifying some OOP concepts.
Weekly Newsletter
[Read This Article] [Top]
• Complete Coverage
• Site Updates
• Upcoming Features
A few members of the 15 Seconds discussion list talk about the proper way to use methods in order
ADO object errors.
[Read This Article] [Top]

Rob Chartier creates a simple portable and reusable address book in .NET to demonstrate the pow
application architecture. Complete source code included!
[Read This Article] [Top]

Learn about N-tier application architecture and realize that developing with multiple layers produces
and reusable application for distribution to any number of client interfaces.
[Read This Article] [Top]

Learn about N-tier application architecture and realize that developing with multiple layers produces
and reusable application for distribution to any number of client interfaces.
[Read This Article] [Top]

Ed Myers' article shows several ways to use a SQL calculated field and the ORDER BY clause to a
recordset in random order. A simple tool is provided for verifying that the results are uniformly rando
technique for bubbling records with certain attributes to the top of an otherwise randomized list is al
[Read This Article] [Top]

Want to receive email when the next article is published? Just Click Here to sign up.
News
Articles
Archiv
e
Writer
s
Code Sampl
es
Components

Tools
FAQ
Feedback
Books
Links
DL Archives
Messageboa
rd
List Servers
Mailing List
WebHosts
Consultants
Tech Jobs
Home
Site Map
Press
Legal
Privacy
Policy

IT
Developer
Internet News
Small Business
Personal Technology

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers
Support the Active Server Industry

WebMediaBrands Corporate Info


Copyright 2009 WebMediaBrands Inc. All Rights Reserved. Copyright 2009 WebMediaBrands Inc. All Rights Reserved.

Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.


Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs

Whitepapers and eBooks

The IBM Global CIO Study 2009 Microsoft Partner Portal: What Azure Means for Microsoft Partners
Article: Avaya AE Services Provide Rapid Telephony Integration with Facebook Internet.com eBook: Web Development Frameworks for Java
Intel Brief: Proactive PC Support Improves Service and Lowers TCO Article: New BlackBerry Enterprise Server Eases Administration for IT Pros
Microsoft Article: Make Designer/Developer Collaboration a Reality Microsoft Article: Stress Free and Efficient Designer/Developer Collaboration
Whitepapers: Manage Your Business Infrastracture with IBM Whitepapers: APC IT InfraStruXure Resource Center
Whitepaper: Maximize Your Storage Investment with HP Internet.com eBook: Developing a Content Management System Strategy
Internet.com eBook: Becoming a Better Project Manager MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts

Video: Enter the 2009 AT&T devCentral Fast Pitch Contest Ipswitch Video: A Closer Look--WS_FTP Server
SAP BusinessObjects Webcast: Unlock the Power of Reporting with Crystal Reports MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits

Iron Speed Designer Application Generator MORE DOWNLOADS, EKITS, AND FREE TRIALS

Tutorials and Demos

Demo: Microsoft Virtualization - Data Center to Desktop MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES
Internet.com Hot List: Get the Inside Scoop on the Hottest IT and Developer Products

What's the deal with Databinder.Eval and Container.DataItem?


Reposting here for the benefit of asp.net developers and Google

The databinding expression <%# some expression %> is evaluated in the language of the page (VB,
C#, etc.) This can have a big impact on the current syntax, so be very careful when you are looking at
docs for the language you are using.

Container.DataItem is a runtime alias for the DataItem for this specific item in the bound list. For a
grid which displays 10 rows of data, this is one row from the datasource. The actual type of DataItem
is determined by the type of the datasource. For example, if the datasource is a Dataview, the type of
DataItem is DataRowView. If the type of the datasource is an array of strings, the type of DataItem is
String. If the datasource is a collection of strongly-typed objects (for example "Employees" objects),
the type of DataItem is Employees.

Each of these cases requires a slightly different databinding expression, with further differences
between VB and C#. In every case, you want the databinding expression to produce a string that can
be displayed in the page.

Here are some examples:

Array of Strings:
VB/C# <%# Container.DataItem %>

Field from DataView:


VB <%# Container.DataItem("EmployeeName") %>
C# <%# ((DataRowView)Container.DataItem)["EmployeeName"] %>

Property from a collection of objects:


VB <%# Container.DataItem.CustomerName %>
C# <%# ((Customer)Container.DataItem).CustomerName %>

Non-String property from a collection of objects:


VB <%# CStr(Container.DataItem.CustomerID) %>
C# <%# ((Customer)Container.DataItem).CustomerID.ToString() %>

As you can see the syntax is tricky, especially for C#, which requires explicit casting. So we've
provided a DataBinder.Eval() helper method that figures out the syntax for you and formats the
result as a string. It's really convenient, with a couple of caveats: it's late bound (uses reflection at
runtime to figure out the data types), and it only supports basic data types in the fields: string, int,
datetime, etc.

You can use Eval instead of DataBinder.Eval in ASP.net 2.0

DataBinder.Eval takes 2 or 3 arguments. The first arg is the data object to bind to. In the case of
DataGrid, DataList and Repeater, Container.DataItem is the single row. The second arg the string
name of the field from the data object you which to display. DataBinder.Eval uses these two pieces
of information to work out the rest of the expression syntax.

An optional third argument is a .NET formatting string. DataBinder.Eval will handle a single
replacement for {0} only. So the example below:

<a href='<%# "default.aspx?CategoryId=" + Cstr(Databinder.Eval(Container.DataItem,


"ID"))%>'>
could be simplified to:

<a href='<%# Databinder.Eval(Container.DataItem,"ID","default.aspx?CategoryId={0}" )


%>'>

Wrapping DataBinder.Eval in CStr() is unnecessary as the compiler will wrap the statement with a
Convert.ToString like this:

control1.SetDataBoundString(0, Convert.ToString(DataBinder.Eval(item1.DataItem,
"ID")));

Best of all, the Databinder.Eval syntax is the same for VB and C#.

Upgrade your Internet Experience

Don't show me this again

United States Change | All Microsoft Sites

Help and Support


Search Microsoft Support

Search Microsoft.com

Search the web

• Help and Support Home

• Select a Product

• Advanced Search

• Buy products
Article ID: 306154 - Last Review: March 29, 2007 - Revision: 4.6
How To Display Hierarchical Data by Using Nested Get Help Now
Repeater Controls and Visual C# .NET
View products that this article applies to. Contact a support
This article was previously published under Q306154 professional by E-
mail, Online, or
On This Page Phone
Article Translations
• SUMMARY
o Bind to the Parent Table
o Bind to the Child Table
o Complete Code List
 Nestedrepeater.aspx
 Nestedrepeater.aspx.cs
• REFERENCES
Search related topics
Expand all | Collapse all • ASP.NET server controls
• Inherits
SUMMARY • Web controls
• How do I delete from the browser

This article describes how to use nested Repeater controls to display hierarchical
• View HTML code
data. You can apply this concept to other list-bound controls.

Back to the top

Bind to the Parent Table Page Tools

1. Start Microsoft Visual Studio .NET. • Print this page

2. On the File menu, point to New, and then click Project.


• E-mail this page
3. Click Visual C# Projects under Project Types, and then click ASP.NET

Web Application under Templates.

4. In the Location box, delete the WebApplication#, and then type

NestedRepeater. If you use the local server, leave the server name as

http://localhost. The following path appears in the Location box:

http://localhost/ NestedRepeater

Click OK.

5. In Solution Explorer, right-click the NestedRepeater project name node,

point to Add, and then click Add Web Form.


6. To name the Web Form, type NestedRepeater, and click Open.

7. The new Web Form is created. It opens in Design View in the Integrated

Development Environment (IDE) of Microsoft Visual Studio .NET. From the

Toolbox, select the Repeater control, and then drag it to the Web Form page.

8. Change the ID property of this Repeater control to parentRepeater.

9. Switch to the HTML view for this Web Form. To do so, click the HTML tab in

the lower-left corner of the Designer. The Repeater control generates the

following HTML code:

10. <asp:Repeater id="parentRepeater" runat="server"></asp:Repeater>

11. Add the following code in the Repeater tags:


12. <itemtemplate>

13. <b><%# DataBinder.Eval(Container.DataItem, "au_id") %></b><br>

14. </itemtemplate>

After you do that, the HTML code for the Repeater is as follows:

<asp:Repeater id="parentRepeater" runat="server">

<itemtemplate>

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

%></b><br>

</itemtemplate>

</asp:Repeater>

15. In Solution Explorer, right-click NestedRepeater.aspx, and then click View


Code to switch to the NestedRepeater.aspx.cs code-behind file.

16. Add the following namespace declaration to the top of the file:

17. using System.Data;

18. using System.Data.SqlClient;

19. Add the following code to the Page_Load event to create a connection to the
Pubs database, and then to bind the Authors table to the Repeater control:

20. public void Page_Load(object sender, EventArgs e)

21. {

22. //Create the connection and DataAdapter for the Authors table.

23. SqlConnection cnn = new

SqlConnection("server=(local);database=pubs; Integrated

Security=SSPI");

24. SqlDataAdapter cmd1 = new SqlDataAdapter("select * from

authors",cnn);

25.

26. //Create and fill the DataSet.

27. DataSet ds = new DataSet();

28. cmd1.Fill(ds,"authors");

29. //Insert code in step 4 of the next section here.

30. //Bind the Authors table to the parent Repeater control, and call

DataBind.

31. parentRepeater.DataSource = ds.Tables["authors"];

32. Page.DataBind();

33.

34. //Close the connection.

35. cnn.Close();

36. }

NOTE: You may have to modify the database connection string as

appropriate for your environment.

37. Save all of the files.

38. In Solution Explorer, right-click the NestedRepeater.aspx, and then click


Set As Start Page.

39. On the Build menu click Build Solution to compile the project.
40. View the .aspx page in the browser, and then verify that the page works thus

far.

The output should appear as follows:


o 172-32-1176

o 213-46-8915

o 238-95-7766

o 267-41-2394

o ...

Back to the top

Bind to the Child Table

1. In the HTML view of the NestedRepeater.aspx page, locate the following

line of code:

2. <b><%# DataBinder.Eval(Container.DataItem, "au_id") %></b><br>

Add the following code after this code:

<asp:repeater id="childRepeater" runat="server">

<itemtemplate>

<%# DataBinder.Eval(Container.DataItem,

"[\"title_id\"]")%><br>

</itemtemplate>

</asp:repeater>

This new code adds a second Repeater control to the ItemTemplate

property of the parent Repeater control.

3. Set the DataSource property for the child Repeater control as follows:

4. <asp:repeater ... datasource='<%# ((DataRowView)Container.DataItem)

5. .Row.GetChildRows("myrelation") %>' >

After you set the DataSource property for the child Repeater control, the

HTML code for the two Repeater controls (parent and child) appears as
follows:

<asp:Repeater id="parentRepeater" runat="server">

<itemtemplate>

<b>

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

</b>

<br>

<asp:repeater id="childRepeater" runat="server"

datasource='<%# ((DataRowView)Container.DataItem)

.Row.GetChildRows("myrelation") %>' >

<itemtemplate>

<%#

DataBinder.Eval(Container.DataItem, "[\"title_id\"]")%><br>

</itemtemplate>

</asp:Repeater>

</itemtemplate>

</asp:Repeater>

6. Add the following page directive to the top of the page:

7. <%@ Import Namespace="System.Data" %>

8. In the code-behind page, replace the following line in the Page_Load event

9. //Insert code in step 4 of the next section here.

with the following code:

//Create a second DataAdapter for the Titles table.

SqlDataAdapter cmd2 = new SqlDataAdapter("select * from

titleauthor",cnn);

cmd2.Fill(ds,"titles");
//Create the relation between the Authors and Titles tables.

ds.Relations.Add("myrelation",

ds.Tables["authors"].Columns["au_id"],

ds.Tables["titles"].Columns["au_id"]);

This adds the Titles table to the DataSet, and then adds the relationships

between the Authors and Titles tables.

10. Save and compile the application.

11. View the page in the browser, and then verify that the page works so far. The

output should appear as follows:

172-32-1176

PS3333

213-46-8915

BU1032

BU2075

238-95-7766

PC1035

267-41-2394

BU1111

TC7777

...

Back to the top

Complete Code List

Nestedrepeater.aspx

<%@ Page language="c#" Codebehind="NestedRepeater.aspx.cs"

AutoEventWireup="false" Inherits="NestedRepeater.NestedRepeater" %>

<%@ Import Namespace="System.Data" %>


<html>

<body>

<form runat=server>

<!-- start parent repeater -->

<asp:repeater id="parentRepeater" runat="server">

<itemtemplate>

<b><%# DataBinder.Eval(Container.DataItem,"au_id") %></b><br>

<!-- start child repeater -->

<asp:repeater id="childRepeater" datasource='<%#

((DataRowView)Container.DataItem)

.Row.GetChildRows("myrelation") %>' runat="server">

<itemtemplate>

<%# DataBinder.Eval(Container.DataItem, "[\"title_id\"]")%><br>

</itemtemplate>

</asp:repeater>

<!-- end child repeater -->

</itemtemplate>

</asp:repeater>

<!-- end parent repeater -->

</form>

</body>

</html>

Nestedrepeater.aspx.cs

using System;

using System.Data;

using System.Data.SqlClient;

using System.Web;
using System.Web.SessionState;

using System.Web.UI;

using System.Web.UI.WebControls;

namespace NestedRepeater

public class NestedRepeater : System.Web.UI.Page

protected System.Web.UI.WebControls.Repeater parentRepeater;

public NestedRepeater()

Page.Init += new System.EventHandler(Page_Init);

public void Page_Load(object sender, EventArgs e)

//Create the connection and DataAdapter for the Authors table.

SqlConnection cnn = new

SqlConnection("server=(local);database=pubs; Integrated Security=SSPI ;");

SqlDataAdapter cmd1 = new SqlDataAdapter("select * from

authors",cnn);

//Create and fill the DataSet.

DataSet ds = new DataSet();

cmd1.Fill(ds,"authors");

//Create a second DataAdapter for the Titles table.

SqlDataAdapter cmd2 = new SqlDataAdapter("select * from

titleauthor",cnn);

cmd2.Fill(ds,"titles");

//Create the relation bewtween the Authors and Titles tables.

ds.Relations.Add("myrelation",

ds.Tables["authors"].Columns["au_id"],

ds.Tables["titles"].Columns["au_id"]);
//Bind the Authors table to the parent Repeater control, and call

DataBind.

parentRepeater.DataSource = ds.Tables["authors"];

Page.DataBind();

//Close the connection.

cnn.Close();

private void Page_Init(object sender, EventArgs e)

InitializeComponent();

private void InitializeComponent()

this.Load += new System.EventHandler(this.Page_Load);

Back to the top

REFERENCES

For more information, refer to the following topics in the Microsoft .NET Framework

Software Development Kit (SDK):

Adding a Relationship between Tables

http://msdn.microsoft.com/library/default.asp?url=/library/en-

us/cpguide/html/cpconaddingrelationshipbetweentwotables.asp

Navigating a Relationship between Tables

http://msdn.microsoft.com/library/default.asp?url=/library/en-

us/cpguide/html/cpconnavigatingrelationshipbetweentwotables.asp

Repeater Web Server Control

http://msdn.microsoft.com/library/default.asp?url=/library/en-

us/cpgenref/html/cpconrepeaterwebservercontrol.asp
Back to the top

APPLIES TO

• Microsoft ASP.NET 1.0

• Microsoft ASP.NET 1.1

• Microsoft Visual C# .NET 2002 Standard Edition

• Microsoft Visual C# .NET 2003 Standard Edition

Back to the top


Keywords: kbdatabinding kbhowtomaster kbservercontrols KB306154 Back to the
top

Provide feedback on this information

Did this information solve your problem?

Yes
No
I don't
know

Was this information relevant?

Yes
No

What can we do to improve this information?

To protect your privacy, do not include contact information in your feedback.

Get Help
Now

Contact a
support
professional
by E-mail,
Online, or
Phone

Help and Support


Feedback | Services Agreement
Contact Us | Terms of Use | Trademarks | Privacy Statement ©2009
Microsoft

Using Forms Authentication in ASP.NET:--


There are times when you want to validate users hitting a web site on your own
rather than using Windows or Passport authentication. That requires forms based
security. This article shows you how to implement Forms Based Authentication.

Hitting any web page on the site will automatically redirect to the login form. When
the login form has authenticated the user, it will automatically redirect back to the
originally requested page. Failure to log in will prohibit the user from hitting the
originally requested page.

Each example below is shown in both Visual Basic .NET and C#. Use the appropriate
code for the language you are using.

In the web.config file in the root of the web site, insert this XML:

<authentication mode="Forms">
<forms name="login" loginUrl="login.aspx" />
</authentication>

<authorization>
<allow roles="bigboss" />
<allow roles="wimpyuser" />
<allow users="admin" />
<deny users="*" />
</authorization>

Change the rules to give permissions to the proper users and roles. You may create a
different web.config and its authorization section in each subdirectory with different
rules.

In the global.asax file, insert this code:


[vb.net]
Imports System.Security.Principal
Imports System.Web.Security

Sub Application_AuthenticateRequest(ByVal sender As Object, ByVal e As EventArgs)


' Fires upon attempting to authenticate the use
If Not (HttpContext.Current.User Is Nothing) Then
If HttpContext.Current.User.Identity.IsAuthenticated Then
If TypeOf HttpContext.Current.User.Identity Is FormsIdentity Then
Dim fi As FormsIdentity = CType(HttpContext.Current.User.Identity,
FormsIdentity)
Dim fat As FormsAuthenticationTicket = fi.Ticket

Dim astrRoles As String() = fat.UserData.Split("|"c)


HttpContext.Current.User = New GenericPrincipal(fi, astrRoles)
End If
End If
End If
End Sub

[c#]
using System.Security.Principal;
using System.Web.Security;

protected void Application_AuthenticateRequest(Object sender, EventArgs e)


{
//Fires upon attempting to authenticate the use
if (!(HttpContext.Current.User == null))
{
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
if (HttpContext.Current.User.Identity.GetType() ==
typeof(FormsIdentity))
{
FormsIdentity fi = (FormsIdentity)
HttpContext.Current.User.Identity;
FormsAuthenticationTicket fat = fi.Ticket;

String[] astrRoles = fat.UserData.Split('|');


HttpContext.Current.User = new GenericPrincipal(fi,
astrRoles);
}
}
}
}

Create a Web Form named login.aspx, set the style to Flow Layout, and put this onto
the page:

<table height="66%" width="100%">


<tr>
<td align="middle">
<table id="loginbox" width="300" class="itemstyle">
<tr>
<td id="login" align="middle" colspan="3">Login</td>
</tr>
<tr>
<td>Username:</td>
<td><asp:textbox id="txtUsername" tabindex="4" runat="server"
columns="12"></asp:textbox></td>
<td valign="center" align="middle" rowspan="2">
<asp:button id="btnLogin" runat="server" text="Login"
cssclass="button"></asp:button></td>
<tr>
<td>Password:</td>
<td><asp:textbox id="txtPassword" runat="server" columns="12"
textmode="Password"></asp:textbox></td>
</tr>
<tr>
<td>&nbsp;</td>
<td colspan="2"><asp:label id="lblError" runat="server"
forecolor="Red" visible="False">Not a valid username or
password.</asp:label>
</td>
</tr>
</table>
</td>
</tr>
</table>

In the CodeBehind for login.aspx, put this code:

[vb.net]
Imports System.Web.Security

Private Sub btnLogin_Click(ByVal sender As Object, ByVal e As System.EventArgs) _


Handles btnLogin.Click
If ValidateUser(txtUsername.Text, txtPassword.Text) Then
FormsAuthentication.Initialize()
Dim strRole As String = AssignRoles(txtUsername.Text)

'The AddMinutes determines how long the user will be logged in after leaving
'the site if he doesn't log off.
Dim fat As FormsAuthenticationTicket = New FormsAuthenticationTicket(1, _
txtUsername.Text, DateTime.Now, _
DateTime.Now.AddMinutes(30), False, strRole, _
FormsAuthentication.FormsCookiePath)
Response.Cookies.Add(New HttpCookie(FormsAuthentication.FormsCookieName, _
FormsAuthentication.Encrypt(fat)))
Response.Redirect(FormsAuthentication.GetRedirectUrl(txtUsername.Text, False))
Else
lblError.Visible = True
End If
End Sub

Private Function ValidateUser(ByVal strUsername As String, ByVal strPassword As


String) _
As Boolean
'Return true if the username and password is valid, false if it isn't
Return CBool(strUsername = "admin" AndAlso strPassword = "password")
End Function
Private Function AssignRoles(ByVal strUsername As String) As String
'Return a | separated list of roles this user is a member of
If txtUsername.Text = "admin" Then
Return "bigboss|wimpyuser"
Else
Return String.Empty
End If
End Function

[c#]
using System.Web.Security;

private void btnLogin_Click(object sender, System.EventArgs e)


{
if (ValidateUser(txtUsername.Text, txtPassword.Text))
{
FormsAuthentication.Initialize();
String strRole = AssignRoles(txtUsername.Text);

//The AddMinutes determines how long the user will be logged in after
leaving
//the site if he doesn't log off.
FormsAuthenticationTicket fat = new FormsAuthenticationTicket(1,
txtUsername.Text, DateTime.Now,
DateTime.Now.AddMinutes(30), false, strRole,
FormsAuthentication.FormsCookiePath);
Response.Cookies.Add(new
HttpCookie(FormsAuthentication.FormsCookieName,
FormsAuthentication.Encrypt(fat)));
Response.Redirect(FormsAuthentication.GetRedirectUrl(txtUsername.Text,
false));
}
else
lblError.Visible = true;
}

private Boolean ValidateUser(String strUsername, String strPassword)


{
//Return true if the username and password is valid, false if it isn't
return ((strUsername == "admin") && (strPassword == "password"));
}

private String AssignRoles(String strUsername)


{
//Return a | separated list of roles this user is a member of
if (txtUsername.Text == "admin")
return "bigboss|wimpyuser";
else
return String.Empty;
}

Change the ValidateUser and AssignRoles to do lookups into a database or other data
store instead of the hardcoded validation and role assignment shown.
On each page on the site, you will need a way to log out. Simply put a hyperlink to
the logout page:

<asp:HyperLink id="hlLogout" runat="server"


NavigateUrl="logout.aspx">Logout</asp:HyperLink>

The logout.aspx page should have this on it:

<table width="100%">
<tr>
<td align="middle">
You have been logged out.
<asp:hyperlink id="hlLogin" runat="server"
navigateurl="default.aspx">Log back in.</asp:hyperlink>
</td>
</tr>
</table>

The CodeBehind for the logout page should include this:

[vb.net]
Imports System.Web.Security

Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _


Handles MyBase.Load
Session.Abandon()
FormsAuthentication.SignOut()
End Sub

[c#]
using System.Web.Security;

private void Page_Load(object sender, System.EventArgs e)


{
// Put user code to initialize the page here
Session.Abandon();
FormsAuthentication.SignOut();
}

You can put things that are only allowable to certain roles on your web page by using
code like this:

[vb.net]
hlAdmin.Visible = Page.User.IsInRole("bigboss")

[c#]
hlAdmin.Visible = Page.User.IsInRole("bigboss");
Send mail
Dim mymail As New MailMessage
mymail.From = mailFrom
mymail.To = mailTo
mymail.Body = body
mymail.BodyFormat = MailFormat.Html
mymail.Priority = MailPriority.High
mymail.Subject = subject
SmtpMail.Send(mymail)

Create cookies
HttpContext.Current.Response.Cookies(“nameofCookie”).value = assign value

Read Cookie
variable = HttpContext.Current.Request.Cookies("campuscornerlogin").Value
remove cookies

Dim _cookie As HttpCookie

For i As Integer = 0 To Request.Cookies.Count


_cookie = Request.Cookies(i)
_cookie.Expires = DateTime.Now.AddDays(-5)
_cookie.Value = Nothing

Response.Cookies.Add(_cookie)
Next

session

HttpContext.Current.Session("campuscorneruserid")= givevalue

Remove session
HttpContext.Current.Session.Remove("campuscorneruserid")
HttpContext.Current.Session.RemoveAll()
HttpContext.Current.Session.Abandon()

Cookies :------------------

Cookies provide a useful means in Web applications to store user-specific information. JavaScript developers have been
doing the bulk of cookie-related work for many years. ASP.NET also provides cookie access through the System.Web
namespace. While you shouldn't use cookies to store sensitive data, they're an excellent choice for more trivial data such as
color preferences or last-visit date.

Pass the cookies


Cookies are small files stored on the client computer. If you're a Windows user, examine the Cookies directory in your user
directory, which is within the Documents And Settings directory. This directory contains text files with this filename format:

username @ Web site domain that created the cookie

The text files may contain name/value pairs, separated by an equal sign, along with more information. Let's turn our
attention to working with these files in ASP.NET.

Cookie interaction in ASP.NET


The .NET System.Web namespace has three classes that you can use to work with client-side cookies:

• HttpCookie: provides a type-safe way to create and manipulate individual HTTP cookies.

• HttpResponse: The Cookies property allows client cookies to be manipulated.

• HttpRequest: The Cookies property allows access to cookies that the client maintains.

The Cookies property of both the HttpResponse and HttpRequest objects returns an HttpCookieCollection object. It has
methods to add and retrieve individual cookies to and from the collection.

HttpCookie class
The HttpCookie class allows individual cookies to be created for client storage. Once the HttpCookie object is created and
populated, you can add it to the Cookies property of the HttpResponse object. Likewise, you can access existing cookies via
the HttpRequest object. The HttpCookie class contains the following public properties:

• Domain: Gets or sets the domain associated with the cookie. This may be used to limit cookie access to the specified
domain.

• Expires: Gets or sets the expiration date and time for the cookie. You may set this to a past date to automatically expire
or delete the cookie.

• Names: Gets or sets the cookie name.

• Path: Gets or sets the cookie's virtual path. This allows you to limit the cookie's scope; that is, access to the cookie may be
limited to a specific folder or directory. Setting this property limits its access to the specified directory and all directories
beneath it.

• Secure: Signals whether the cookie value is transmitted using Secure Sockets Layer (SSL).

• Value: Gets or sets an individual cookie value.

• Values: Retrieves a collection of key/value pairs contained within the cookie.

While this isn't an exhaustive list, it provides everything you need to work with cookies. A VB.NET example will give you a
better idea of how it works:

Dim testCookie As New HttpCookie("LastVisited")


testCookie.Value = DateTime.Now.ToString
testCookie.Expires = DateTime.Now.AddDays(7)
testCookie.Domain = "builder.com"
Response.Cookies.Add(testCookie)

This code creates a new cookie with the name LastVisited and populates the value with today's date and time. Also, the
cookie expiration is set to one week, and the associated domain is populated. Once the object is created, it's added to the
client's cookies collection via the Response.Cookies object's Add method. The HttpCookie constructor method has two
variations:

• HttpCookie objectName = New HttpCookie("cookieName")

• HttpCookie objectName = New HttpCookie("cookieName", "cookieValue")

Also, the Response object contains a SetCookie method that accepts an HttpCookie object.

Where's my cookie?
Once cookies are stored on the client, there are various ways that you can access them. If you know the cookie name, you can
easily access its value(s) with the HttpResponse object. The following VB.NET line displays the value associated with the
cookie:

Response.Write(Request.Cookies("LastVisitied").Value)

In addition, the complete list of cookies may be accessed via an HttpCookieCollection object. This allows the cookie list to be
processed with a for loop. The following C# code provides a sample:

HttpCookieCollection cookies;
HttpCookie oneCookie;
cookies = Request.Cookies;
string[] cookieArray = cookies.AllKeys;
for (int i=0; I < cookieArray.Length; i++) {
oneCookie = cookies[cookieArray[i]];
Response.Write(oneCookie.Name + " - " + oneCookie.Value);
}

Here's the same code in VB.NET:

Dim i As Integer
Dim oneCookie As HttpCookie
For i = 0 To Request.Cookies.Count - 1
oneCookie = Request.Cookies(i)
Response.Write(oneCookie.Name + " - " + oneCookie.Value)
Next I

Stability is an issue
The cookie files are stored on the client machine, so your users can delete or edit them at any time. In addition, some users
may disable cookies. For this reason, never rely on that data. You should store critical information on the server--preferably
in a database. Also, you should use cookies only for minor information that may customize the user experience.

Storing critical information in a cookie is considered poor programming because it can be viewed easily, since it resides in a
file on the client machine. One way around this is to use SSL; a better approach is to avoid cookies with sensitive
information.

Can I use cookies?


Users may disable cookie support in their browser. You can access this setting in your code to determine if cookies are
supported. The Request object makes this determination easy. The following VB.NET code shows how it's used:

If Request.Browser.Cookies = True Then


' Work with cookies
Else
' No cookie support
End If

This may be combined with code to utilize cookie values. The following C# code snippet tests for cookie support and
populates a text box control accordingly (whether a cookie is present or not):

if (Request.Browser.Cookies == true)
{
if (Request.Cookies["LastVisited1"] == null)
{
HttpCookie newCookie = new HttpCookie("LastVisited1",DateTime.Now.ToString());
newCookie.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(newCookie);
this.txtName.Text = "Is this your first time?";
} else {
this.txtName.Text = "We haven't seen you since " +
Request.Cookies["LastVisited1"].Value;
} }

You could place this code in the Page_Load event of an ASP.NET page.

Another way to store data


ASP.NET provides several methods for storing user-specific data. One of the older methods is cookies. While cookies aren't
the best vehicle for sensitive data, they're an excellent choice for benign items such as color preferences, last-visit date, and
so forth. While this data is important, it isn't the end of the world if it's lost when the user's computer crashes.

Vous aimerez peut-être aussi