Scripting.Dictionary objects

Source: Internet
Author: User
Tags array arrays comparison count empty error handling reference
Object


Many Microsoft programming languages, such as Visual Basic, VBScript, and JScript, provide collections (collection). You can think of a set as an array, and you can use the built-in functions to accomplish basic tasks such as storing and manipulating data. There is no need to worry about the ranks of the data, but access using unique keys.
Both VBScript and JScript provide similar objects, commonly known as scripting.dictionary objects or Dictionary objects. It is similar to a two-dimensional array, where the data for the key and related entries are stored together. However, the real object-oriented approach should not directly access data entries, it must be implemented using the methods and properties supported by the Dictionary object.
This chapter provides sample pages that allow you to test the methods and properties of the script Runtime object. These instances are in the CHAPER05 subdirectory of the file of the downloaded file.

5.3.1 Create and use Dictionary objects
An example of creating a Dictionary object is as follows:
' In VBScript:
Dim Objmydata
Set objmydata = Server.CreateObject ("Scripting.Dictionary")

In Jscript:
var objmydata = Server.CreateObject (' scripting.dictionary ');

<!--server-side with an OBJECT element-->
<object runat= "SERVER" scope= "PAGE" id= "Objmydata"
Progid= "Scripting.Dictionary" >
</OBJECT>
The Dictionary object can also be used in the client's ie.
1. Overview of the members of the Dictionary object
Table 5-2 and Table 5-3 list the properties and methods of the Dictionary object and the corresponding description.
An error occurs when a key/entry pair is added, if the key already exists, or when a key/entry pair is deleted, the keyword/entry pair does not exist, or the CompareMode of the Dictionary object that already contains the data is changed.
Table 5-2 Properties and descriptions of Dictionary objects
Attribute description
CompareMode (VBScript only) Sets or returns a string comparison pattern for a key
Count is read-only. Returns the number of key/entry pairs in dictionary
Item (key) Sets or returns the entry value of the specified key
Key (key) Set value
Table 5-3 methods and descriptions of Dictionary objects
Method description
Add (Key,item) add key/entry to Dictionary
Exists (Key) returns TRUE if the specified key exists, otherwise returns false
Items () returns an array containing all the entries in the Dictionary object
Keys () returns an array containing all the keys in the Dictionary object
Remove (key) deletes a specified key/entry pair
RemoveAll () Delete all keys/entries to
2. Add and remove entries to dictionary
Once you get a new (empty) Dictionary, you can add entries to it, get the entry from it, and delete the entry:
' In VBScript:
Objmydata.add "MyKey", "myitem" ' Add Value myitem with key MyKey
Objmydata.add "Yourkey", "Youritem" ' ADD value Youritem with key Yourkey
Blnisthere = objmydata.exists ("MyKey") ' Returns True because the item Exists
Stritem = Objmydata.item ("Yourkey") ' Retrieve value of Yourkey
Stritem = Objmydata.remove ("MyKey") ' Retrieve and Remove Yourkey
Objmydata.removeall ' Remove all the items
In JScript, the equivalent code is:
In JScript;
Objmydata.add (' MyKey ', ' myitem '); ADD Value myitem with key MyKey
Objmydata.add (' Yourkey ', ' Youritem '); ADD value Youritem with key Yourkey
var blnisthere = objmydata.exists (' MyKey '); Returns True because the item exists
var stritem = Objmydata.item (' Yourkey '); Retrieve Value of Yourkey
var stritem = objmydata.remove (' MyKey '); Retrieve and remove Yourkey
Objmydata.removeall (); Remove all the items
3. Modify the value of a key or entry
You can change the data stored in the dictionary by modifying the value of the key or by modifying the data of the entry that is associated with a particular key. The following code changes the data in an entry that has a key of MyKey.
Objmydata.item ("MyKey") = "NewValue" in VBScript
Objmydata.item (' MyKey ') = ' newvalue '; In JScript
If the specified key is not found in dictionary, a new key/entry pair is created in dictionary with the MyKey as the key and the entry value of new value. Interestingly, if you use a nonexistent key to retrieve an entry, you not only get an empty string (which is conceivable), but also add a new key/entry pair in the dictionary, the key is the specified key, but the entry's data is empty.
You can use the key property to change only the value of the key without changing the data for the entry that corresponds to it. To change an existing key MyKey to Mynewkey, you can use:
Objmydata.key ("MyKey") = "Mynewvalue" in VBScript
Objmydata.item (' MyKey ') = ' mynewvalue '; In JScript
If the specified key is not found, a run-time error is generated.
4. Set comparison mode
The Dictionary CompareMode property is only available in VBScript and cannot be used in JScript. Allows you to specify how comparisons are compared when you compare string keys. Two allowable values are Binarycompare (0) and Textcompare (1). Binarycompare (0) is the binary number control (that is, case-sensitive); Textcompare (1) is text-controlled (that is, case-insensitive).
5. Traverse Dictionary
When studying dictionary, there are two methods and an attribute that require special attention, which allows us to traverse all key/entry pairs stored in the dictionary. The items method returns all the entry data in the dictionary in the form of a one-dimensional array, and the keys method returns all existing key values with a one-dimensional array. You can use the Count property to get the number of keys or entries.
For example, you can use the following code to get all the key and entry values in the dictionary named Objmydata. Note that although the Count property holds the number of keys/entries in dictionary, the array of VBScript and JScript always starts with subscript 0. Therefore, the array subscript should be from 0 to Count-1.
' In VBScript:
Arrkeys = Objmydata.keys ' Get all of the Keys into an array
Arritems = Objmydata.items ' Get all of the Items into an array

For intloop = 0 to objmydata.count–1 ' iterate through the array
Strthiskey = Arrkeys (intloop) ' This is the key value
Strthisitem = Arritems (intloop) ' This is the item (data) value
Next

In JScript
Get Vb-style arrays using the Keys () and Items () methods
var Arrkeys = new VBArray (Objmydata.keys ()). ToArray ();
var arritems = new VBArray (Objmydata.items ()). ToArray ();

for (intloop = 0; intloop < Objmydata.count; intloop++) {
Iterate through the arrays
Strthiskey = Arrkeys[intloop]; This is the key value
Strthisitem = Arritems[intloop]; This is the item (data) value
}
In VBScript you can also use for each ... The next statement completes the same function:
' Iterate the dictionary as a collection in VBScript
For each objitem in Arritems
Response.Write Objitem & "=" & Arritems (objitem) & "<BR>"
Next
5.3.2 Dictionary Object Example
This book provides a series of sample files that can be used to test the various properties of the script Run-time library.
The default page of this chapter Code provides a series of examples of VBScript links that you can use. Some examples are also valid for JScript. These samples are stored in the corresponding subdirectories in the Chapter05 directory, and the displayed interface is shown in Figure 5-2:

To see the Dictionary object running, click on the first link on the menu page to open the page called show_dictionary.asp. This page shows the content of the Dictionary object we provide, allowing you to experiment with its properties and methods. The screen looks like figure 5-3:

1. Dictionary's Global.asa file
One of the files provided with the Dictionary Object sample page is Global.asa. It creates and populates the Dictionary object of a session-level scope, so its contents are not lost between page requests. Generally (considering scalability), this is not an ideal practice. In this example, you can see the effects of Dictionary's properties and methods.
If you download and install the sample on your own server, you must create a virtual application that is based on this global.asa file. or add its contents to the Global.asa file in the root folder of the default site. The 3rd chapter describes how to create a virtual application with a wizard. For this example, however, the easiest way to create a virtual application is to right-click the dictionary subfolder in the Chapter05 sample folder, and in the Properties dialog box's Home Directory tab, click the Create button, as shown in Figure 5-4:

In this global.asa file, the code creates a Scripting.Dictionary object instance of the session-level scope using the <OBJECT> element. It then puts a series of values into the dictionary in the Session_OnStart event handler and assigns a reference to the Dictionary object to the ASP session variable MyDictionary:
<object id= "objbooklist" runat= "SERVER" scope= "Session"
Progid= "Scripting.Dictionary" >
</OBJECT>

<script language= "VBScript" runat= "SERVER" >

Sub Session_OnStart ()
Objbooklist.add "2610", "Professional Active Server Pages 3.0"
Objbooklist.add "1274", "Instant JavaScript"
Objbooklist.add "2882", "beginning ASP components"
Objbooklist.add "1797", "Professional ASP techniques"
Objbooklist.add "1835", "AD0 2.0 Programmer ' s Reference"
Set session ("mydictionary") = Objbooklist
End Sub

</SCRIPT>
2. Dictionary Sample page
In the Scripting.Dictionary Object home page, the first task is to get a reference to the Dictionary object instance of the session-level scope. Note that this reference is an object variable, so you must use the SET keyword in VBScript.
Then, check to see if you got an object (this is a good habit), and if you don't have a virtual application that contains the Global.asa file correctly, check out where the problem is. You will see our own message instead of the ASP's error message (but note that the default error handling must be turned off for this operation).
<%

On Error Resume Next ' turn out error handling to test if object exists

' Retrieve Dictionary object from user ' s session
Set Objmydata = Session ("MyDictionary")

If IsObject (objmydata) Then ' found Dictionary object in session
...
%>

<p><div class= "Subhead" >iterating the Dictionary with arrays</div>
<%
Arrkeysarray = Objmydata.keys ' Get all of the Keys into an array
Arritemsarray = Objmydata.items ' Get all of the Items into an array
For intloop = 0 to Objmydata.count-1 ' iterate through the array
Response.Write "Key: <B>" & Arrkeysarray (intloop) & "</B> Value: <B>" _
& Arritemsarray (intloop) & "</B><BR>"
Next
%>
...
... Other code and controls go ...
...
<%
Else

' Could not find Dictionary object in the session
Response.Write "Dictionary Object not available in Global.asa for session"

End If
%>
The list of dictionary content displayed on the page is a two array created using the key and items methods of the Dictionary object, which can be traversed using the preceding code.
3. Dictionary page Control
Under Dictionary's list of contents is a series of HTML controls that can be used to set certain properties of the Dictionary object and to perform various methods. The controls are all within a <FORM>, and the Action property value is this page, so the contents of the form are submitted back to this page. The same technique is used in the examples in the previous chapter.
In <FORM>, changing a property or executing a method is achieved by a button (without a caption). The values for properties and methods are placed in the text box or list box next to the button.
The first button on the page is used to set the key property of the entry in the dictionary. A drop-down list is used to select a key value that already exists. The following code creates a control for that part of the page. To populate the list, another technique is used to traverse the Dictionary object, i.e. Next statement. The code is as follows:
...
<form action= "<% = Request.ServerVariables (" Script_name ")%>" method= "POST >

<p><div class= "subhead" >the Dictionary properties</div>
<input type= "SUBMIT" name= "Cmdchangekey" "value=" ">
Dictionary.key ("
<select name= "Lstchangekey" size= "1" >
<%
For each objitem in Objmydata
Response.Write "<OPTION>" & Objitem
Next
%>
</SELECT> ") ="
<input type= "TEXT" name= "Txtchangekey" size= "value=" "New Key NAME" > "
<BR>
...
... Controls go ...
...
</FORM>
...
4. Properties and methods that use dictionary
On the Scription.dictionary Object page, click the button that checks for and changes the key property of the entry, as shown in Figure 5-5:

Submit the form to the page again. The page contains a script segment that checks the value of the clicked button. It determines which button is clicked by looking up the name of the button in the Resquest.form collection. If you find a value that corresponds to Cmdchangkey, you get the corresponding value from the list or text box and use it to change the key property:
...
' Look for a command sent ' FORM section buttons
If Len (Request.Form ("Cmdchangekey")) Then
Strkeyname = Request.Form ("Lstchangekey") ' Existing Key from list box
Strnewkey = Request.Form ("Txtchangekey") ' New key value from text box
Objmydata.key (strkeyname) = Strnewkey ' Set Key property of this item
End If
...
After the page is loaded, the corresponding results are seen in the dictionary list of contents, as shown in Figure 5-6:

The rest of the code on the page is used to set the Item property of an entry, or to execute the Dictionary object's method. The following are the code for these operations, and each piece of code is very similar to the code that demonstrates the key property. Each time the results are displayed in the dictionary List of contents:
...
If Len (Request.Form ("Cmdchangeitem")) Then
Strkeyname = Request.Form ("Lstchangeitem") ' Existing Key from list box
Strnewvalue = Request.Form ("Txtchangeitem") ' New item value from text box
Objmydata.item (strkeyname) = Strnewvalue ' Set the Item property
End If

If Len (Request.Form ("Cmdadd")) Then
Strkeyname = Request.Form ("Txtaddkey") ' New key value from text box
Stritemvalue = Request.Form ("Txtadditem") ' New item value from text box
Objmydata.add strkeyname, Stritemvalue ' Execute the Add method
End If

If Len (Request.Form ("Cmdremove")) Then
Strkeyname = Request.Form ("Lstremove") ' Existion Key from list box
Objmydata.remove strkeyname ' Execute the Remove method
End If

If Len (Request.Form ("Cmdremoveall")) Then
Objmydata.removeall ' Execute The RemoveAll method
End If
...
For example, if you click the Add Method button now, a new entry will be added to the dictionary content list, as shown in Figure 5-7:

The result is as shown in Figure 5-8:

You can experiment with the properties and methods of Dictionary objects in this page, and you will find out what factors and in what circumstances can cause Dictionary object errors. For example, try adding an entry with the same key value as an existing entry to see what happens.




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.