Académique Documents
Professionnel Documents
Culture Documents
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
<html>
<body>
<asp:Label ID="Output" RunAt="server" />
</body>
</html>
try {
reader = new StreamReader (Server.MapPath
("Quotes.txt"));
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
in Global.asax adds a DataSet named ds to the application cache and keys it with the string "MyData." The statement
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:
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:
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:
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:
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>
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
void Application_Start ()
{
_cache = Context.Cache;
_path = Server.MapPath ("Quotes.txt");
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>
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).
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.
Digg This
Add to del.icio.us
Kick It
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:
Note: A lightweight version of SQL Server is installed when the .NET SDK is installed.
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#
The utility is now failing when trying to export the data around 100000 rows in table. It is giving
out of memory exception.
DataSet resultDataSet =
xdo.ExecDataSetSQL(sqlStatementField);
if (resultDataSet != null &&
resultDataSet.Tables.Count > 0)
result = resultDataSet.Tables[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.
| | | | | | | | | | | | | | | | | |
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
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
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
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.
Array of Strings:
VB/C# <%# Container.DataItem %>
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.
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:
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#.
Search Microsoft.com
• 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.
NestedRepeater. If you use the local server, leave the server name as
http://localhost/ NestedRepeater
Click OK.
7. The new Web Form is created. It opens in Design View in the Integrated
Toolbox, select the Repeater control, and then drag it to the Web Form page.
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
14. </itemtemplate>
After you do that, the HTML code for the Repeater is as follows:
<itemtemplate>
%></b><br>
</itemtemplate>
</asp:Repeater>
16. Add the following namespace declaration to the top of the file:
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:
21. {
22. //Create the connection and DataAdapter for the Authors table.
SqlConnection("server=(local);database=pubs; Integrated
Security=SSPI");
authors",cnn);
25.
28. cmd1.Fill(ds,"authors");
30. //Bind the Authors table to the parent Repeater control, and call
DataBind.
32. Page.DataBind();
33.
35. cnn.Close();
36. }
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.
o 213-46-8915
o 238-95-7766
o 267-41-2394
o ...
line of code:
<itemtemplate>
<%# DataBinder.Eval(Container.DataItem,
"[\"title_id\"]")%><br>
</itemtemplate>
</asp:repeater>
3. Set the DataSource property for the child Repeater control as follows:
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:
<itemtemplate>
<b>
</b>
<br>
datasource='<%# ((DataRowView)Container.DataItem)
<itemtemplate>
<%#
DataBinder.Eval(Container.DataItem, "[\"title_id\"]")%><br>
</itemtemplate>
</asp:Repeater>
</itemtemplate>
</asp:Repeater>
8. In the code-behind page, replace the following line in the Page_Load event
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
11. View the page in the browser, and then verify that the page works so far. The
172-32-1176
PS3333
213-46-8915
BU1032
BU2075
238-95-7766
PC1035
267-41-2394
BU1111
TC7777
...
Nestedrepeater.aspx
<body>
<form runat=server>
<itemtemplate>
((DataRowView)Container.DataItem)
<itemtemplate>
</itemtemplate>
</asp:repeater>
</itemtemplate>
</asp: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 NestedRepeater()
authors",cnn);
cmd1.Fill(ds,"authors");
titleauthor",cnn);
cmd2.Fill(ds,"titles");
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();
cnn.Close();
InitializeComponent();
REFERENCES
For more information, refer to the following topics in the Microsoft .NET Framework
http://msdn.microsoft.com/library/default.asp?url=/library/en-
us/cpguide/html/cpconaddingrelationshipbetweentwotables.asp
http://msdn.microsoft.com/library/default.asp?url=/library/en-
us/cpguide/html/cpconnavigatingrelationshipbetweentwotables.asp
http://msdn.microsoft.com/library/default.asp?url=/library/en-
us/cpgenref/html/cpconrepeaterwebservercontrol.asp
Back to the top
APPLIES TO
Yes
No
I don't
know
Yes
No
Get Help
Now
Contact a
support
professional
by E-mail,
Online, or
Phone
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.
[c#]
using System.Security.Principal;
using System.Web.Security;
Create a Web Form named login.aspx, set the style to Flow Layout, and put this onto
the page:
[vb.net]
Imports System.Web.Security
'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
[c#]
using System.Web.Security;
//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;
}
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:
<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>
[vb.net]
Imports System.Web.Security
[c#]
using System.Web.Security;
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
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.
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.
• HttpCookie: provides a type-safe way to create and manipulate individual HTTP cookies.
• 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.
• 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).
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:
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:
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);
}
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.
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.