Listing 73 Altered GUIDMaker Class That Always Returns a Single Unchanging GUID Value

(GuidMaker.es)

public class GuidMaker { private String sGUiD; public GuidMaker() { sGUiD = GuidString;

public String GuidString { get {

return sGUiD;

Now, you can create an instance of the GUIDMaker class, store it in a Session variable, and access the GUiDString property whenever you need the value. For example, create a new Web Form in the ch7 subdirectory of the CSharpASP application and name it ch7-3.aspx. Place the following code in the Page_Load event in the code-behind class file:

private void Page Load(object sender, System.EventArgs e) { GuidMaker gm;

for (int i = 0; i < arr.Length; i++) { arr[i] = "item " + i.ToString();

System.Diagnostics.Debug.WriteLine(arr[i]);

if (!(Session["counter"] == null)) { int i = (int) Session["counter"]; Session["counter"] = ++i;

Response.Write("Counter=" + Session["counter"].ToString() +

"<br>"); if (Session["guid"]==null) { gm = new GuidMaker(); Session["guid"] = gm;

Response.Write("The GUID value is: " + gm.GuidString + "<br>"); // Uncomment the following code to see the Add method in // action. When you do that, the display will increment from // 1 to 2, but will then remain at 2 no matter how many // times you refresh the browser. // Session.Add("counter", 1)

Save the changes, set the ch7.aspx Web Form as the start page, and run the application. You'll see the counter value and a GUID in the browser—similar to Figure 7.6. Of course, the GUID that your server generates will be different. By refreshing the page, you can see that the counter changes each time the Page_Load method fires, but the GUID remains the same. If you launch a new instance of the browser or close the current browser and restart the application, the GUID will change, because it's stored at Session scope. Thus, the GUID is different for each browser instance.

Figure 7.6: Session("counter") and Session("guid") values shown in a browser

There's a second way to create Session variables. The Session object is a wrapper for a hashed name/value collection that contains objects, so, as with most collections, you can use the collection's Add method to add objects to the collection. The syntax is as follows:

Session.Add(name,value);

For example, rather than writing Session["counter"] = 1, you could write Session.Add-

("counter", 1). The result is the same, regardless of which way you write the code. Note that the first method (except for the square brackets) is compatible with classic VBScript ASP code, while the second method is more like standard .NET collection code.

Was this article helpful?

0 0

Post a comment