Common asp.net Code techniques (DPC&DWC Reference)--6

Source: Internet
Author: User
Tags foreach count empty variables reset sessions classic asp
asp.net Figure 2.5
Output of Listing 2.1.5 when viewed through a browser.

If you have ' ve worked with classic ASP, your are likely familiar with the concept of session-level variables. These variables are defined in a per-user basis and last for the duration of the user's visit to the site. These variables are synonymous with global variables in-their values can be accessed across ASP pages. Session-level variables, which are discussed in greater detail at Chapter, "managing state," are a simple way to Mainta In a per-user basis. Because we want the user ' s navigation history stack to persist as the user bounces our site, we'll store the around K class instance in a Session-level variable.

To implement a navigation history stack as a Session-level variable, we must make sure this we have created such a variabl E before trying to reference it. Keep in mind this when a visitor a-comes to my site and visits that the page, the session-level variable would not B E instantiated. Therefore, on each page, before we refer to the navigation history stack, it's essential that we check to ensure Session-variable, session["History"], has been assigned to a instance of the Stack class.


--------------------------------------------------------------------------------

Note

To access a session variable using C #, the braces are used around the session variable name. For example, to retrieve the value of the History sessions variable with C # we use:

session["History"]
With vb.net, however, parentheses are used into place of the brackets:

Session ("History")


--------------------------------------------------------------------------------

Line 6 in Listing 2.1.5 checks session["History") to determine whether it references a Stack object instance. If session["History"] has not been assigned a object instance, it would equal null (or Nothing, in VB). If session["History" is null, we need to set it to a newly created the Stack class (line 9).

However, if session["History" is not NULL, we know this user has already visited at least one of the other page in our site. Therefore, we can display the contents of the session["History" Stack. This is accomplished in lines through and the use of a enumerator. We ' ll discuss iteration through collections via enumerators in the next section, similarities among the Collection. With C #, as opposed to VB, explicit casting must is done when working with the session object. For example, in line, before we can call the GetEnumerator () method (a method of the Stack Class), we must cast the Ses sion["History"] variable to a Stack:

C # code must use an explicit cast
IEnumerator enumhistory = ((Stack) session["History"]). GetEnumerator ();

' VB code, however, does not require a explicit cast
Dim EnumHistory as IEnumerator = Session ("History"). GetEnumerator ()
With VB, however, such a are not necessary. Casting issues with the sessions object are discussed in more detail in Chapter 14.

After either creating a new Session-level stack instance or displaying the stack ' s contents, we ' re ready to add the Curren T URL to the navigation history stack. This could is accomplished with the following simple line of code:

((Stack) session["History"]). Push (Request.Url.PathAndQuery);
However, if the user refreshed the current page, it would, again, get added to the navigation stack. It would is nice to have the same page repeatedly appear in the navigation stack. Therefore, on line, "We use the" Peek method "to" if the top-most element in the Stack isn't equal to the current URL. If the top-most element of the ' stack is ' not ' equal to ' the current URL, we Push the ' current URL ' onto the top of the stack, Otherwise we do nothing.

Before we use the Peek method, we-determine whether the Stack is empty. Recall from the previous section, ' Working with the queue Class, ' using the ' Peek method ' on a empty Queue would raise an in Validoperationexception exception. This is the "same case" with the Stack class; Therefore, on line, we-check to ensure, ' at least one element are in the Stack before using the ' Peek method.

Two useful utility asp.net pages, have been created to provide some extra functionality for our navigation stack. The fist page, ClearStackHistory.Csharp.aspx, erases the contents of the history stack and are presented in Listing. The second page, Back.Csharp.aspx, serves like a back button in the user's browser, taking him to the previously visited P Age. The code for Back.Csharp.aspx are given in Listing 2.1.7. We ' ll examine these two code listings momentarily.

Listing 2.1.5 also contains a link to another ASP.net page, listing2.1.5.b.aspx. This page is identical to listing2.1.5.aspx. In your Web site, your would need to, at a minimum, include the code in Listing 2.1.5 in each asp.net page to correctly kee P The navigation history up-to-date.

Listing 2.1.6 ClearStackHistory.CSharp.aspx Erases the Contents of the navigation Stack
1: <script language= "C #" runat= "Server" >
2:
3:void Page_Load (Object sender, EventArgs e)
4: {
5://If we have a stack created or not:
6:if (session["History"] = = null)
7: {
8://There ' s no Stack, so we don ' t need to do anything!
9:} else {
All://We need to clear the stack
One: ((Stack) session["History"]). Clear ();
12:}
13:}
14:
: </script>
16:
: : <body>
19:your navigation history has been cleared!
</body>
Listing 2.1.6 contains the code for ClearStackHistory.CSharp.aspx. This code only has a single task-clear the contents of navigation history Stack-and therefore is fairly straightforwar D. The ASP.net page starts by checking to determine if session[' History '] refers to a Stack object instance (line 6). If it does, the clear method was used to erase all stack ' s elements (line 11).

The code for the second utility page, Back.CSharp.aspx, can is seen in Listing 2.1.7.

Listing 2.1.7 Back.CSharp.aspx sends the User to the Previous Page in his navigation Stack
1: <script language= "C #" runat= "Server" >
2:void Page_Load (Object sender, EventArgs e)
3: {
4://If we have a stack created or not:
5:if (session["History"] = = NULL | |
6: ((Stack) session["History"]). Count < 2)
7: {
8://There ' s no Stack, so we can ' t go back!
9:response.write ("Egad, I can ' t go back!");
} else {
One://We need to go prev. page
((Stack) session["History"]). Pop ();
13:response.redirect ((Stack) session["History"). Pop (). ToString ());
14:}
15:}
: </script>
As with ClearStackHistory.CSharp.aspx, Back.CSharp.aspx starts by checking to determine if session[' History ' is null. If is the case, a warning message is displayed because we can ' t possibly step back through our navigation history STA ck if it doesn ' t exist!

Take a moment to briefly look over Listing 2.1.5 again. Note this on each page we visit and we add the current URL to the stack. Therefore, if we want the previous page, we can ' t just pluck off the top element from the stack (because tha T contains the current URL). Rather, we must pluck off the Top-most item, dispose of it, and then visit the "next item" on the top of the stack. For this reason, our stack must have in least two elements to is able to traverse back to the previous page. On line 6, we check to make sure this navigation history stack contains at least two.

Given so we have a properly defined navigation history stack-that is, session["history"] are not null and there are at Le AST two elements in the stack-we would reach lines and which the actual of work of IOUs page. Line simply disposes of the top-most Stack element; Line uses the ' Redirect method of the ' Response object to send the ' user to ' next element at the top of the stack.

That's wraps up our examination of the navigation history stack example. The code samples spanned three listings:listing 2.1.5, Listing 2.1.6, and Listing 2.1.7. If you are decide to use this code on the your Web site, there are a couple of things to keep in mind:

Because our implementation of the navigation history stack are a code snippet in a asp.net page, the code in Listin G 2.1.5 would need to appear into every Web page on your site. This, the course, is a ridiculous requirement; It would make sense to encapsulate the code and functionality into a user control to allow for easy code reuse. (For more information in user controls, refer to Chapter 5, "Creating and Using User controls.")

Second, remember to Back.CSharp.aspx we are popping off the top two URLs. Because Pop removes these elements to the stack altogether, the navigation history Stack cannot contain any sort of forw ARD link.

Similarities among the Collection Types
Because each collection has the same basic functionality-to serve as a variable-sized storage medium for objects-it are not Surprising that's collection types have much in common with one another. All have methods to add and remove elements from the collection. The Count property, which returns the total number of elements in the collection, are common among all collection types.

Each collection also has a means to iterate through each element. This can is accomplished in VB using a For Each ... Next loop or, in C #, a Foreach loop, as follows:

' With VB, use a For each ... Next Loop
Dim qtasks as queue = New Queue ()

' ... Populate the Queue ...

Dim S as String
For each s in Qtasks
' s represents the current element in Qtasks
Response.Write (S + "<br>")
Next


In C #, a foreach construct can is used to iterate
Through each element
Queue qtasks = new Queue ();

// ... Populate the Queue ...

foreach (String s in qtasks)
{
s represents the current element in Qtasks
Response.Write (S + "<br>");
}
Although each collection can is iterated via a for each ... Next or Foreach loop, each collection can also have it elements iterated with a enumerator. Enumerators are small classes that provide a simple functionality:to serve as a (read-only) cursor to allow the developer To step through the elements of a collection.

The. NET Framework provides a number of specific enumerators for specific collection types. For example,the Idictionaryelement Enumerator are useful for iterating through a Hashtable. The IList enumerator is handy for stepping through the elements of a ArrayList. All of these specialized enumerators are derived from a base enumerator interface, IEnumerator. Because of this fact, the collection types can is iterated via the IEnumerator enumerator as.

Because an enumerator ' s most basic purpose are to serve as a cursor for a collection, the IEnumerator class contains only a The ' returns ' collection to which the ' enumerator is currently pointing. (more specialized enumerators, such as Idictionaryelement, contain multiple properties.) IEnumerator contains just two methods:movenext, which advances the enumerator to the next element in the collection, and Reset, which returns the enumerator to its starting position-the position immediately before the "I" in the Coll Ection.

Listing 2.1.8 contains a simple asp.net page This illustrates iteration through both an ArrayList and Hashtable with the I Enumerator Enumerator. The output is shown in Figure 2.6.

Listing 2.1.8 to step through each Element of a Collection, a enumerator Can is Used
1: <script language= "VB" runat= "Server" >
2:
3:sub Page_Load (sender as Object, E as EventArgs)
4: ' Create some collections
5:dim aTeam1 as New ArrayList (), _
6:ateam2 as New ArrayList (), _
7:ateam3 as New ArrayList ()
8:
9:dim htprojects as New Hashtable ()
10:
One: ' Assign memebers to the various teams
12:ateam1.add ("Scott")
13:ateam1.add ("Rob")
14:ateam1.add ("Chris")
15:
16:ateam2.add ("Doug")
17:ateam2.add ("Don")
18:
19:ateam3.add ("Billy")
20:ateam3.add ("Mark")
21:ateam3.add ("Charles")
22:ateam3.add ("Steve")
23:
24:
: ' Add to the htprojects HashTable
26:htprojects.add ("prototyping", aTeam1)
27:htprojects.add ("coding", ATEAM2)
28:htprojects.add ("Testing", ATEAM3)
29:
: ' Now, list each project
31:dim enumprojects as IEnumerator = Htprojects.getenumerator ()
32:do while Enumprojects.movenext ()
33:lblprojectlisting.text &= EnumProjects.Current.Key & "<br>"
34:loop
35:
"Now list,"
37:dim Enumteam as IEnumerator
38:enumprojects.reset ()
39:do while Enumprojects.movenext ()
40:lbldetailedlisting.text &= "<b>" & EnumProjects.Current.Key
& ":</b><ul>"
41:
42:enumteam = EnumProjects.Current.Value.GetEnumerator ()
43:do while Enumteam.movenext ()
44:lbldetailedlisting.text &= enumteam.current & "<br>"
45:loop
46:
47:lbldetailedlisting.text &= "</ul><p>"
48:loop
49:end Sub
50:
Wuyi: </script>
52:
: Si: <body>
55:
A: <font size=+1><b><u>project listing:</u></b></font><br>
<asp:label runat= "Server" id= "lblprojectlisting"/>
: <p>
59:
<font size=+1><b><u>detailed Project listing</u>:</b></font><br>
<asp:label runat= "Server" id= "lbldetailedlisting"/>
62:
: </body>
:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.