First of all let me start by saying that this approach is not suitable for performance. I highly recommend you to use SQLSERVER session mode when sharing session data between applications. Anyway, I will make two applications Parent and the Child. Parent will pass the session to the Child and the Child will simply display the session variable on the screen.
Database:
CREATE TABLE Person
(
PersonID int identity(1,1) PRIMARY KEY,
Username nvarchar(50),
GUID nvarchar(50)
)
Parent Application Code:
I will be saving the username into the Session variable.
protected void Button1_Click(object sender, EventArgs e)
{
// Writes the session in the database
SaveSessionInDatabase(txtUserName.Text);
// Put in the database
Response.Redirect("http://localhost:2979/ChildApplication/Default.aspx?guid="+GUID);
}
private string ConnectionString
{
get { return ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; }
}
private string GUID
{
get
{
Guid guid = System.Guid.NewGuid();
string gID = string.Empty;
if (ViewState["GUID"] != null)
{
gID = ViewState["GUID"] as String;
}
else
{
ViewState["GUID"] = guid.ToString();
gID = ViewState["GUID"] as String;
}
return gID;
}
}
// This method saves the username in the database
private void SaveSessionInDatabase(string userName)
{
string query = "INSERT INTO Person(UserName,GUID) VALUES(@UserName,@Guid)";
SqlConnection myConnection = new SqlConnection(ConnectionString);
SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.Parameters.AddWithValue("@UserName", userName);
myCommand.Parameters.AddWithValue("@Guid", GUID);
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
}
The reason I am using GUID and sending it in the url is that you cannot predict the next value of the GUID and hence its much safer than other approaches. I saved the GUID in the viewstate because if some control causes the POSTBACK I don't want to have a new GUID for that person.
Child Application:
The child application extract the GUID from the url and look up the guid in the database table Person and fetch the userName.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (Request.QueryString["guid"] != null)
{
string quid = Request.QueryString["guid"] as String;
lblMsg.Text = GetSessionVariable(quid);
}
}
}
private string GetSessionVariable(string guid)
{
string query = "SELECT UserName FROM Person WHERE GUID = @GUID";
SqlConnection myConnection = new SqlConnection(ConnectionString);
SqlCommand myCommand = new SqlCommand(query, myConnection);
myCommand.Parameters.AddWithValue("@GUID", guid);
myConnection.Open();
string userName = (string) myCommand.ExecuteScalar();
myConnection.Close();
return userName;
}
private string ConnectionString
{
get { return ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; }
}
Ohh yeah I am using ASP.NET 2.0 BETA II. You can do the same thing in ASP.NET 1.X.