Friday, January 25, 2013

Amazing People Compilation - Amazing skill and Talent in HD 2012


AMAZING PEOPLE (25 MIN LONG COMPILATION)


PEOPLE ARE AWESOME 2013


Database operation in QTP (borrowed from http://www.qtpschool.com)

DataBase_Connection() creates a new connection to a database.
There are two arguments passed to this function -
1. sessionName - the name of the session (string)
2. connection_string - a connection string, for example the connection_string can be "DSN=SQLServer_Source;UID=SA;PWD=xyz123". Please note that the connection string will vary as per your database details.

Con = <name of the session>
SQL="SELECT * FROM Your_Table"
con_string="DSN=SQLServer_Source;UID=SA;PWD=xyz123"

isConnected = DataBase_Connection (Con , con_string)
'Now check if connection is successful. Function will return zero if connection is successful.
If isConnected = 0 then
    'Execute your SQL statement
    set myrs = Con.Execute(SQL)


    'Retrieve values from the recordset
    print "val - row 0 col 0: " & db_get_field_value( myrs , 0 , 0 )
    print "val - row 0 col 1: " & db_get_field_value( myrs , 0 , 1 )
End If


Con.close
Set Con = Nothing 'Disconnect database

'-----------------------------------------------------------------------------------------------
Function DataBase_Connection(sessionName,connection_string)
    Dim oConnection
    on error Resume next
    ' Opening connection
    set oConnection = CreateObject("ADODB.Connection")


    If Err.Number <> 0 then
        DataBase_Connection= "Error :- " & CStr(Err.Number) & " " & Err.Description
        Err.clear
        Exit Function
    End If
 
    oConnection.Open connection_string
oConnection.CommandTimeout = 120  'modify this value if needed. 
    If Err.Number <> 0 then
        DataBase_Connection= "Error := " & CStr(Err.Number) & " " & Err.Description
        err.clear
        Exit Function
    End If
    set sessionName = oConnection
    DataBase_Connection = 0
End Function


We need another function to retrieve data from record set.

Function db_get_field_value( myrs , rowNum, colNum )
    dim curRow

    myrs.MoveFirst
    count_fields = myrs.fields.count-1
    If ( TypeName(colNum)<> "String" ) and ( count_fields < colNum ) then
        db_get_field_value = -1 'requested field index more than exists in recordset
    Else
        myrs.Move rowNum
        db_get_field_value = myrs.fields(colNum).Value
    End If
End Function


Connecting QC with QTP using scripting (borrowed from http://jiteshsojitra.blogspot.in/)

Connecting QC with QTP using scripting (borrowed from http://jiteshsojitra.blogspot.in/)


Set qtApp = CreateObject("QuickTest.Application")
qtApp.Launch
qtApp.Visible = True
qtApp.TDConnection. Connect "URL", "DOMAIN", "PROJECT", "USERNAME", "PASSWORD", False

'Further code here

qtApp .Disconnect
qtApp .Logout
Set qtApp =nothing

Mercury Timer -- Code from (http://jiteshsojitra.blogspot.in/)

Mercury Timer -- Code from (http://jiteshsojitra.blogspot.in/)

StartTime = MercuryTimers("Timer").Start / 1000
' Operation 1
' Operation 2
EndTime = MercuryTimers("Timer").Stop() / 1000
TotalTime = EndTime - StartTime
Msgbox ""&TotalTime

Retrieving Test Case name from QC

Retrieving Test Case name from QC


Set td=createobject("TDApiOle80.TDConnection")
td.InitConnectionEx "http://Link/qcbin"
td.ConnectProjectEx "DOMAIN", "PROJECT","USERNAME", "PASSWORD"

Set tstMgr = td.TreeManager
Set tsttr = tstMgr.NodeByPath("Path")
Set tsetFact = tsttr.TestFactory
Set tsetList = tsetFact.NewList("")

For Each tset in tsetList
   Msgbox ("Test Name = " & tset.Name)
Next

td.Disconnect
td.logout
set td=nothing

Thursday, January 24, 2013

VB Script VS SQL Query


VBS
SQL
Mid
  msgbox mid(“string”,3,4)
Substr
select substr(‘string’,3,4)
        From dual
          /
Replace
msgbox replace(“I’m”,”’”,” “)
Replace
Len
Length
Lcase
Ucase
Lower
Upper
“ string”
‘string’
“”
‘---null
Null
Date
Sysdate
Now
Systimestamp
Strreverse(“string”)
Reverse(“string”)
5 mod 2
Mod(5,2)
Instr(1,”string”,”i”)
Instr(‘string’,’i’,1)
“a”&”b”
‘a’||’b’

Creating Dictionary in VBS

Simple example to show the usage of Dictionary in VBS

Set hash = CreateObject ("Scripting.Dictionary")
hash.add "A", "Apple" 'Inserting values into dictionary
hash.add "B", "Ball"  'Inserting valuesinto Dictionary

hash.item("b") = "Note Dictionary is Case Sensitive" 'The dictionary's "item" method can be used to do the same job as "add "

'hash.CompareMode = 1
'This must be places immediately after the CreateObject statement and before any items are added.
'If that's done then the keys will no longer be case sensitive.
msgbox "A for "& hash.item("A")

keys = hash.Keys   'Keys - returns an array containing the key words
items = hash.Items 'Items - returns an array containing the values
for i = 0 to hash.Count - 1
 msgbox Keys(i) & " for  " & Items(i)
next

hash.Remove("A") 'To remove individual values from dictionary
hash.RemoveAll   'To remove all values into Dictionary

Wednesday, January 23, 2013

Running Test Cases in QC using QTP

Sometimes it might be required to match the data provided say in an excel with Test case name as in QC while running Automated Test Cases using QTP.Then QTP allows user to create QTP object inside QTP and killing of QTP object or deallocation of QTP object will not affect currently opened QTP.

Function tc_check(TCName)
Set oQTP=createobject("quicktest.application")
QC_Loc=oQTP.Test.Location
bStatus=instr(1,lCase(QC_Loc),trim(lcase(TCName) ) )
if bStatus>0 then
msgbox "matching TC found"
else
msgbox "TC does not match"
end if
oQTP=nothing
End Function

Clean Up for QTP

Sometimes there is a need to kill applications initially which might hamper the current work in hand , every time you run your automation script .

This piece of code in QTP might be helpful :-

SystemUtil.CloseProcessByName "Application Name as in Task Manager.Extension"

Monday, January 21, 2013

Script to Run Multiple test sets in Test Lab of QC via QTP

Vb Script to Run MultipleTest Sets in Test Lab of Quality Center via QTP

'All the test sets should reside inside single parent folder

''To execute the this file enter the below line into commond prompt
     'C:\Windows\SysWOW64\cscript.exe "C:\Path of this file.vbs"

Dim aSet_name
Dim iCount
Dim QCConnection
Set QCConnection = CreateObject("TDApiOle80.TDConnection")
'---------------------------------------------------------------------------------------------------------------

QCConnection.InitConnectionEx "http://server address/qcbin"  '<--------------- Fill in server address
     
QCConnection.login "Username ", "Password"   '<---------------- QC Username and Password

QCConnection.Connect "QC Domain", "Qc Project"   '<---------------- FILL Domain/Project
nPath ="Root\Test1\Path"               '<----------------Parent Path 
aSet_name=array("TestSet1","TestSet2","TestSetn")   '<-------Test Set names
'-----------------------------------------------------------------------------------------------------------------

Set TSetFact = QCConnection.TestSetFactory
Set tsTreeMgr = QCConnection.TestSetTreeManager
Set tsFolder = tsTreeMgr.NodeByPath(nPath)

If tsFolder Is Nothing Then
 'msgbox "error"
 wscript.echo "error"
 Call QC_Disconnect()
End If

for iCount=0 to ubound(aSet_name)
 Set tsList = tsFolder.FindTestSets( aSet_name(iCount) )

 If tsList.Count > 1 Then

  'MsgBox "FindTestSets found more than one test set: refine search"
  wscript.echo "FindTestSets found more than one test set: refine search"

 ElseIf tsList.Count <> 1 then
  'MsgBox "FindTestSets: test set not found"
  wscript.echo  "FindTestSets: test set not found"
 else
        'End If

  Set theTestSet = tsList.Item(1)
  Set Scheduler = theTestSet.StartExecution("")
  Scheduler.RunAllLocally = True
  Scheduler.HostTimeOut = 100000  'The time to wait for response before  failing.
  Scheduler.run
  Set execStatus = Scheduler.ExecutionStatus
  RunFinished = False

  while RunFinished = False
   execStatus.RefreshExecStatusInfo "all", True
   RunFinished = execStatus.Finished
  wend

  wscript.echo "Completed Execution of Test Set "&aSet_name(iCount)
 end if
next


Call QC_Disconnect()
'-----------------------------------------------------
Function QC_Disconnect()
 QCConnection.Disconnect
 QCConnection.Logout
 Set QCConnection = Nothing
End Function

Converting Decimal to Whole Number 2 methods : -

1)

x=inputbox("enter a number with decimal")
whole=mid(x,1,instr(1,x,".")-1)
deci=mid(x,instr(1,x,".")+1,len(x))
if mid(deci,1,1) >=5 then whole=whole+1
msgbox whole


2)

x=inputbox("enter a decimal no with 1 digit after the decimal point")
whole=x*10
deci=whole mod 10
whole=whole-deci
whole=whole/10
if deci>=5 then
  whole=whole+1
end if
msgbox whole

Excel Creation using VBS

Example


set xl=createobject("excel.application")
sPath=InputBox("enter path where you want to save the file")

set wb=xl.workbooks.Add
Set ws=wb.worksheets(1) 'sheetname
ws.Name="New Name"

ws.cells(1,1).value="Completed creation of new excel file"

wb.saveas (sPath)
wb.close
xl.quit
Set xl=nothing

Text File Operations in Vbs

Example :

Dim sPath
set fso=createobject("scripting.filesystemobject")
sPath=inputbox("enter path where you want to save the file")

fso.createtextfile sPath
set ctrl=fso.getfile("1.txt")
set mode=ctrl.openastextstream(8)
'1-read
'2-write
'8-append
mode.writeline "hi"
mode.writeblanklines 5
mode.writeline "end"
msgbox "over"
set fso=nothing

Sorting using built in Function

Example :

set a =createobject("system.collections.arraylist")
a.add "5"
a.add "1"
a.add "2"
a.sort
for each i in a
 b=b&i&vbnewline
next
msgbox b

Vb Script --Regular Expression EXAMPLES

1)To validate any website address starting from --www

set regex=new regexp
regex.pattern="www\..*\.(com|in|jp)$"
n=inputbox("validate any website address starting from --www")
if regex.test(n) then
 msgbox "valid"
else
 msgbox "invalid"
End if

2) Replace all matches in the string with the replacement text

Sub ReplaceAllByExpression(ByRef StringToExtract, ByVal MatchPattern, _ByVal ReplacementText)

 Dim regEx, CurrentMatch, CurrentMatches
 Set regEx = New RegExp
 regEx.Pattern = MatchPattern
 regEx.IgnoreCase = True
 regEx.Global = True
 regEx.MultiLine = True
 StringToExtract = regEx.Replace(StringToExtract, ReplacementText)
 Set regEx = Nothing

End Sub

' Example
' Remove all images from an HTML page
ReplaceAllByExpression HTMLPageData, "<img[^<]*?>", ""

The RexExp Object


The RegExp object has three properties and three methods. The properties are:
  1. Pattern property - holds the regular expression pattern
  2. Global property - True or False (default False). If False, matching stops at first match.
  3. IgnoreCase property - True or False (default True). If True, allows case-insensitive matching
The methods are:
  1. Execute method - executes a match against the specified string. Returns a Matches collection, which contains a Match object for each match. The Match object can also contain a SubMatches collection
  2. Replace method - replaces the part of the string found in a match with another string
  3. Test method - executes an attempted match and returns True or False

To set up a RegExp object:

Dim re
Set re = New RegExp
With re
    .Pattern = "some_pattern"
    .Global = True
    .IgnoreCase = True
End With

A Pattern can be any string value.
 For example, if the pattern is "Hello World", the RegExp object will match that in the target string.
If IgnoreCase is True, it will match any case, so "hellO wORld" would be matched.

If Global is set to True, it will contine to search the string for all instances of "Hello World". If False, it will stop searching after the first instance is found.

Execute method, returning Matches collection

Dim re, targetString, colMatch, objMatch
Set re = New RegExp
With re
  .Pattern = "a"
  .Global = True
  .IgnoreCase = True
End With
targetString = "The rain in Spain falls mainly in the plain"

Set colMatch = re.Execute(targetString)
For each objMatch  in colMatch
  Response.Write objMatch.Value & "<br />"
Next


The above will produce a list of 5 letter a's.


Test method, returning True or False

Dim re, targetString
Set re = New RegExp
With re
  .Pattern = "a"
  .Global = False
  .IgnoreCase = False
End With
targetString = "The rain in Spain falls mainly in the plain"

re.Test(targetString)

Thursday, January 17, 2013

Error handling in QTP (Using Codes)

On error Statements

Following are error statements :
1. On Error Resume Next
2. On Error Go to 0
3. err Object

4. Reporter.RunStatus
5.Reporter.ReportNote

1.On Error Resume Next:
On Error Resume Next statement enables the Error handling in the code.If there is error in the code "On error Resume Next" ignores it and continue with next line of code.

2.On Error Go to 0:
On error got to 0 statement disables error handling we have previiously enabled it by using On Error resume Next.

3.err.number and err.description:
Provides the error number and the description of the error

Err Object  has following methods :=
 a) Err.Raise
    ex: Err.Raise 6

b)Err.Clear

c)Err.Number

 lines of code which would raise the error :-
If err.number <> 0 ' which means that some error has occurred
msgbox err.description

your code logic if no error occurs :-on error goto 0 ' this stops your error handling code

Extract Error No:
msgbox Err.number

Example :
If Err.Number <>0 then
     msgbox("Here it prints") 'Because of Err object we can give our own error message
end if

Example:
On Error Resume Next
Err.Raise 8    'raise a user-defined error
Err.Description = "My Error"
Err.Source = "MyAppName"

4.Reporter.RunStatus
example (1) :
If Reporter.RunStatus=micFail then ExitAction

example(2):
If Reporter.RunStatus = 0 then ExitAction

0 or micPass: If this step runs test passes which is shown in test report.
1 or micFail: If this step runs test fails which is shown in test report.
2 or micDone: Used to send message to the test report and does not affect status of test.
3 or micWarning: Again, used to send warning message to the test report and does not affect status of test.

5.Reporter.ReportNote
Reporter.ReportNote ("Testing App Now")
Reporter.ReportNote ("The Results paths of Test Scripts") & vbtab &MyResultsPath

 

Monday, January 14, 2013

Using Class in Vbs

Here is a piece of code which using class in vbs, to add numbers 2 and 3:-


Call a2()

Class a1

             Private Function add2()
                        msgbox 2+3
            End Function

            Function add1()
                        Call add2()
            End Function
End Class

Function a2()
         Set a2=new a1
         a2.add1
End Function

'Save the above code in text file and save as ".vbs"

Keeping Remote Desktop or Physical machine Active

How to keep Remote Desktop or Physical machine active ,without using any 3rd party tools ?

If you are having only limited access to the computer say in your office it is always best to use 3rd party tool mouse or keyboard simulator which does not require any installation to keep the system active.In many cases , due to some policy even 3rd party tool might be restricted during that case you might have write your own script to keep the machine alive.
Below is a small script which keeps the system active i.e., prevent system from logging off by sending keystrokes (caps key in our case).

Dim i
set oWscript=createobject("Wscript.Shell")
i=0
do until i=1
 oWscript.sendkeys "%({NUMLOCK})"
 Wscript.Sleep 1000
 loop

  1. Copy the ablove piece of code in a notepad file and save it as ".vbs"
  2. Once double clicked you can see your NUMLOCK LED light in our keyboard going ON and OFF with a gap of 1sec.
  3. To kill this process open Task manager and kill process "wscript"

Keeping 2 Remote Desktops active

How to keep 2 or more Remote Desktops active ?

When you have 2 machines say 1 for execution ( i.e., running automation scripts and the other to do day to day activity) or you might have access to run automation scripts in few machines , then there is a need to keep all the machine active.

Below is the piece of code which can help you achieve this .

Dim i,sW_count,iTime_delay
set oShell =createobject("Wscript.Shell")
i=0
sW_count=Inputbox("Enter number of windows")
Redim Window_Name(sW_count-1)

For iCount=0 to sW_count-1
 Window_Name(iCount)=inputbox("enter exact name as found in the Title box the window")
Next

iTime_delay=Inputbox("Enter time before next trigger in seconds")   iTime_delay=iTime_delay*1000
For iCount=0 to sW_count-1
 WScript.Sleep(500)
 oShell.AppActivate(Window_Name(iCount))
 WScript.Sleep(500)
 oShell.SendKeys "% x"   'to maximize the window
next

do until i=1
 for iCount=0 to sW_count-1
  oShell.AppActivate(Window_Name(iCount))
  WScript.Sleep(iTime_delay)     
 next 
loop


How to use :
  1.  Copy this piece of code in a text file and save it with an extension as ".vbs".
  2. Double click on the file.
  3. Enter how many windows you wish to keep alive.
  4. Enter the exact names of all the windows as on the title bar of the window E.g:CATCHBUG.blogspot.com - Windows Internet Explorer
  5. Enter after how many seconds you wish to trigger the window in seconds Eg: 120   (This will trigger each window after 120 seconds )
  6. To close this script open task manager kill the "wscript" process. 
Note :
  1. This script should be used in conjunction with any key stroke or mouse simulation tool.
  2. This works only on windows platform.

Prevent Logging off of Remote Desktops

 How to prevent Remote Desktops and physical machine from logging off     

The problem with Remote machines when accessed through citrix is that it tends to log off if the machine is unattended for sometime . As per my research there a few ways to prevent the machine from logging off but the one which I found very convenient was with the use of  a tool called MouseMove .

MouseMove
This application sends mouse simulation at stipulated time interval to prevent the system from logging off. Inorder for the whole procedure to work the mouse simluation should be target towards the remote machine by doing this 2 things can be achieved
  1. Prevents the physical machine from Logging off ( This happens anyways as any mouse activity keeps the physical machine alive )
  2. Prevents the remote machine from loggin off if targeted properly.
Another cool feature is that you can choose the application on which the mouse stimulation can take effect.

Finally this tool is tailored for applications which uses hotkeys during automation run and batch runs.As this tool does not use any keys unless configured at the beginning.Follow the link http://movemouse.codeplex.com/ to download the application and the best part is it is FREE !!