Reading and Writing Cookies

Sometimes using viewstate and hidden form fields are just not enough to be able to control the actions and views of our website visitors.

As an alternative to viewstate and hidden form fields we may wish to make use of cookies. Cookies are, typically, short pieces of information stored on a users computer.

To handle cookies in .Net we have two functions, one for writing and one for reading our value:

Protected Function WriteCookie(ByVal CookieName As String, ByVal CookieValue As String)
  Try
    Dim objCookie As New System.Web.HttpCookie(CookieName, CookieValue)
    objCookie.Expires = DateTime.Now.Add(New TimeSpan(0, 0, 30, 0))
    Response.Cookies.Add(objCookie)
  Catch exc As Exception
    ProcessModuleLoadException(Me, exc)
  End Try
End Function

Protected Function ReadCookie(ByVal CookieName As String)
  Try
    If Not Context.Request.Cookies(CookieName).Value Is Nothing Then
      Return Context.Request.Cookies(CookieName).Value
    Else
      Return ""
    End If
  Catch exc As Exception
    ProcessModuleLoadException(Me, exc)
  End Try
End Function

To write a value to a cookie we will then call the WriteCookie function

WriteCookie(“itemId”, itemId.ToString)

And similarly to read the cookie value we will use the ReadCookie function

If ReadCookie(“itemId”) = “” Then

Putting our read and write together we have:

Dim objc As New Controller
Dim obj As New Info
If ReadCookie("ItemId") = "" Then
  itemId = objc.AddProperty(obj)
  WriteCookie("itemId", ItemId.ToString)
Else
  itemId = ReadCookie("ItemId")
End If
lblItemId.Text = itemId

In the above example AddProperty is a stored procedure to add a property to a database,

We first check to see whether the cookie has been set. If it has then we shall be using that value instead. If all is clear then we are free to add our property to the database.

This arrangement was used to prevent multiple inserts into a database, following repeated pressing of the browser refresh key.