Maintaining Session State

Web services are sometimes criticized as being a great technology that has nothing to do with the Web itself. But since .NET web services are seamlessly integrated with ASP.NET (naturally), if you’re using ASP.NET, you’re able to perform some tricks that enable scenarios that web services technology by itself cannot offer.

With .NET web services, for example, you can maintain session state. And even if you are using Ajax, this session state is still available to you from your Atlas application.

Implementing this is easier than describing it. The EnableSession property of the [WebMethod] attribute does the trick—exactly as if you were coding a .NET web method:

[WebMethod(EnableSession=true)]

Then you can directly access the ASP.NET Session object and write data to it and read from it. The next code snippet shows code for two functions: one stores the current time in a session, and the other one determines the difference between the current time and the timestamp in the session. If there is no timestamp in the session, -1 is returned.

 [WebMethod(EnableSession = true)]
public bool SaveTime()
{
  Session["PageLoaded"] = DateTime.Now;
  return true;
}

[WebMethod(EnableSession = true)]
public double CalculateDifference()
{
  if (Session["PageLoaded"] == null) {
    return -1;
  } else {
    DateTime then = (DateTime)Session["PageLoaded"];
    TimeSpan diff = DateTime.Now.Subtract(then);
    return diff.TotalSeconds;
  }
}

Now let’s return to our application for handling the division of two ...

Get Programming Atlas now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.