ASP.NET Client-Side State Management – ViewState, Cookies and QueryString

Web form pages are HTTP-Based, they are stateless, which means they don’t know whether the requests are all from the same client, and pages are destroyed and recreated with each round trip to the server, therefore information will be lost and state management is a major issue in developing web applications. In this article we review how to handle state manage on the client using ViewState , Cookies, Hidden Fields and QueryStrings.

1. ASP.NET ViewState

Each control on a Web Forms page, including the page itself, has a ViewState property, it is a built-in struture for automatic retention of page and control state, which means you don’t need to do anything about getting back the data of controls after posting page to the server.

Here, which is useful to us is the ViewState property, we can use it to save information between round trips to the server.

//to save information
ViewState.Add(“shape”,”circle”);
//to retrieve information
string shapes=ViewState[“shape”];

Note: Unlike Hidden Fields, the values in ViewState are invisible in the ‘viewsource’ of the page, they are compressed and encoded.

2. ASP.NET Cookies .

A cookie is a small amount of data stored either in a text file on the client’s file system or in-memory in the client browser session. Cookies are mainly used for tracking data settings.

Let’s take an example: say we want to customize a welcome web page, when the user request the default web page, the application first to detect if the user has logined before, we can retrieve the user informatin from cookies:

if(Request.Cookies[“username”]!=null)
 lbMessage.text=”Dear“+Request.Cookies[“username”].Value+”, Welcome shoppinghere!”;
else
 lbMessage.text=”Welcome shoppinghere!”;

If you want to storeclient’s information, you can use the following code:

Response.Cookies[“username’].Value=username;

So next time when the user request the web page, you can easily recongnize the user again.

3. ASP.NET Hidden Fields

A hidden field does not render visibly in the browser,but you can set its properties just as you can with a standard control. When a page is submitted to the server, the content of a hidden field is sent in theHTTP Form collection along with the values of other controls.

A hidden field acts as a repository for any page-specific information that you would like tostore directly in the page. Hidden field stores a single variable in itsvalue property and must be explicitly added it to the page.
ASP.NET provides the HtmlInputHidden control that offers hidden field functionality.

protected System.Web.UI.HtmlControls.HtmlInput Hidden Hidden1;
//to assign a value to Hiddenfield
Hidden1.Value=”this is a test”;
//to retrieve a value
stringstr=Hidden1.Value;

Note: Keep in mind, in orderto use hidden field, you have to use HTTP-Post method to post web page. Although its name is ‘Hidden’, its value is not hidden, you can see its value through ‘view source’ function.

4. ASP.NET QueryStrings

Query strings provide a simple but limited way of maintaining some state information.You can easily pass information from one page to another, But most browsers and client devices impose a 255-character limit on the length of the URL. In addition, the query values are exposed to the Internet via the URL so in some cases security may be an issue.Continues…

Implementing a Generic Data Access Layer in ADO.NET Part 3

In this the final article of this series, I will discuss the other classes in this framework and how we can use this framework to perform various CRUD operations in our applications.

Let us start from where we left off in the previous part of this series. Note that most of the methods of the DatabaseHelper class have been marked as “internal” to prevent them from being called outside of the “ApplicationFramework.DataAccessLayer” namespace.

Now we will come to the DBManager class; the wrapper class that encapsulates the calls to another class called DBHelper that actually performs the CRUD operations on the underlying database. The DBManager class extends the DBManagerBase abstract class. The DBManagerBase class contains the definition for the Open () and the Close () methods and some other public properties that are generic and can be used by any class that acts as a wrapper. We will have a look at the DBManagerBase class first.

The following code listing shows the DBManagerBase class.

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Configuration;
using System.Data.Common;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data.Odbc;
using System.IO;

namespace ApplicationFramework.DataAccessLayer

{
public abstract class DBManagerBase

{

protected DatabaseHelper databaseHelper = null;
protected DbDataReader dbDataReader = null;
protected DataSet dataSet = null;
protected ProviderType providerType;
protected String connectionString = String.Empty;
protected bool isOpen = false;

public bool IsOpen

{

get
{
return isOpen;

}

set
{

isOpen = value;

}

}

 public string ConnectionString
{
get

{
return connectionString;
}

set

{
connectionString = value;
}

}

public DbConnection Connection
{
get
{

return databaseHelper.Connection;
}
}

public DbCommand Command

{
get
{

return databaseHelper.Command;
}

}

public ProviderType DBProvider
{
set
{
providerType = value;
}

get
{
return providerType;
}

}

public DataSet DBSet
{
get
{
return dataSet;
}

}

public DbDataReader DBReader
{
get
{
return dbDataReader;
}

}

protected void Open(string connectionString)

{
databaseHelper = new DatabaseHelper(connectionString, DBProvider);
}

protected void Close()
{
if (dbDataReader != null)
if (!dbDataReader.IsClosed)
dbDataReader.Close();
databaseHelper.Dispose();
}

public void BeginTransaction()
{
databaseHelper.BeginTransaction();
}

public void CommitTransaction()
{
databaseHelper.CommitTransaction();
}

 public void RollbackTransaction()
{
databaseHelper.RollbackTransaction();
}
}
}

Note that the DBManagerBase class contains the most common methods that are required. You can Open or Close a connection, Begin, Commit or Rollback transactions, etc. These methods would remain the same and are mandatory in this context even if you decide to have another version of the DBManager class with some more methods implemented it.
Continues…

Implementing a Generic Data Access Layer in ADO.NET Part 2

In the first part of this series of articles on Data Access Layer, we have had a look at what the strategies are, for designing and implementing a Generic Data Access Layer. We have had a look at the enumerators and the factory classes that we will be using. In this part of this article of three part series, we will discuss how we can implement the DatabaseHelper class, one that would be responsible for performing the actual database operations.

The DatabaseHelper class encapsulates the various calls to the database to perform the CRUD operations. The DBManager class that we will discuss later acts as a wrapper on top of this class. You have various methods in the DatabaseHelper class to add parameters, to execute queries, stored procedures, etc.

Here is the code that illustrates how the connection to the database is established based on the provider type chosen and the command object created.

 public DatabaseHelper(string connectionstring, ProviderType provider)
{
this.strConnectionString = connectionstring;
objFactory = DBFactory.GetProvider(provider);
objConnection = objFactory.CreateConnection();
objCommand = objFactory.CreateCommand();
objConnection.ConnectionString = this.strConnectionString;
objCommand.Connection = objConnection;
}

In ADO.NET, you have the following data providers.

  • SQL Server Data Provider
  • Oracle Data Provider
  • Odbc Data Provider
  • OleDB Data Provider

Note: Depending on the data provider used, you need to use the command object that is specific to that provider. Your data reader should also be specific to the data provider used. The use of the DBFactory class as shown in the code snippet above. Note that you use the command objects to execute the database commands that contain the SQL statements. Added to this, we will have overloaded versions of AddParameter method to add parameters to the command objects so that we can pass parameters to the database stored procedures or SQL statements. Here is the simplest version of the AddParameter method.

internal int AddParameter(string name, object value)

{
DbParameter dbParameter = objFactory.CreateParameter();
dbParameter.ParameterName = name;
dbParameter.Value = value;
return objCommand.Parameters.Add(dbParameter);
}

While the ParameterName identifies the unique name of the parameter to be passed, the Value implies the value of the parameter passed. Hence, if the ParameterName comprises of “@EmpName”, the Parameter’s value might be “Joydip Kanjilal”.
Continues…

Implementing a Generic Data Access Layer in ADO.NET Part 1

A Data Access Layer (DAL) is an integral part in the design of any application. There are plenty of articles that discuss how we an implement a DAL using ADO.NET. Most of these have constraints in the sense that they are not generic in nature. In other words, they are not provider independent. This series of articles will discuss the implementation of a generic, i.e., a provider independent Data Access Layer in ADO.NET. The basic prerequisite to learning this article is a proper understanding of ADO.NET and good coding skills in C#. I will present the code examples in this article in C#. However with little effort, you can twist it over to VB.NET as well.

The Strategies Involved in Creating a Data Access Layer

Let us first understand what the necessities are for building such a layer. I would rather start by discussing how an application designed using ADO.NET actually connects to the database and performs the CRUD (Create, Read, Update and Delete) operations.

First, you need to open the connection using a database provider. Fine, but what is a provider anyway? A provider is responsible for connecting to a specific database. Why specific? The reason is that a provider for an Oracle database cannot be used to connect to a SQL Server database and vice-versa. Next, you need a command object that can be used to execute the database commands of your choice. This is followed by the usage of a DataReader or a DataSet or a DataTable instance to retrieve data (if you are performing a Read operation) from the database table. When you use a DataSet, you need a DataAdapter as a bridge between the actual database and the DataSet instance.

Implementing the DAL Framework

With this in mind, let us design a provider independent Data Access Layer.

Let us first understand the ADO.NET Library. The major classes that constitute the ADO.NET library are:

     

  • Connection
  • Command
  • Data Reader
  • Data Adapter
  •  

The corresponding interfaces that the above classes implement are stated below.

     

  • IDBConnection
  • IDataReader
  • IDBCommand
  • IDBDataAdapter
  •  

The Data Providers that make up the library are specific to a particular database that they would connect to. These are the Data Providers that are available in ADO.NET.

     

  • SQL Server Data Provider
  • Oracle Data Provider
  • ODBC Data Provider
  • OleDB Data Provider
  •  

Now we are all set to implement our DAL. The major components that constitute our DAL block are:

     

  • ProviderType (Enum)
  • DatabaseConnectionState (Enum)
  • StoredProcedureParameterDirection (Enum)
  • DBManager (Class)
  • DBHelper (Class)
  •  

We will start our discussion with the enum data type that would contain the data provider types in it. These provider types relate to the databases that we will be connecting to, depending our requirements. The following code snippet illustrates the ProviderType enum that contains four values that correspond to a specific data provider.Continues…