Visual Basic .NET Power Tools

Team Fly 

Page 326

Using Session State

ASP.NET includes a Session object that can persist data and can make that data global to all the pages in a given website. To see how to use the Session object, start a new ASP.NET Web service project and replace the commented green template code with the code in Listing 13.3.

LISTING 13.3: SAVING STATE IN THE SESSION OBJECT

<WebMethod(Description:=''Figures visits.",enablesession:=True)> Public Function CountVisits() As Integer        If Session("counter") Is Nothing Then            Session.Add("counter", 1)        Else            Session("counter") += 1        End If        Return Session("counter")End Function

WARNING You must add the Description argument in this method, because the enablesession argument can't come first in an argument list.

Your session variable named counter tracks the number of times this method is invoked during a given session. Notice that the name within the parentheses—here, counter—is used as an ordinary variable name. If you wish, you could get a unique ID from the session object by changing the declaration, as in

Public Function CountVisits() As String

and then replacing the Return with this line:

Return Session.SessionID

When this Web service is consumed, you get the ID, which looks something like this:

<?xml version="1.0" encoding== "utf-8" ?>  <string xmlns= "http://tempuri.org/services/Service1"> d2lpzlq5pk1ctnqntwcb4a45  </string>

Making a Database Connection

Given that most all computer business applications require database connections, you want to know how to connect a database to Web services. This next example shows you how to make that connection. The example assumes that you have the Pubs sample databases available on your hard drive. If

Team Fly 

Категории