Tuesday, January 5, 2010

Working with Hashtable using QTP DOT Net Factory

Hashtable is similar to a Dictionary object. It stores values in key-item pairs. Hashtable can be implemented in QTP using DOT Net factory with .net framework mscorlib assembly.

The below line creates an instance of the Hashtable.

Set oHash=DotNetFactory.CreateInstance("System.Collections.Hashtable","mscorlib")

Now we are ready to work with Hashtable methods and properties in QTP.


Adding an element:
Syntax: Object.Add key, value

Example:
Set oHash=DotNetFactory.CreateInstance("System.Collections.Hashtable","mscorlib")
oHash.Add 1,"QTP"


Removing all elements:
Syntax: Object.Clear
Example: oHash.Clear
'This line clears all the elements in the Hashtable object

Counting Property:
The count property returns number of items in the hastable.
Msgbox oHash.Count


For more information about Hashtable, please navigate the below links,
http://msdn.microsoft.com/en-us/library/4yh14awz(VS.80).aspx
http://en.wikipedia.org/wiki/Hash_table
http://www.itl.nist.gov/div897/sqg/dads/HTML/hashtab.html

4 comments:

  1. Hey Asiq, The tricks are really useful. great job!!!!
    Jesna

    ReplyDelete
  2. Asiq:

    Two questions:
    Why did you include mscorlib in the set statement? It is not required for add, containsKey, containsValue or clear.
    How can the keys be printed?

    Parke

    ReplyDelete
  3. Asiq, got the following to work:

    Set myHash = DotnetFactory.CreateInstance("System.Collections.Hashtable")
    Set myEnumerator = DotnetFactory.CreateInstance("System.Collections.IDictionaryEnumerator")

    ' create the hash
    myHash.add "a", "apple"
    myHash.add "o", "orange"
    myHash.add "r","red"
    myHash.add "b", "blue"

    Set myEnumerator = myHash.getEnumerator

    ' using contains returns true or false
    print "contains B " & myHash.Contains("B")
    print "contains b " & myHash.Contains("b")
    ' can check if a value is somewhere in the hashtable
    print "hash contains value red " & myHash.ContainsValue("red")
    print "value for o = " & myHash.Item("o")
    print "number of keys = " & myHash.count

    ' print the keys and values
    While myEnumerator.movenext
    print "key " &myEnumerator.Key & ":: value " & myenumerator.value
    Wend

    Parke

    ReplyDelete