affiliate marketing Dot Net Posts: June 2011

Friday, 24 June 2011

Save multiples values into table in sql server using function

set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
CREATE FUNCTION [dbo].[Fxn_Global_SeperatedValues]
(@values varchar(Max) )
RETURNS @um_temp Table (person_id int)
AS
Begin
DECLARE @NextString VARCHAR(100)
DECLARE @Pos INT
DECLARE @Delimiter VARCHAR(10)
SET @Delimiter = ','
--SET @Values = @Values + @Delimiter
SET @Pos = CHARINDEX(@Delimiter,@Values)
WHILE (@pos <> 0)
BEGIN
SET @NextString = substring(@Values,1,@Pos - 1)
insert into @um_temp (person_id) values(@NextString)
SET @Values = substring(@Values,@pos+1,len(@Values))
SET @pos = charindex(@Delimiter,@Values)
End
return
End

How to use Cursor to Insert data into table

GO
/****** Object: StoredProcedure [dbo].[InsertData] Script Date: 04/08/2011 05:30:36 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
create procedure [dbo].[InsertData]
as
begin
DECLARE @MODEL_NO varchar(16),@MODEL_SERNO nvarchar(15),@MFG_DATE datetime,
@MFG_SOURCE nvarchar(5),@CUST_NO nvarchar(10),@ORDER_NO nvarchar(10),
@INVOICE_NO nvarchar(10),@SHIP_DATE datetime,@CREATE_DATE datetime,
@USER_ID nvarchar(10)
DECLARE wtytprod_cursor CURSOR FOR SELECT * FROM dbo.Temporary
OPEN wtytprod_cursor
FETCH NEXT FROM wtytprod_cursor
INTO @MODEL_NO,@MODEL_SERNO,@MFG_DATE,@MFG_SOURCE,@CUST_NO,@ORDER_NO,@INVOICE_NO,@SHIP_DATE,@CREATE_DATE,@USER_ID
WHILE @@FETCH_STATUS = 0
BEGIN
if exists(select * from dbo.WTYTPROD where MODEL_SERNO =@MODEL_SERNO)
update dbo.WTYTPROD set MODEL_NO =@MODEL_NO,MODEL_SERNO =@MODEL_SERNO,MFG_DATE =@MFG_DATE,MFG_SOURCE =@MFG_SOURCE,CUST_NO =@CUST_NO,ORDER_NO =@ORDER_NO,INVOICE_NO=@INVOICE_NO,SHIP_DATE=@SHIP_DATE,CREATE_DATE=@CREATE_DATE,[USER_ID]=@USER_ID where MODEL_SERNO=@MODEL_SERNO
else
insert into dbo.WTYTPROD (MODEL_NO,MODEL_SERNO,MFG_DATE,MFG_SOURCE,CUST_NO,ORDER_NO,
INVOICE_NO,SHIP_DATE,CREATE_DATE,USER_ID)values(@MODEL_NO,@MODEL_SERNO,@MFG_DATE,@MFG_SOURCE,@CUST_NO,@ORDER_NO,@INVOICE_NO,@SHIP_DATE,@CREATE_DATE,@USER_ID)
FETCH NEXT FROM wtytprod_cursor
INTO @MODEL_NO,@MODEL_SERNO,@MFG_DATE,@MFG_SOURCE,@CUST_NO,@ORDER_NO,@INVOICE_NO,@SHIP_DATE,@CREATE_DATE,@USER_ID
END
CLOSE wtytprod_cursor
DEALLOCATE wtytprod_cursor
END
GO

how to Search string for the exact word match in c#

Regex.IsMatch("Hello1 Hello2", "\bHello\b");


Something like this method below should work for you every time:


static bool ExactMatch(string input, string match)
{
return Regex.IsMatch(input, string.Format(@"\b{0}\b", Regex.Escape(match)));

}

Visual Studio 2010 Keyboard Shortcut - What are your favorites?

I am always looking for ways to code / browse through codes easier and faster. What are some of your favorites Visual Studio 2010 Keyboard Shortcut?
Here are some of mine.
1. View Call Hierarchy - CTRL + K + T
This shortcut has help me find where a method or properties are being used.
2. Cut Line to Clipboard - CTRL + L
It's an easy way to copy and paste a line or just deleting a line that's not being used quickly.
3. Searching without a search dialog - CTRL + F3 or CTRL + SHIFT + F3
This shortcut will use whatever keyword your mouse cursor is on as a text to find.
4. Fuzzy Search - CTRL + , (Comma Key)
Have you ever need to find methods, properties, file which contains a certain keywords and you don't really remember the full name? This is probably the best shortcut in Visual Studio 2010.
5. Find matching curly bracket - CTRL + }
This will help you find matching curly bracket for those hundred lines methods or classes.
6. Go back to the last method (where your cursor was) CTRL + -
Do you like pressing F12 to Go To Definition? This shortcut will help you get back where you were.

Lamda expression dynamically add where condition

using System;
using System.Linq;
using System.Linq.Expressions;
using System.Collections.Generic;
public static class PredicateBuilder
{
public static Expression> True () { return f => true; }
public static Expression> False () { return f => false; }
public static Expression> Or (this Expression> expr1,Expression> expr2)
{
var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast ());
return Expression.Lambda>(Expression.OrElse (expr1.Body, invokedExpr), expr1.Parameters);
}
public static Expression> And (this Expression> expr1,Expression> expr2)
{
var invokedExpr = Expression.Invoke (expr2, expr1.Parameters.Cast ());
return Expression.Lambda>(Expression.AndAlso (expr1.Body, invokedExpr), expr1.Parameters);
}
}
Using Predicate builder it is developed using lamda expressions for dynamically add and ,or condition in where query in Linqtosql.
 var predicate = PredicateBuilder.True();(Here ICP_ServiceProvider is Data base table)
string temp = Item.Value;
//>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
switch (Item.Target.ToUpper())
{
case "MFGACCTNUM":
if (Item.LogicalOperation.ToUpper() == "AND")
predicate = predicate.And(p => p.MfgAcctNum.StartsWith(temp));
else
predicate = predicate.Or(p => p.MfgAcctNum.StartsWith(temp));
break;
case "HVACPID":
if (Item.LogicalOperation.ToUpper() == "AND")
predicate = predicate.And(p => p.HVACPId.StartsWith(temp));
else
predicate = predicate.Or(p => p.HVACPId.StartsWith(temp));
break;
case "DISTRIBUTOR":
if (Item.LogicalOperation.ToUpper() == "AND")
predicate = predicate.And(p => p.Distributor.StartsWith(temp));
else
predicate = predicate.Or(p => p.Distributor.StartsWith(temp));
break;
default:
break;
}
}
var tmpdb = (from _ServiceProvider in PHDBContext.ICP_ServiceProviderMasters.Where(predicate)

C# 3.0/3.5 New Features: What is Object Initializers


C# 3.0 Features: Object Initializers

C# 3.0 is just around the corner so I thought I'd start writing about a few of the features that it exposes and provide quick and concise examples of how they can be used. Many of the new features rely on the compiler to generate code that you would have had to write in the past. This can result in significantly less code compared to C# 2.0 syntax in many cases. Here's a list of some of the key features available in C# 3.0:

Object Initializers

Anonymous Types

Automatic Properties

Extension Methods

Lambda Expressions

LINQ

Collection Initializers
In this post I'll discuss the fundamentals of object initializers in C# 3.0. To get started, let's look at the standard way of initializing an object with data in C# 2.0 using constructors. The following example creates a Person object and passes three values to its constructor.
Person p = new Person("John", "Doe", "602-123-1234");As mentioned, C# 3.0 now supports the concept of "object initializers" which means you can easily assign data to specific properties in a type with having to create an explicit constructor (you can of course still create constructors as well). The standard C# { and } brackets are used to create object initializers. Here's an example of using an object initializer to assign property data to a Person type. It's nice because doing the same thing without using a constructor in C# 2.0 would have resulted in around 5 lines of code which is too many for something simple like property value assignments.
Person p = new Person() {FirstName="John",LastName="Doe",Phone="602-123-1234",City="Phoenix"};If the Person type defines a sub object as a property you can even use object initializers to create the sub object. Here's an example of defining an Address object:
Person p = new Person()
{
FirstName = "John",
LastName = "Doe",
Address = new Address()
{
Street = "1234 St.",
City = "Phoenix"
}
};
If you've used JavaScript Object Notation (normally referred to as JSON) in AJAX or other client-side applications, you'll recognize this style of syntax. It's simple, compact, and easy to use. Although I formatted the example above onto multiple lines to maximize readability, it could certainly be compacted quite a bit if desired.
In the next post I do on C# 3.0 features I'll cover anonymous types and explain how they answer a question I'm often asked in .NET language classes I teach: "Why do I have to define a type name twice when creating an object?".

Using SQL Server for ASP.Net session state


 1)Tool to install the session state template
You can install the session state service to custom database with the installation template query:InstallSqlStateTemplate.sql

By default, InstallSqlStateTemplate.sql located in following folders:
C:\Windows\Microsoft.NET\Framework\version_ID\



Copy this sql file to another location, and update the template file:
- find and replace all reserved string DatabaseNamePlaceHolder within the template
- replace this string to the database name which install the session state service, for this tutorial -statedemoDB_62760



Execute the InstallSqlStateTemplate.sql via the Management Studio
1 - Click "New Query"
2 - Copy and paste the contents of updated InstallSqlStateTemplate.sql as sql query
3 - "Execute" the query4 - The result of the query execution

Query execution result:

-------------------------------------------------
Starting execution of InstallSqlStateTemplate.SQL
-------------------------------------------------

--------------------------------------------------
Note:                                             
This file is included for backward compatibility  
only.  You should use aspnet_regsql.exe to install
and uninstall SQL session state.                  

Run 'aspnet_regsql.exe -?' for details.         
--------------------------------------------------
If the job does not exist, an error from msdb.dbo.sp_delete_job is expected.
Msg 229, Level 14, State 5, Procedure sp_delete_job, Line 1
The EXECUTE permission was denied on the object 'sp_delete_job', database 'msdb', schema 'dbo'.
If the category already exists, an error from msdb.dbo.sp_add_category is expected.
Msg 229, Level 14, State 5, Procedure sp_add_category, Line 1
The EXECUTE permission was denied on the object 'sp_add_category', database 'msdb', schema 'dbo'.
Msg 229, Level 14, State 5, Procedure sp_add_job, Line 1
The EXECUTE permission was denied on the object 'sp_add_job', database 'msdb', schema 'dbo'.

--------------------------------------------------
Completed execution of InstallSqlStateTemplate.SQL
--------------------------------------------------

Normally, the core tables/stored procedures have installed on the database after execution
Above error message due to insufficient user privilege to add the scheduled job.
Which is a scheduled job to delete expired session state record of the session state database.

4.) Update the web.config file

Update the web.config to use the custom session state server/database:
Update/insert sessionState code:


        mode="SQLServer"
        allowCustomSqlDatabase="true"
        sqlConnectionString="data source=sql999.mysite4now.com;initial catalog=statedemoDB_62760;user id=statedemoUser_62760;password=statepassword"
        cookieless="false"
        timeout="20"
/>

** Use mode = SQLServer
** To use custom DB instead of default database "ASPSTATE" , need to enable option allowCustomSqlDatabase="true"
** sessionState : S is uppercase, case sensitive
** sqlConnectionString :  S are uppercase, case sensitive

5.) Create the scheduled job to delete expired sessions record in the database

Refer to steps 3.)
To setup the scheduled job for the session state database,
you need to purchase the scheduled Task service via control panel:
control panel -> Site Admin -> Schedule Task
      

image slide show in asp.net using ajax slideextender


suppose your image folder name is "TempImages"

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using FidesTech;

public partial class SlideShowTest : System.Web.UI.Page
{
private static DataTable tblData = new DataTable();

protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack)
return;

DBConnection db = new DBConnection();
string strSQL = "SELECT tbl_advertisment.ImagePath FROM tbl_advertisment";
MySql.Data.MySqlClient.MySqlConnection conn = new MySql.Data.MySqlClient.MySqlConnection(ConfigurationManager.AppSettings["connectionString"]);
conn.Open();

MySql.Data.MySqlClient.MySqlCommand comm = new MySql.Data.MySqlClient.MySqlCommand(strSQL, conn);
MySql.Data.MySqlClient.MySqlDataAdapter da = new MySql.Data.MySqlClient.MySqlDataAdapter(comm);
tblData = new DataTable();
da.Fill(tblData);
conn.Close();

// set the initial image
if (tblData.Rows.Count > 0)
{

// string seperated by '/'
// I am spliting path because in my database image path is saved like this format
//~/TempImages/image.jpg
//If you store your images with folder name then you also split the image path
//other wise if you just store the image name like image1.jpg then you dont need
//split the image path
//

string info = tblData.Rows[0]["ImagePath"].ToString();

string[] arInfo = new string[2];

// define which character is seperating fields
char[] splitter = { '/' };

arInfo = info.Split(splitter);

imgShowImage.ImageUrl = "TempImages/" + arInfo[2];
}
}

[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static AjaxControlToolkit.Slide[] GetSlides()
{
AjaxControlToolkit.Slide[] slides = new AjaxControlToolkit.Slide[tblData.Rows.Count];
string imagepath = "";
for (int i = 0; i < tblData.Rows.Count; i++)
{
DataRow dr = tblData.Rows[i];
string info = dr["ImagePath"].ToString();
string[] arInfo = new string[2];
// define which character is seperating fields
char[] splitter = { '/' };
arInfo = info.Split(splitter);
imagepath = arInfo[2];
slides[i] = new AjaxControlToolkit.Slide("TempImages/" + imagepath,"Image name","Image Description");
}
return slides;
}

}

Solution for Ajax Errors


Solution for Ajax Errors(http errors,bad request,invalid request errors etc)
<asp:ScriptManager ID="ScriptManager1" runat="server">
asp:ScriptManager>
<script type="text/javascript" language="javascript">
var divElem = 'AlertDiv';
var messageElem = 'AlertMessage';
var bodyTag = 'bodytag';
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
function ToggleAlertDiv(visString)
{
if (visString == 'hidden')
{
$get(bodyTag).style.backgroundColor = 'white';
}
else
{
$get(bodyTag).style.backgroundColor = 'gray';
}
var adiv = $get(divElem);
adiv.style.visibility = visString;
}
function ClearErrorState() {
$get(messageElem).innerHTML = '';
ToggleAlertDiv('hidden');
}
function EndRequestHandler(sender, args)
{
if (args.get_error() != undefined)
{
var errorMessage;
if (args.get_response().get_statusCode() == '200')
{
errorMessage = args.get_error().message;
}
else
{
// Error occurred somewhere other than the server page.
errorMessage = 'An unspecified error occurred. ';
}
args.set_errorHandled(true);
ToggleAlertDiv('visible');
$get(messageElem).innerHTML = errorMessage;
}
}
script>
<div id="alertdiv" style="visibility: hidden">
<div id="alertmessage">
div>
<br />
<div id="alertbuttons">
<input id="okbutton" type="button" value="ok" runat="server" onclick="clearerrorstate()" />
div>
div>

ASP.NET Session State

A session is defined as the period of time that a unique user interacts with a Web application. Active Server Pages (ASP) developers who wish to retain data for unique user sessions can use an intrinsic feature known as session state.

Programmatically, session state is nothing more than memory in the shape of a dictionary or hash table, e.g. key-value pairs, which can be set and read for the duration of a user's session. For example, a user selects stocks to track and the Web application can store these values in the user's ASP session instance:

Session("Stocks") = "MSFT; VRSN; GE"

On subsequent pages these values are read and the Web application has access to these values without the user re-entering them:

//Get Stocks, split string, etc.
string StockString ;
StockString = Session("Stocks");

ASP maintains session state by providing the client with a unique key assigned to the user when the session begins. This key is stored in an HTTP cookie that the client sends to the server on each request. The server can then read the key from the cookie and re-inflate the server session state.

Problems with ASP Session State

ASP developers know session state as a great feature, but one that is somewhat limited. These limitations include:

*
Process dependent. ASP session state exists in the process that hosts ASP; thus the actions that affect the process also affect session state. When the process is recycled or fails, session state is lost.
*
Server farm limitations. As users move from server to server in a Web server farm, their session state does not follow them. ASP session state is machine specific. Each ASP server provides its own session state, and unless the user returns to the same server, the session state is inaccessible. While network IP level routing solutions can solve such problems, by ensuring that client IPs are routed to the originating server, some ISPs choose to use a proxy load-balancing solution for their clients. Most infamous of these is AOL. Solutions such as AOL's prevent network level routing of requests to servers because the IP addresses for the requestor cannot be guaranteed to be unique.
*
Cookie dependent. Clients that don't accept HTTP cookies can't take advantage of session state. Some clients believe that cookies compromise security and/or privacy and thus disable them, which disables session state on the server.

These are several of the problem sets that were taken into consideration in the design of ASP.NET session state.

ASP.NET Session State

ASP.NET session state solves all of the above problems associated with classic ASP session state:

*
Process independent. ASP.NET session state is able to run in a separate process from the ASP.NET host process. If session state is in a separate process, the ASP.NET process can come and go while the session state process remains available. Of course, you can still use session state in process similar to classic ASP, too.
*
Support for server farm configurations. By moving to an out-of-process model, ASP.NET also solves the server farm problem. The new out-of-process model allows all servers in the farm to share a session state process. You can implement this by changing the ASP.NET configuration to point to a common server.
*
Cookie independent. Although solutions to the problem of cookieless state management do exist for classic ASP, they're not trivial to implement. ASP.NET, on the other hand, reduces the complexities of cookieless session state to a simple configuration setting.

Let's look at each of these features in more detail, including how the settings are configured.

Using ASP.NET Session State

Session state settings in ASP.NET are configured through the ASP.NET XML configuration file config.web. We'll look at config.web in more detail in a later column, but for this discussion of session state let's look at it briefly.

Config.web

There are two types of configuration files: a machine configuration file and an application configuration file, both named config.web. The two are identical, except that the machine configuration file applies settings to all applications but the application configuration files are either restrictive or expansive on an application-by-application basis.

In Beta 1, the machine config.web file is in the WinNT\Microsoft.NET\Framework\v1.0.2204 directory, while the optional application configuration files exist in the application's directory. Application config.web files are optional in the sense that if an application config.web file doesn't exist, the machine config.web settings are used instead. ASP.NET session state settings can be made in the machine config.web file and overridden in a particular application's config.web file.

Note: Changes made to config.web are applied immediately, unlike classic ASP, where the server has to be stopped and started for settings to take affect.

Session configuration

Below is a sample config.web file used to configure the session state settings for an ASP.NET application:

configuration>
sessionstate
mode="inproc"
cookieless="false"
timeout="20"
sqlconnectionstring="data source=127.0.0.1;user id=;password="
server="127.0.0.1"
port="42424" />
configuration>

The settings above are used to configure ASP.NET session state. Let's look at each in more detail and cover the various uses afterward.

*
Mode. The mode setting supports three options: inproc, sqlserver, and stateserver. As stated earlier, ASP.NET supports two modes: in process and out of process. There are also two options for out-of-process state management: memory based (stateserver), and SQL Server based (sqlserver). We'll discuss implementing these options shortly.
*
Cookieless. The cookieless option for ASP.NET is configured with this simple Boolean setting.
*
Timeout. This option controls the length of time a session is considered valid. The session timeout is a sliding value; on each request the timeout period is set to the current time plus the timeout value.
*
Sqlconnectionstring. The sqlconnectionstring identifies the database connection string that names the database used for mode sqlserver.
*
Server. In the out-of-process mode stateserver, it names the server that is running the required Windows NT service: ASPState.
*
Port. The port setting, which accompanies the server setting, identifies the port number that corresponds to the server setting for mode stateserver.

Sample session state application

Before we use session state, we need an application to test it with. Below is the code for a simple C# application that writes to and reads from session state, SessionState.aspx:

Script runat=server>
Public void Session_Add(sender As Object, e As EventArgs)
{
Session("MySession") = text1.Value;
span1.InnerHtml = "Session data updated!

Your session contains: " +
Session("MySession").ToString() + "
"
}
Public void CheckSession(sender As Object, e As EventArgs)
{
If (Session("MySession") = Isnull)
{
span1.InnerHtml = "NOTHING, SESSION DATA LOST!";
}
Else
{
span1.InnerHtml = "Your session contains:
font color=red>" +
Session("MySession").ToString() + "/font>"
}
}
Script>
form runat=server ID="Form1">
input id=text1 type=text runat=server NAME="text1">
input type=submit runat=server
OnServerClick="Session_Add" Value="Add to Session State" ID="Submit1" NAME="Submit1">
input type=submit runat=server
OnServerClick="CheckSession" Value="View Session State" ID="Submit2" NAME="Submit2">
form>
hr size=1>
font size=6>

This simple page wires up two server-side events for the Add and View buttons, and simply sets the session state to the value in the text box.

There are four general configuration settings we can look at in more detail: in-process mode, out-of-process mode, SQL Server mode, and Cookieless.

In-process Mode

In-process mode simply means using ASP.NET session state in a similar manner to classic ASP session state. That is, session state is managed in process and if the process is re-cycled, state is lost. Given the new settings that ASP.NET provides, you might wonder why you would ever use this mode. The reasoning is quite simple: performance. The performance of session state, e.g. the time it takes to read from and write to the session state dictionary, will be much faster when the memory read to and from is in process, as cross-process calls add overhead when data is marshaled back and forth or possibly read from SQL Server.

In-process mode is the default setting for ASP.NET. When this setting is used, the only other session config.web settings used are cookieless and timeout.

If we call SessionState.aspx, set a session state value, and stop and start the ASP.NET process (iisreset), the value set before the process was cycled will be lost.

Out-of-process Mode

Included with the .NET SDK is a Windows NT service: ASPState. This Windows service is what ASP.NET uses for out-of-process session state management. To use this state manager, you first need to start the service. To start the service, open a command prompt and type:

net start aspstate

What you'll see is:

session1.gif

Figure 1. Starting the Windows NT service ASPState at the command prompt

At this point, the Windows NT Service ASPState has started and is available to ASP.NET. Next, we need to configure ASP.NET to take advantage of this service. To do this we need to configure config.web:

configuration>
sessionstate
mode="stateserver"
cookieless="false"
timeout="20"
sqlconnectionstring="data source=127.0.0.1;user id=;password="
server="127.0.0.1"
port="42424" />
configuration>

We changed only from inproc mode to stateserver mode. This setting tells ASP.NET to look for the ASP state service on the server specified in the server and port settings-in this case, the local server.

We can now call SessionState.aspx, set a session state value, stop and start the IIS process (iisreset), and continue to have access to the values for our current state.

SQL Server Mode

The SQL Server mode option is similar to that of the Windows NT Service, except that the information persists to SQL Server rather than being stored in memory.

To use SQL Server as our session state store, we first must create the necessary tables and stored procedures that ASP.NET will look for on the identified SQL Server. The .NET SDK provides us with a SQL script (state.sql) to do just that.

state.sql

The state.sql file contains the SQL commands used to create the ASPState database. This script 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] 
sessionstate
mode="sqlserver"
cookieless="false"
timeout="20"
sqlconnectionstring="data source=MySqlServer;
user id=ASPState;
password=1Gr8State"
server="127.0.0.1"
port="42424" />
configuration>

Again, similar to the Windows NT service state manager, we can now call SessionState.aspx, set a session state value, stop and start the IIS process (iisreset), and continue to have access to the values for our current state. In fact, we could cluster the SQL Servers such that if one SQL Server happened to be unavailable, another server that was replicating its data could take its place. This provides a level of reliability that was not available in ASP.

Cookieless State

The last new feature that we can configure for ASP.NET session state is cookieless session state. Essentially this feature allows sites whose clients choose not to use cookies to take advantage of ASP.NET session state.

This is done by modifying the URL with an ID that uniquely identifies the session:

http://localhost/(lit3py55t21z5v55vlm25s55)/Application/SessionState.aspx

ASP.NET will modify relative links found within the page and embed this ID. Thus, as long as the user follows the path of links the site provides, session state can be maintained. However, if the end user re-writes the URL, the session state instance will most likely be lost.

The IIS 4.0 Resource Kit provided a similar feature. It was implemented as an ISAPI filter that could modify the incoming and outgoing byte stream to write and read the necessary information. The difference between this and the ASP.NET feature is the effort required to use the feature. In ASP.NET, it's simply a matter of flipping a Boolean value in the config.web file:

configuration>
sessionstate
mode="stateserver"
cookieless="true"
timeout="20"
sqlconnectionstring="data source=127.0.0.1;user id=;password="
server="127.0.0.1"
port="42424" />
blockquote>

blockquote>
configuration>

Once cookieless is set to true, ASP.NET will do the work necessary to enable cookieless session state. Also note that all modes are supported for cookieless sessions.

Performance and Reliability Considerations

It's worth mentioning, briefly, some of the performance and reliability issues you should consider when using ASP.NET session state modes.

*
In process. In process will perform best because the session state memory is kept within the ASP.NET process. For Web applications hosted on a single server, applications in which the user is guaranteed to be re-directed to the correct server, or when session state data is not critical (in the sense that it can be re-constructed or re-populated), this is the mode to choose.
*
Out of process. This mode is best used when performance is important but you can't guarantee which server a user will request an application from. With out-of-process mode, you get the performance of reading from memory and the reliability of a separate process that manages the state for all servers.
*
SQL Server. This mode is best used when the reliability of the data is fundamental to the stability of the application, as the database can be clustered for failure scenarios. The performance isn't as fast as out of process, but the tradeoff is the higher level of reliability.