How to Store and Retrieve an Object from Cookie in ASP.NET C#


Hi,

The name of the article suggests a typical problem which the developers come around whenever they are designing a login Form or want to store some useful object in the Cookie.

Unfortunately, cookies are unsecured and they can store string value only. So, to come out of this problem one need to understand that all data can not be / must not be saved in the Cookie. Some basic information like Login Name, user name, email can be saved but not password. Also, the developer need to make sure that no one can read the information except the website for which it is designed.

Solution?

1. First you need to prepare the object: How? – This can be done by serializing the object as a string. XML, JSON, base-64 of arbitrary binary etc.

2. Now, once your object is prepared, you need to add some security. In other word you need to encrypt the string such a way that the content can be readable by you only.

3. Last step: very easy, store the encrypted content as a string in the Cookie.

How to retrieve?

Just do the opposite.

1. Get the content of the cookie as a string

2. Decrypt the string

3. Deserialize it

4. Use the object as you like.

Now, lets see an example code.

here is the class whose object I want to store in my Cookie:

public class clsAdmin
{
private string _name;

public string Name
{
get { return _name; }

set { _name = value; }
}

private int _id;

public int AdminId
{
get { return _id; }
set { _id = value; }
}
}

Now, to serialize the object we can use the following code:

clsAdmin admin = new clsAdmin();

admin.Name = “UBK”;

admin.AdminId = 1;

//  Serialize it

String _serAdmin = SerializeAnObject(admin);

So, you have your serialized string. Now, you need to encrypt it. For this you can refer to this article or use your own code.

String _encVal = EncDec.Encrypt(_serAdmin, “YOUR PASSWORD”);

This time your data is ready to be saved in a cookie.

try
{
HttpCookie myCookie = new HttpCookie(“admin_cookie”);
DateTime now = DateTime.Now;

// Set the cookie value.
myCookie.Value = _encVal;

// Set the cookie expiration date.
myCookie.Expires = now.AddDays(14);

// Add the cookie.
Response.Cookies.Add(myCookie);
}
catch (Exception _e)
{
//Failed to add Cookie
throw _e;
}

Once your Cookie is added, this is time to use it in our code.

try
{
HttpCookie myCookie = new HttpCookie(“admin_cookie”);
myCookie = Request.Cookies[“admin_cookie”];

// Read the cookie information and display it.
if (myCookie != null)
{
string _admStr = EncDec.Decrypt(myCookie.Value, “YOUR PASSWORD”);
clsAdmin _adm = DeSerializeAnObject(_admStr, typeof(clsAdmin)) as clsAdmin;

if (null != _adm && _adm.Login.Length > 0)
{
//DO Whatever you want with the object
}
}
else
Response.Write(“not found”);
}
catch (Exception _e)
{
//Failed to read cookie?
throw _e;
}

For XML Serializer I have used the wonderful code from http://weblogs.asp.net/stevewellens/archive/2009/07/02/serializing-and-deserializing-objects-to-and-from-xml.aspx

/// ---- SerializeAnObject -----------------------------
/// <summary>
/// Serializes an object to an XML string
/// </summary>
///AnObject">The Object to serialize
/// <returns>XML string</returns>

public static string SerializeAnObject(object AnObject)
{
    XmlSerializer Xml_Serializer = new XmlSerializer(AnObject.GetType());
    StringWriter Writer = new StringWriter();      

    Xml_Serializer.Serialize(Writer, AnObject);
    return Writer.ToString();
}
 

/// ---- DeSerializeAnObject ------------------------------
/// <summary>
/// DeSerialize an object
/// </summary>
///XmlOfAnObject">The XML string
///ObjectType">The type of object
/// A deserialized object...must be cast to correct type

public static Object DeSerializeAnObject(string XmlOfAnObject, Type ObjectType)
{       
    StringReader StrReader = new StringReader(XmlOfAnObject);
    XmlSerializer Xml_Serializer = new XmlSerializer(ObjectType);
    XmlTextReader XmlReader = new XmlTextReader(StrReader);
    try
    {
        Object AnObject = Xml_Serializer.Deserialize(XmlReader);
        return AnObject;
    }
    finally
    {
        XmlReader.Close();
        StrReader.Close();
    }
}

Hope this will help someones quest :)

An AJAX Class: To use AJAX (Asynchronous JavaScript and XML) in a better way


An AJAX Class: To use AJAX (Asynchronous JavaScript and XML) in a better way

Class: clsAjax.js

 

// JavaScript Document

/*

* This file creates the instance of xmlHttpRequest object, sends and

* receives the request and response respectively.

* @Author Udaybhanu Karmakar

*/

/*

* Static script to instantiate XMLHttp object for different browsers.

*/

 

function ServerXMLHTTPRequest()

{

          this.clientHttpHandler = create();

          this.httpMethod = “GET”;

          this.serverUrl = “”;

          this.isAsync = true;

          this.respFunc = “”;

          this.send = function () {

                                                if(this.serverUrl != “”)

                                                 {

                                                          this.clientHttpHandler.open(this.httpMethod, this.serverUrl, this.isAsync);

                                                          this.clientHttpHandler.onreadystatechange = this.respFunc;

                                                          this.clientHttpHandler.send(null);

 

                                                 }

                                      };

          this.receive = receive;       

}

 

 

/* This method creates the xmlHttpRequest object and returns it.

*/

function create()     

{

          var xmlHttpRequest = false;

 

          //Internet Explorer

          try{

                   xmlHttpRequest = new ActiveXObject(“Msxml2.XMLHTTP”);

                   //alert(“creating new Msxml2.XMLHTTP obj”);

          }catch (xml2Exception){

                   try{

                             xmlHttpRequest = new ActiveXObject(“Microsoft.XMLHTTP”);

                             //alert(“creating new Microsoft.XMLHTTP obj”);

                   }catch (xmlException){

                             xmlHttpRequest = false;

                   }

          }

 

          //Netscape, Mozila, Firefox, Safari, Opera

          if (!xmlHttpRequest && typeof XMLHTTPRequest == ‘undefined’){

                   try{

                             //alert(“creating new ff obj”);

                             xmlHttpRequest = new XMLHttpRequest();

                   }catch (genException){

                             XMLHttpRequest = false;

                   }

          }

         

          if (!xmlHttpRequest && window.createRequest){

                   try{

                             xmlHttpRequest = window.createRequest();

                   }catch (e){

                             xmlHttpRequest=false;

                   }

          }

 

          return xmlHttpRequest;

}

 

/*

* This method checks the state and the status of the response and

* depending on that fetches the response text.

* readystate: 0 – uninitialized, 1 – loading, 2 – loaded, 3 – interactive, 4 – complete

*/

function receive(){

          var status = null;

          try{

                   if (this.clientHttpHandler.readyState == 4){

                             status = this.clientHttpHandler.status;

                             if (status == 200){

                                      return true;

                             }

                   }

                   return false;

          }catch (genException){

                   alert(“Error accessing Data.\nStatus returned: ” + status);

          }

}

 

//Destructor

 

function destructObj(objToDestroy){

          objToDestroy = null; 

}

  

Suppose we have one text box and one button in a HTML page.

 

From this page users can add their emails in the mailing list by adding their email in the text box and clicking on the save button.

 

So in HTML first we have to create a page to display on text box and one button.

 

Page: addUserToMailingList.html

 

<html>

<head>

<title>Ajax Class Example – Mailing List</title>

</head>

<body>

<h1>Add my email to mailing list </h1>

<table width=”80%” border=”0″>

  <tr>

    <td width=”17%”>Email Address </td>

    <td width=”23%”><input name=”txtEmail” type=”text” id=”txtEmail”> </td>

    <td width=”60%”><input type=”button” name=”saveBtn” value=”Add email”></td>

  </tr>

</table>

</body>

</html>

 

Now in the onclick event for the Add email button we have to fire some code to save the email in the Mailing list in the background.

 

So after adding the JavaScript in the head section and adding the event listener for the Save button the HTML page now becomes:

 

<html>

<head>

<title>Ajax Class Example – Mailing List</title>

<script type=”text/javascript” src=””></script>

<script type=”text/javascript”>

var ajaxObject = null;

var response = null;

 

function saveEmail(){

          var emailAddr = document.getElementById(“txtEmail”).value;

          sendSaveEmailRequest(email);

}

 

/*

Function to send

*/

 

function sendSaveEmailRequest(email){

 

          //Initialize the Ajax Object

         

          if (ajaxObject == null){

                   ajaxObject = new ServerXMLHTTPRequest();

          }

                  

          //The url of the backend page to add the email address in Database

          serverURL = “save.user.emaillist.asp”;

          //Add the email address as query string

          //Add a random number at the end to stop IE caching

          queryString = “?userEmail=” + email + “&random=” + Math.random();

 

          if (queryString != “”){

                   serverURL += “?” + queryString;

          }

         

          if (serverURL != “”){

                             //Give the backgound page URL

                             ajaxObject.serverUrl = serverURL;

                             //Give the function name to execute after processing

                             ajaxObject.respFunc = receiveChangeData;

                             //Send asynchoronous request

                             ajaxObject.isAsync = true;

                             //Send the request

                             ajaxObject.send();

          }

}

 

function receiveChangeData(){

          if (ajaxObject.receive()){

                   //Destroy the response object for better use.

                   //There might be data of the previous call.

                  

                   if(response != null){

                             response = null;

                   }

 

                   //Now get the response as text

                   response = ajaxObject.clientHttpHandler.responseText;

                  

                   var str = “”;

                  

                   //If the backend page gives output as “OK” the user email successfully added

                  

                   if(response==’OK’){                     

                             alert(“User email added successfully in the email list”);             

                            

                   }else if(response==’NOK’){ //Else there is some problem adding

                             alert(“There is some problems adding user in the email list. \n Please check.”);

                   }

                   //Now destruct the object

                   destructObj(ajaxObject);

          }

}

</script>

</head>

<body>

<h1>Add my email to mailing list </h1>

<table width=”80%” border=”0″>

  <tr>

    <td width=”17%”>Email Address </td>

    <td width=”23%”><input name=”txtEmail” type=”text” id=”txtEmail”> </td>

    <td width=”60%”><input type=”button” name=”saveBtn” value=”Add email” onClick=”javascript:saveEmail()”></td>

  </tr>

</table>

</body>

</html>

 

 

Now we should create one backend page i.e save.user.emaillist.asp to save the data:

 

 

Page save.user.emaillist.asp

 

<%@LANGUAGE=”VBSCRIPT” CODEPAGE=”1252″%>

<%

Dim userEMail

 

userEMail = Request.QueryString(“userEmail “)

‘If email is not blank then add it to Database

 

If userEMail <> “” Then

‘Add user in Database

‘If addition success then

‘Response.write(“OK”)

‘Else

‘Response.write(“NOK”)

End If

%>