Thursday

QTP - Naming Convention in VBS

Copyright: Roman Koch · Nutzungsbestimmungen · Datenschutz
Source: http://www.romankoch.ch/capslock/vbnaming.htm

Naming Conventions for Visual Basic Scripts

Basic Principles
Compared to Visual Basic and VBA, VBScript is less restrictive in the way it deals with variables and constants. VBScript knows only one basic data type, the Variant, and you can easily use the same variable to store a number and then a string later on. You don't even need to declare your variables. Although this is great for prototyping, I have found that this makes script maintenance difficult, and can become the cause of program errors or strange program behaviours. Therefore, on top of my variable naming conventions, two basic principles always apply:

Enforce declarations. If a VBScript starts with Option Explicit statement, all variables and constants must be explicitly declared, or an error occurs. Option Explicit prevents you from lazy programming.
Never misuse variables. Once you have named a variable to be used for a specific data type, never misuse it for another data type. For example, if you have a variable named iClicks to count the number of clicks, never assign a string to it - even if you know that the variable is currently "unused".
Data Type Prefixes
By using data type prefixes, your variables always indicate what they are designed for. I'm using just six prefixes:

Prefix Data Types Example
b Boolean (true or false) bChecked = True
d Date/time dStartTime = Now
i All numeric data types
(Byte, Integer, Currency, Long, Single, Double) iTax = iPrice * 0.076
o Objects Set oFile = Nothing
s Strings sTitle = "Welcome!"
u User interface elements uPara.style.display = "block"

Constants Prefix
I have found that I usually have only an handful of constants in my scripts. Indicating the data type therefore is less important for constants. I'm using the prefix letter c for all constants, e.g.

Const cTitle = "Welcome!"
uDocument.title = cTitle
Scope of Variables and Constants
Variables and constants can be declared on the script level, meaning they are available to all Sub and Function procedures in a script, or on the procedure level, meaning they are available only to the Sub or Function procedure that contains the declaration. In general, I try to avoid script- level declarations, as it makes long scripts difficult to read. Use script-level declarations only if you really need a variable or constant in multiple procedures - don't do it just to save memory.

For script-level variables and constants, I just double the prefix. sTitle is a procedure-level string variable, while ccPath is a script-level constant.

Best Practices
In addition to the basic principles and naming prefixes, the following best practices help me to avoid run-time errors and to keep my code easy to maintain:

Always pass variable by value. VBScript by default passes variables to functions and procedures by reference, and in most cases, this default is not what you would expect. By explicitly passing variables by value, you can avoid unexpected changes to your variables.

Function GetBetter (ByVal iNumber)
iNumber = iNumber + 1
GetBetter = iNumber
End Function
iRating = 4
iNewRating = GetBetter(iRating)
Initialize variables. VB does not require you to initialize variables and usually behaves consistently when using an uninitialized variable. However, by explicitly initializing variables, I can later on remember how I wanted my script to work when I wrote it. Instead of

Dim iRecords
...
iRecords = iRecords + 1
I prefer to write

Dim iRecords
iRecords = 0
...
iRecords = iRecords + 1
Use conversion functions. For calculations, I rely on the VB subtype conversion functions to document my code. When processing numeric user input, the short and dangerous way of coding is

iRating = uRating.valueI prefer to write

If IsNumeric(uRating.value) Then
iRating = CInt(uRating.value)
Else
...
End If
Use predefined constants. Many objects provide predefined constants for VB and VBA. The FileSystemObject for example provides constants that indicate the opening mode for files. Instead of

Set oLog = oFSO.OpenTextFile(Server.MapPath("log.txt"), 8, True)
I prefer to write

Const fsoForAppending = 8
Set oLog = oFSO.OpenTextFile(Server.MapPath("log.txt"), fsoForAppending, True)
Use short numeric variables for local counters only. Traditional programming uses short numeric variables, especially i and j, as a local buffer. Although they do not conform to my naming conventions, I still use them, but only for local (procedure-level) counters:

Dim i, j
For i = 0 to iRows - 1
For j = 0 to iCells - 1
uTable.rows(i).cells(j).innertext = ""
Next
Next

User Define Function

' Object pass karna jaroori hai
RegisterUserFunc "WebEdit","set", "mthd"

Browser("CASO Dashboard").Page("CASO Dashboard").WebEdit("WebEdit").set "copy"

Function mthd (obj, x)
Msgbox x
'
If x="copy" Then
Msgbox "Hi"
End If

' dim y
'
' y = obj.GetROProperty("value")
'
' Reporter.ReportEvent micDone, "previous value", y
'
' MySet=obj.Set(x)

End Function

UnRegisterUserFunc "WebEdit", "Set"

Wednesday

Adding a Quote in vbs

StringObjMth=ObjectName & "(" & Chr(34) & Method & Chr(34) & ")"


Chr(34) will give value , """ can be mislead.

Monday

URL Encoding %20 means Space + means 2B

URL Encoding
(or: 'What are those "%20" codes in URLs?')
= Index DOT Html by Brian Wilson =
Main Index | Element Index | Element Tree | HTML Support History
RFC 1738 | Which characters must be encoded and why
How to URL encode characters | URL encode a character


Character Code Code
Points Points
(Hex) (Dec)
 Dollar ("$") 24 36
 Ampersand ("&") 26 38
 Plus ("+") 2B 43
 Comma (",") 2C 44
 Forward slash/Virgule ("/") 2F 47
 Colon (":") 3A 58
 Semi-colon (";") 3B 59
 Equals ("=") 3D 61
 Question mark ("?") 3F 63
 'At' symbol ("@") 40 64

Character Code Code Why encode?
Points Points
(Hex) (Dec)
Space 20 32 Significant sequences of spaces may be lost in some uses (especially multiple spaces)
Quotation marks 22 34 These characters are often used to delimit URLs in plain text.
'Less Than' symbol ("<") 3C 60
'Greater Than' symbol (">") 3E 62
'Pound' character ("#") 23 35 This is used in URLs to indicate where a fragment identifier (bookmarks/anchors in HTML) begins.
Percent character ("%") 25 37 This is used to URL encode/escape other characters, so it should itself also be encoded.
Misc. characters: Some systems can possibly modify these characters.
   Left Curly Brace ("{") 7B 123
   Right Curly Brace ("}") 7D 125
   Vertical Bar/Pipe ("|") 7C 124
   Backslash ("\") 5C 92
   Caret ("^") 5E 94
   Tilde ("~") 7E 126
   Left Square Bracket ("[") 5B 91
   Right Square Bracket ("]") 5D 93
   Grave Accent ("`") 60 96


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

RFC 1738: Uniform Resource Locators (URL) specification
--------------------------------------------------------------------------------
The specification for URLs (RFC 1738, Dec. '94) poses a problem, in that it limits the use of allowed characters in URLs to only a limited subset of the US-ASCII character set:
"...Only alphanumerics [0-9a-zA-Z], the special characters "$-_.+!*'()," [not including the quotes - ed], and reserved characters used for their reserved purposes may be used unencoded within a URL."
HTML, on the other hand, allows the entire range of the ISO-8859-1 (ISO-Latin) character set to be used in documents - and HTML4 expands the allowable range to include all of the Unicode character set as well. In the case of non-ISO-8859-1 characters (characters above FF hex/255 decimal in the Unicode set), they just can not be used in URLs, because there is no safe way to specify character set information in the URL content yet [RFC2396.]

URLs should be encoded everywhere in an HTML document that a URL is referenced to import an object (A, APPLET, AREA, BASE, BGSOUND, BODY, EMBED, FORM, FRAME, IFRAME, ILAYER, IMG, ISINDEX, INPUT, LAYER, LINK, OBJECT, SCRIPT, SOUND, TABLE, TD, TH, and TR elements.)

What characters need to be encoded and why?
--------------------------------------------------------------------------------
ASCII Control characters
Why: These characters are not printable.
Characters: Includes the ISO-8859-1 (ISO-Latin) character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal.)
Non-ASCII characters
Why: These are by definition not legal in URLs since they are not in the ASCII set.
Characters: Includes the entire "top half" of the ISO-Latin set 80-FF hex (128-255 decimal.)
"Reserved characters"
Why: URLs use some characters for special use in defining their syntax. When these characters are not used in their special role inside a URL, they need to be encoded.
Characters: Character Code
Points
(Hex) Code
Points
(Dec)
Dollar ("$")
Ampersand ("&")
Plus ("+")
Comma (",")
Forward slash/Virgule ("/")
Colon (":")
Semi-colon (";")
Equals ("=")
Question mark ("?")
'At' symbol ("@")
24
26
2B
2C
2F
3A
3B
3D
3F
40 36
38
43
44
47
58
59
61
63
64

"Unsafe characters"
Why: Some characters present the possibility of being misunderstood within URLs for various reasons. These characters should also always be encoded.
Characters: Character Code
Points
(Hex) Code
Points
(Dec) Why encode?
Space 20 32 Significant sequences of spaces may be lost in some uses (especially multiple spaces)
Quotation marks
'Less Than' symbol ("<")
'Greater Than' symbol (">") 22
3C
3E 34
60
62 These characters are often used to delimit URLs in plain text.
'Pound' character ("#") 23 35 This is used in URLs to indicate where a fragment identifier (bookmarks/anchors in HTML) begins.
Percent character ("%") 25 37 This is used to URL encode/escape other characters, so it should itself also be encoded.
Misc. characters:
Left Curly Brace ("{")
Right Curly Brace ("}")
Vertical Bar/Pipe ("|")
Backslash ("\")
Caret ("^")
Tilde ("~")
Left Square Bracket ("[")
Right Square Bracket ("]")
Grave Accent ("`")
7B
7D
7C
5C
5E
7E
5B
5D
60
123
125
124
92
94
126
91
93
96 Some systems can possibly modify these characters.



How are characters URL encoded?
--------------------------------------------------------------------------------
URL encoding of a character consists of a "%" symbol, followed by the two-digit hexadecimal representation (case-insensitive) of the ISO-Latin code point for the character.
Example
Space = decimal code point 32 in the ISO-Latin set.
32 decimal = 20 in hexadecimal
The URL encoded representation will be "%20"

URL encoding converter
--------------------------------------------------------------------------------
The box below allows you to convert content between its unencoded and encoded forms. The initial input state is considered to be "unencoded" (hit 'Convert' at the beginning to start in the encoded state.) Further, to allow actual URLs to be encoded, this little converter does not encode URL syntax characters (the ";", "/", "?", ":", "@", "=", "#" and "&" characters)...if you also need to encode these characters for any reason, see the "Reserved characters" table above for the appropriate encoded values.

NOTE:
This converter uses the String.charCodeAt and String.fromCharCode functions, which are only available in Javascript version 1.2 or better, so it doesn't work in Opera 3.x and below, Netscape 3 and below, and IE 3 and below. Browser detection can be tiresome, so this will just fail in those browsers...you have been warned. 8-}




No
Encoding URL-Safe
Encoding


Browser Peculiarities
--------------------------------------------------------------------------------

Internet Explorer is notoriously relaxed in its requirements for encoding spaces in URLs. This tends to contribute to author sloppiness in authoring URLs. Keep in mind that Netscape and Opera are much more strict on this point, and spaces MUST be encoded if the URL is to be considered to be correct.

Sunday

C# - Database connection (SQLSERVER) by c sharp function

DBConnect();

using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;


protected void DBConnect()
{



System.Data.SqlClient.SqlConnection conn =
new System.Data.SqlClient.SqlConnection();
conn.ConnectionString = "Data Source=THOKR02-XP;Initial Catalog=OnDemand;Integrated Security=True";
conn.Open();

SqlCommand command = new SqlCommand("SELECT [TestSuite_Name] FROM [OnDemand].[dbo].[TestSuites]", conn);
SqlDataReader reader = command.ExecuteReader();
DropDownList1.Items.Clear();
while (reader.Read())
{

//TextBox2.Text = (String)reader[0];
DropDownList1.Items.Add((String)reader[0]);
}
reader.Close();
conn.Close();

}

Friday

STAF - Installation on Linux Machine

STAF - Installation on Linux Machine

STEP 1: Software Installation
All the required software are
1. apache-tomcat-6.0.20.tar.gz
2. jre-6u16-linux-i586.bin
3. STAF335-linux.tar.gz


Software: STAF335-linux.tar.gz
Unzip and untar it at the location where you want to install:
gunzip –d STAF335-linux.tar.gz
tar xvf STAF335-linux.tar

Now, navigate to Staf directory and run below command
./STAFInst –acceptlincense -acceptlicense

Once you run the above command, files will get generated in the Staf home directory (By default it will be /usr/local/staf).
Make sure that STAFEnv.sh and startSTAFProc.sh files got created.
Note: If you do not get these files, you cannot move on with the installation.

Now run the below command from the Staf home directory.
chmod a+x STAFEnv.sh
. ./STAFEnv

Now run the below command from the Staf home directory.
chmod a+x startSTAFProc.sh
./startSTAFProc.sh
You should get “nohup: appending output to `nohup.out'” as response.

Verification:
Type STAF local PING PING
PONG should be your response.

NOTE: To let other machines to ping your machine, give the trust level to other machines in “staf .cfg” file.
Find the sample staf .cfg file attached.

# Turn on tracing of internal errors and deprecated options
trace enable tracepoints "error deprecated"

# Enable TCP/IP connections
#interface ssl library STAFTCP option Secure=Yes option Port=6550
interface tcp library STAFTCP option Secure=No option Port=6500

# Set default local trust
trust machine local://local level 5


# Add default service loader
serviceloader library STAFDSLS

TRUST LEVEL 5 MACHINE tcp://machinename-xp.in.com

Once you are done with above step, run the below command
./etc/init.d/iptables stop
The above command will let other machines to connect to your machine without any problem


" you can ping now windows and linux machine added in trusted list"

Thursday

Web devlopment .aspx page creation.

1. Install VS WebDevloper Express from Microsoft

2. OPen VS and select new project with .asp extension

3. Connect database by Go in Design Panel
Database Explorer
Connect to Database ( any kind)
4. big the DIV tag panel (for object Accomodation)
5. Create a drop down to get value of colum in table
add Dropdown list from the Standar (toolbox ) inleft Panel

Click on newly added Object and Select Data source
Click on databases

check the connect string like Data Source=THOKR02-XP;Initial Catalog=OnDemand;Integrated Security=True
The specify Query

chose Where clause and Source is Control (actualy that Object)
Click on advance " Generate Insert update Delete
Go in Design Panel
Select Form View

Edit template




Go in Design Panel
Select Validation ( like see not more than 15 Char)
Select Required field and drag and drop agains the row in form where we want to validate.


Now run sample Application ....
see ASP.NET Devlopment Server runs ASP.NET application locally Dilaoge box ...
gives URL
Port : 1749
Virtual Path : /WebSite1
and Physical Path: C:\My Documents\Visual Studio 2008\WebSites\WebSite1\

Tuesday

On demand Testing Framework - Keyword Driven

What this program will do : it will read the Yes flag and then run the QTP on the particular machine. Which is given into the column "Where want to Run PATH - QC or any other Path"
Prerequisite: Might be DCOM setting need to do for remote execution.

Run prompt > dcomcnfg > Component service > Computer > My computer > DCOM config > right click on QuickTest Professional Automation > security > add the name of user for alll three customize radio button from which you want to run the QTP scripts.

Steps:
Design the Exel with coulmn
Testcasename Where want to Run PATH - QC or any other Path Run On demand When You want to run AM/PM Enviorment URL Resultant Command TSR Location USER


Sample:

Testcasename Where want to Run PATH - QC or any other Path Run On demand When You want to run AM/PM Enviorment URL Resultant Command TSR Location USER
TC_Login shukr02-xp YES Now PM www.Build1.com C:\Automation\TestSuite
TC_CreatRequest Load Sharing Machine NO Now AM www.Build1.com C:\Automation\TestSuite
TC_AmendRequest Load Sharing Machine NO Now PM www.Build3.com C:\Automation\TestSuite
TC_DO_Question Load Sharing Machine NO Now AM www.Build4.com C:\Automation\TestSuite
TC_PutRecommendation Load Sharing Machines NO Now AM www.Build1.com C:\Automation\TestSuite
TC_LogIncident Load Sharing Machine NO Now AM www.Build1.com C:\Automation\TestSuite
TC_resubmit Incident Load Sharing Machine NO 10:20 AM www.Build2.com C:\Automation\TestSuite
TC_SendEmail Subject\QTPFolder\Automation Suite NO 10:34 PM www.Build2.com C:\Automation\TestSuite
TC_LogtheBug0 alara01-xp YES Now AM www.Build2.com \\alara01-xp\Automation\TestSuite
TC_LogtheBug1 alara01-xp NO Now AM www.Build2.com \\alara01-xp\Automation\TestSuite
TC_LogtheBug Load Sharing Machines NO Now AM www.Build2.com C:\Automation\TestSuite
EOF EOF EOF EOF EOF EOF EOF EOF EOF



Select Task
QTP Automation YES
CURL Automation - Sheet 2 NO
Build Deployment - Sheet 3 NO


Macro to run this Code:

'OnDEmandAutomation ("C:\AutomationTesting\TestSuite.xlsm")
Sub OnDEmandAutomation()

'Shell Environ$("COMSPEC") & " /k C:\AutomationTesting\StartAutomation.bat"

Dim tNum, tLoc(100), tCase(100), tTime(100), tTimeAMPM(100), tEnv(100), tpth(100)
APath = "C:\AutomationTesting\TestSuite.xlsm"
tNum = 0

Dim rowCount
rowCount = 2

Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = False
xlApp.Workbooks.Open APath

'xlApp.ScreenUpdating = False
'Set objSheet=xlApp.Workbooks(APath).worksheet("Sheet1")
Set objSheet = xlApp.ActiveWorkbook.Worksheets(1) ' Take Active WorkBook




screenRow = 0

For rowNumber = 2 To 100

screenRow = screenRow + 1

If objSheet.Cells(rowNumber, 1) = "EOF" Then
Exit For

Else
If objSheet.Cells(rowNumber, 3) = "YES" Or objSheet.Cells(rowNumber, 1) = "EOF" Then
tCase(tNum) = objSheet.Cells(rowNumber, 1).Value
tLoc(tNum) = objSheet.Cells(rowNumber, 2).Value
tTime(tNum) = objSheet.Cells(rowNumber, 4).Value
tTimeAMPM(tNum) = objSheet.Cells(rowNumber, 5).Value
tEnv(tNum) = objSheet.Cells(rowNumber, 6).Value
tpth(tNum) = objSheet.Cells(rowNumber, 7).Value


For rt = 0 To 0

'sComp = tLoc(tNum)
'Set WMIobj = GetObject("winmgmts:\\" & sComp & "\root\cimv2")
'Set IEExp = WMIobj.ExecQuery("Select * from Win32_Process Where Name = 'QTPro.exe'")
'MsgBox IEExp.Count
'For Each IEx In IEExp
' IEx.Terminate()
'Next
'Set WMIobj = GetObject("winmgmts:\\" & sComp & "\root\cimv2")
' Find All the iexplore.exe processes
'Set IEExp = WMIobj.ExecQuery("Select * from Win32_Process Where Name = 'iexplore.exe'")
'For Each IEx In IEExp
' IEx.Terminate()
'Next

'Shell Environ$("COMSPEC") & " /k C:\AutomationTesting\LaunchQTP.bat"
'wscript.exe "C:\AutomationTesting\Testrun.vbs"
'If tLoc(tNum) <> "shukr02-xp" Then
'staf_command(tNum)="Staf" & tLoc(tNum) & "process start command" QTPro.exe
Set qtApp = CreateObject("QuickTest.Application", tLoc(tNum)) ' tLoc(tNum) Create the Application object
qtApp.Launch ' Start QuickTest
qtApp.Visible = True ' ' Make the QuickTest application visible
qtApp.Open tpth(tNum), False
qtApp.Test.Run
'qtApp.Test.Close ' Close the test
qtApp.Quit
Set qtApp = Nothing

'Else
'staf_command(tNum)="Staf" & tLoc(tNum) & "process start command" QTPro.exe
'Set qtApp1 = CreateObject("QuickTest.Application") ' Create the Application object
'qtApp1.Launch ' Start QuickTest
'qtApp1.Visible = True ' ' Make the QuickTest application visible
'qtApp1.Open tpth(tNum), False
'qtApp1.Test.Run
'qtApp.Test.Close ' Close the test
'qtApp1.Quit
'Set qtApp1 = Nothing
'End If



Next


'qtApp.Quit ' Exit QuickTest

'Set qtApp = Nothing ' Release the Application object

tNum = tNum + 1


'tNum = tNum + 1
'msgBox "Testcase" & testCase
End If
End If
Next

xlApp.Quit

KillProcessEXCEL = "EXCEL.EXE"
Set ProcessList2 = GetObject("winmgmts://.").InstancesOf("win32_process")
For Each Process In ProcessList2
If Process.Name = KillProcessEXCEL Then
Process.Terminate
End If
Next

'Call AttachHTMLAsMailContent("Team-Picasso-QA123", "shukr02", "alara01", "Automation Completed", "http://result.com")

End Sub


'Function AttachHTMLAsMailContent(sSendTo, sSendToCC, sSendToBCC, sSubject, sHtmlPath)

'Dim objOutlook
'Dim objOutlookMsg
'Dim olMailItem

' Create the Outlook object and the new mail object.
'Set objOutlook = CreateObject(Outlook.Application)
'Set objOutlookMsg = objOutlook.CreateItem(olMailItem)

' Define mail recipients
'objOutlookMsg.To = sSendTo
'objOutlookMsg.CC = sSendToCC
'objOutlookMsg.BCC = sSendToBCC

' Body of the message

'With objOutlookMsg
'Set fso = CreateObject(Scripting.FileSystemObject)
'Set ts = fso.OpenTextFile(sHtmlPath, 1)
'strText = ts.ReadAll
'.HTMLBody = strText
'.Display
'End With

' Send the message
'objOutlookMsg.Send
'Wait (3)

' Release the objects
'Set objOutlook = Nothing
'Set objOutlookMsg = Nothing

'End Function

QTP - Reading Command prompt from QTP

'Add the command prompt as a object in QTP OR.

myname=SysExecute("dir")
MsgBox myname

Function SysExecute(ByVal strCmdtoExecute)
Dim Output ' Variant
SystemUtil.CloseProcessByName("cmd.exe")
Wait 2
SystemUtil.Run "cmd", "/K cd c:\ & cls", "", "", 1
Wait 3
sPrompt = window("CommandWindow").GetVisibleText

if(sPrompt <> " ") then
myarray = split(sPrompt,vbCRLF)
if(ubound(myarray)>0) Then
lastline = ubound(myarray)
sPrompt = myarray(lastline)
else
sPrompt = "c:\>"
end if
else
sPrompt = "c:\>"
end if

with window("CommandWindow")
.activate
.type strCmdtoExecute
.type micreturn
end with
i=1
Do While True
cmdOutput = window("CommandWindow").GetVisibleText
myarray = split(cmdOutput,vbCRLF)
if(ubound(myarray)>0) Then
lastline = ubound(myarray)
sNewPrompt = myarray(lastline)
if(StrComp(sPrompt,sNewPrompt,0) = 0) then
For j = 1 to lastline -1
Output = Output & vbcrlf & myarray(j)
Next
Exit do
end if
else
lastline = ubound(myarray)
end if
if(i>15) then 'Exit condition
if(lastline > 3) then
For j = 2 to lastline -1
Output = Output & vbcrlf & myarray(j)
Next
else
Output = " "
end if
Exit do
end if
i=i+1
Loop

SysExecute = Output
window("CommandWindow").Close
Wait 2
Exit function
End Function

Monday

QTP - Matching pattern in string by regular expression

MsgBox(RegExpTest("ab","abhishek"))

Function RegExpTest(patrn, strng)
Dim regEx, Match, Matches ' Create variable.
Set regEx = New RegExp ' Create a regular expression.
regEx.Pattern = patrn ' Set pattern.
regEx.IgnoreCase = True ' Set case insensitivity.
regEx.Global = True ' Set global applicability.
Set Matches = regEx.Execute(strng) ' Execute search.
For Each Match in Matches ' Iterate Matches collection.
RetStr = RetStr & "Match found at position "
RetStr = RetStr & Match.FirstIndex & ". Match Value is '"
RetStr = RetStr & Match.Value & "'." & vbCRLF
Next
RegExpTest = RetStr
End Function
'If want to search multiple lines
'MsgBox(RegExpTest("is.", "IS1 is2 IS3 is4"))

Friday

STAF - Software Test Automation Framework

Installation and setting machine:

STEP;1 : INstall STF in C:\STAF
Step2: create C:\STAF\service folder
Step3: put Stax in the service folder
STEP 4: Install perl and Python
STEP 5:Set classpath add -->C:\STAF\bin\JSTAF.jar;C:\python22\lib;
classpath add -->C:\STAF\bin\JSTAF.jar;C:\python22\lib;C:\perl\lib;
path add -->C:\STAF\bin;C:\Python22;c:\perl\bin;
create a new variable with PYTHONPATH and set the value C:\STAF\bin;
create a new variable STAF_DIR with the value c:\staf;
STEP 6:OPen the staf.cnf file from c:\staf\bin. put line given below
SERVICE STAX LIBRARY JSTAF EXECUTE C:\STAF\services\stax\STAX.jar
SERVICE EVENT LIBRARY JSTAF EXECUTE C:\STAF\services\stax\STAFEvent.jar
Step 7: Set trust level
TRUST LEVEL 5 MACHINE shukr02-RH5
Step 8: comment the line SSL in staf.cnf file

Step9: set the other trust machine.

Step 10: start Staf


Command:
Go to C:\staf folder in command prompt:
1.To Open the commad promt on trusted machine
staf process start process cmd.exe
staf process start process cmd.exe

2. Copy the file from one locatoin to other location:
C:\>STAF local FS COPY FILE "C:\Program Files\file1.txt" TOFILE "C:\Program Files\file2.txt"
STAF local PROCESS START SHELL COMMAND "copy \"C:\Program Files\file1.txt\" \"C:\Program Files\file2.txt\"" WAIT RETURNSTDOUT STDERRTOSTDOUT

3.LIST DIRECTORY ( like ls in Unix)
STAF local FS LIST DIRECTORY "C:\Program Files"
4.More kind of Unix command facility
like more "C:\Program Files\file1.txt"
STAF local PROCESS START SHELL COMMAND "more \"C:\Program Files\file1.txt\"" WAIT RETURNSTDOUT STDERRTOSTDOUT SAMECONSOLE
STAF local FS GET FILE "C:\Program Files\file1.txt"
5.echo this is the string to be parsed > "C:\Program Files\echofile.txt"

if fiile will not there it will craete the file:

this command will replace the content of file and put the string given after echo "this is the string to be parsed "

STAF local PROCESS START SHELL COMMAND "echo this is the string to be parsed > \"C:\Program Filesr\echofile.txt\"" WAIT RETURNSTDOUT STDERRTOSTDOUT

Wednesday

QTP - Open a process on remote machine

strComputer = "alara01-xp"
'strComputer = "."
'strCommand = "notepad.exe"
'strCommand = "C:\Program Files\HP\QuickTest Professional\bin\QTPro.exe"
'strCommand = "C:\Program Files\HP\QuickTest Professional\bin\QTP.exe"
'c:\Program Files\Mercury Interactive\QuickTest Professional\bin
'strCommand = "c:\Program Files\Mercury Interactive\QuickTest Professional\bin\QTPro.exe"
'strCommand = "C:\Program Files\Internet Explorer\IEXPLORE.exe"
'strCommand = "mspaint.exe"
'strCommand = "IEXPLORE.EXE"
strCommand = "cmd.exe"



Const INTERVAL = "n"
Const MINUTES = 1


Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set objScheduledJob = objWMIService.Get("Win32_ScheduledJob")
Set objSWbemDateTime = CreateObject("WbemScripting.SWbemDateTime")


objSWbemDateTime.SetVarDate(DateAdd(INTERVAL, MINUTES, Now()))
errReturn = objScheduledJob.Create(strCommand, objSWbemDateTime.Value, False, 0, 0, True, intJobID)


If errReturn = 0 Then
Wscript.Echo "notepad.exe was started with a process ID: " & intJobID
Else
Wscript.Echo "notepad.exe could not be started due to error: " & errReturn
End If

VBS to launch/Invoke QTP

VBS to launch QTP 9.2 and invoke script automatically
'Code found @ http://www.learnqtp.com/forums/vbs-launch-qtp-invoke-script-automatically-t-417.html
Enter the following code in VBScript editor and save teh file(saves as a VBS file) then you can go to the CMD to run the VBS file or use windows scheduler to schedule for a particular time.This is just an example make sure to change the location of the test script.

'**************************************************************************
'The following script opens a test, configures run options and settings,
'runs the test, and then checks the results of the test run.
'**************************************************************************
Dim qtApp 'As QuickTest.Application 'Declare the Application object variable
Dim qtTest 'As QuickTest.Test 'Declare a Test object variable
Dim qtResultsOpt 'As QuickTest.RunResultsOptions ' Declare a Run Results Options object variable
Const ForReading = 1, ForWriting = 2
Dim fso, f, result

Set fso = CreateObject("Scripting.FileSystemObject")
Set f = fso.OpenTextFile("C:\Program Files\Mercury Interactive\QuickTest Professional\Tests\Regression_Test_Results.txt", ForWriting, True)

Set qtApp = CreateObject("QuickTest.Application") 'Create the Application object
qtApp.Launch 'Start QuickTest
qtApp.Visible = True 'Make the QuickTest application visible

'Set QuickTest run options
qtApp.Options.Run.ImageCaptureForTestResults = "OnError"
qtApp.Options.Run.RunMode = "Fast"
qtApp.Options.Run.ViewResults = False
qtApp.Open "C:\Program Files\Mercury Interactive\QuickTest Professional\Tests\Regression_Suite_BA_1\CharitableOrg_Owner_NonQual_GuaDeathBen​efit_SurrenderCharges", True ' Open the test in read-only mode

'Set run settings for the test
Set qtTest = qtApp.Test
qtTest.Settings.Run.IterationMode = "rngIterations" 'Run only iterations 2 to 4
qtTest.Settings.Run.StartIteration = 2
qtTest.Settings.Run.EndIteration = 4
qtTest.Settings.Run.OnError = "NextStep" ' Instruct QuickTest to perform next step when error occurs

'Set the results path
Set qtResultsOpt = CreateObject("QuickTest.RunResultsOptions") ' Create the Run Results Options object
qtResultsOpt.ResultsLocation = "C:\Program Files\Mercury Interactive\QuickTest Professional\Tests\Regression_Suite_BA_1\CharitableOrg_Owner_NonQual_GuaDeathBen​efit_SurrenderCharges\Res1" ' Set the results location
qtTest.Run qtResultsOpt 'Run the test
result= qtTest.LastRunResults.Status
f.Write("Test 1: CharitableOrg_Owner_NonQual_GuaDeathBenefit_SurrenderCharges - ")
f.Write(result)
f.WriteBlankLines(1)

Monday

EXPORT QC TESTCASES and BUGS in Excel code

Option Explicit
Dim sUserName,sPassword
sUserName = "YOUR_UID"
sPassword = "YOUR_PWD"
Const xlLeft = -4131
Const xlRight = -4152
Const xlCenter = -4108
Const xlGeneral = 1
Dim QCConnection
'Return the TDConnection object.
Set QCConnection = CreateObject("TDApiOle80.TDConnection")
QCConnection.InitConnectionEx "http://YOUR_URLOFQC:8080/qcbin/"
QCConnection.Login sUserName, sPassword
If (QCConnection.LoggedIn <> True) Then
MsgBox "QC User Authentication Failed"
WScript.Quit
End If
Dim sDomain, sProject
sDomain = "YOUR_Domain"
sProject = "YOUR_Project"
QCConnection.Connect sDomain, sProject
If (QCConnection.Connected <> True) Then
MsgBox "QC Project Failed to Connect to " & sProject
WScript.Quit
End If
Call ExportTestCases()
'Call ExportDefects()
QCConnection.Disconnect
QCConnection.Logout
QCConnection.ReleaseConnection
Function PrintFields(oObject)
Dim FieldsList, Field
Set FieldsList = oObject.Fields
For Each Field In FieldsList
WScript.Echo Field
Next
End Function
Function ExportTestCases()
Dim TestFactory, TestList
Set TestFactory = QCConnection.TestFactory
Set TestList = TestFactory.NewList("") 'Get a list of all tests.
Dim TestCase, Excel, Sheet
Set Excel = CreateObject("Excel.Application") 'Open Excel
Excel.WorkBooks.Add() 'Add a new workbook
'Get the first worksheet.
Set Sheet = Excel.ActiveSheet
Sheet.Name = "Tests"
With Sheet.Range("A1:H1")
.Font.Name = "Arial"
.Font.FontStyle = "Bold"
.Font.Size = 10
.Font.Bold = True
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlCenter
.Interior.ColorIndex = 15 'Light Grey
End With
Sheet.Cells(1, 1) = "Subject (Folder Name)"
Sheet.Cells(1, 2) = "Test Name (Manual Test Plan Name)"
Sheet.Cells(1, 3) = "Description"
'Sheet.Cells(1, 4) = "Designer (Owner)"
'Sheet.Cells(1, 5) = "Status"
Sheet.Cells(1, 6) = "Step Name"
Sheet.Cells(1, 7) = "Step Description(Action)"
Sheet.Cells(1, 8) = "Expected Result"
'Call PrintFields(TestFactory)
Dim Row
Dim countingSubject
Row = 2
'Iterate through all the tests.
For Each TestCase In TestList
Dim DesignStepFactory, DesignStep, DesignStepList
Set DesignStepFactory = TestCase.DesignStepFactory
Set DesignStepList = DesignStepFactory.NewList("")
countingSubject=0
If DesignStepList.Count = 0 Then
'Save a specified set of fields.
Sheet.Cells(Row, 1).Value = TestCase.Field("TS_SUBJECT").Path
Sheet.Cells(Row, 2).Value = TestCase.Field("TS_NAME")
Sheet.Cells(Row, 3).Value = TestCase.Field("TS_DESCRIPTION")
'Sheet.Cells(Row, 4).Value = TestCase.Field("TS_RESPONSIBLE")
'Sheet.Cells(Row, 5).Value = TestCase.Field("TS_STATUS")
Row = Row + 1
Else
For Each DesignStep In DesignStepList
'Save a specified set of fields.
If countingSubject=0 then
Sheet.Cells(Row, 1).Value = TestCase.Field("TS_SUBJECT").Path
Sheet.Cells(Row, 2).Value = TestCase.Field("TS_NAME")
Sheet.Cells(Row, 3).Value = TestCase.Field("TS_DESCRIPTION")
'Sheet.Cells(Row, 4).Value = TestCase.Field("TS_RESPONSIBLE")
'Sheet.Cells(Row, 5).Value = TestCase.Field("TS_STATUS")
'Save the specified design steps.
Sheet.Cells(Row, 6).Value = DesignStep.StepName
Sheet.Cells(Row, 7).Value = DesignStep.StepDescription
Sheet.Cells(Row, 8).Value = DesignStep.StepExpectedResult
else
Sheet.Cells(Row, 6).Value = DesignStep.StepName
Sheet.Cells(Row, 7).Value = DesignStep.StepDescription
Sheet.Cells(Row, 8).Value = DesignStep.StepExpectedResult
end if
countingSubject=countingSubject+1
Row = Row + 1
Next
End If
'for max number of row delet this code if you want full export
If Row>500 Then
Exit For
End If
Next
'Call PrintFields(DesignStepFactory)
'Excel.Columns.AutoFit
'Save the newly created workbook and close Excel.
'Excel.ActiveWorkbook.SaveAs("C:\" & sProject & "_TESTCASE1.xls")
'Excel.Workbooks.Open("C:\Export_TESTCASE1.xlsx")

Dim objRange
Set objRange = Sheet.UsedRange
'Remove tag in the following lines
Excel.Cells.Replace "'tag_html>'"," "
Excel.Cells.Replace "tag_body>"," "
Excel.Cells.Replace "/tag_html>"," "
Excel.Cells.Replace "/tag_body>"," "
Excel.Cells.Replace "tag_br>"," "

Excel.ActiveWorkbook.SaveAs("C:\" & sProject & "_TESTCASE.xlsx")
Excel.Quit
End Function

Thursday

QTP - Associate Object repository at run time in QTP

Methods
Add
Adds an object repository file to the specified position in the collection.
Find
Finds the position of the specified object repository file.
MoveToPos
Moves the object repository file entry from the current position to the specified new position.
Remove
Removes the object repository that is located in the specified position.
RemoveAll
Removes all object repository files from the collection.
SetAsDefault
Sets the object repository files associated with the current action as the default files for all new actions.




'************************************************************************************************************************


'Description:


'


'This example opens a test, configures an action's object repositories collection


'and saves the test.


'


'Assumptions:


'There is no unsaved test currently open in QuickTest.


'For more information, see the example for the Test.SaveAs method.


'************************************************************************************************************************





Dim qtApp 'As QuickTest.Application ' Declare the Application object variable


Dim qtRepositories 'As QuickTest.ObjectRepositories ' Declare an action's object repositories collection variable


Dim lngPosition





' Open QuickTest


Set qtApp = CreateObject("QuickTest.Application") ' Create the Application object


qtApp.Launch ' Launch QuickTest


qtApp.Visible = True ' Set QuickTest to be visible





' Open a test and get the "Login" action's object repositories collection


qtApp.Open "C:\Tests\Test1", False, False ' Open a test


Set qtRepositories = qtApp.Test.Actions("Login").ObjectRepositories ' Get the object repositories collection object of the "Login" action





' Add MainApp.tsr if it's not already in the collection


If qtRepositories.Find("C:\MainApp.tsr") = -1 Then ' If the repository cannot be found in the collection


qtRepositories.Add "C:\MainApp.tsr", 1 ' Add the repository to the collection


End If





' If InnerWnd.tsr is moved down the list - place it back at position 1


If qtRepositories.Count > 1 And qtRepositories.Item(2) = "C:\InnerWnd.tsr" Then ' If there's more than one object repository and InnerWnd.tsr is in position 2


qtRepositories.MoveToPos 1, 2 ' Switch between the first two object repositories


End If





' If Debug.tsr is in the collection - remove it


lngPosition = qtRepositories.Find("C:\Debug.tsr") ' Try finding the Debug.tsr object repository


If lngPosition <> -1 Then ' If the object repository was found in the collection


qtRepositories.Remove lngPosition ' Remove it


End If





' Set the new object repository configuration as the default for all new actions


qtRepositories.SetAsDefault ' Set object repositories associated with the "Login" action as the default for all new actions





'Save the test and close QuickTest


qtApp.Test.Save ' Save the test


qtApp.Quit ' Quit QuickTest





Set qtRepositories = Nothing ' Release the action's shared repositories collection


Set qtApp = Nothing ' Release the Application object

'********************
'***************************


'The following example retrieves an object repository's objects and properties,


'looks for specific test objects using several methods, and copies a test object


'to another object repository.


'********************
'***************************
Dim ImageObj, PageObj, RepositoryFrom, RepositoryTo




Set RepositoryFrom = CreateObject("Mercury.ObjectRepositoryUtil")


Set RepositoryTo = CreateObject("Mercury.ObjectRepositoryUtil")




RepositoryFrom.Load "C:\QuickTest\Tests\Flights.tsr"


RepositoryTo.Load "E:\Temp\Tests\Default.tsr"


Function EnumerateAllChildProperties(Root)


'The following function recursively enumerates all the test objects directly under


'a specified parent object. For each test object, a message box opens containing the


'test object's name, properties, and property values.


Dim TOCollection, TestObject, PropertiesCollection, Property, Msg




Set TOCollection = RepositoryFrom.GetChildren(Root)




For i = 0 To TOCollection.Count - 1


Set TestObject = TOCollection.Item(i)


Msg = RepositoryFrom.GetLogicalName(TestObject) & vbNewLine


Set PropertiesCollection = TestObject.GetTOProperties()




For n = 0 To PropertiesCollection.Count - 1


Set Property = PropertiesCollection.Item(n)


Msg = Msg & Property.Name & "-" & Property.Value & vbNewLine


Next


MsgBox Msg




EnumerateAllChildProperties TestObject


Next




End Function




Function EnumerateAllObjectsProperties(Root)


'The following function enumerates all the test objects under a specified object.


'For each test object, a message box opens containing the test object's name,


'properties, and property values.


Dim TOCollection, TestObject, PropertiesCollection, Property, Msg




Set TOCollection = RepositoryFrom.GetAllObjects(Root)




For i = 0 To TOCollection.Count - 1


Set TestObject = TOCollection.Item(i)


Msg = RepositoryFrom.GetLogicalName(TestObject) & vbNewLine




Set PropertiesCollection = TestObject.GetTOProperties()


For n = 0 To PropertiesCollection.Count - 1


Set Property = PropertiesCollection.Item(n)


Msg = Property.Name & "-" & Property.Value & vbNewLine


Next




MsgBox Msg


Next




End Function




Function RenameAllImages(Root)


'The following function sets a new name for all image test objects under a specified object.


Dim TOCollection, TestObject, PropertiesCollection, Property




Set TOCollection = RepositoryTo.GetAllObjectsByClass("Image")




For i = 0 To TOCollection.Count - 1


Set TestObject = TOCollection.Item(i)


RepositoryTo.RenameObject (TestObject, "Image " & i)


RepositoryTo.UpdateObject TestObject


Next




End Function




Function RemoveAllLinks(Root)


'The following function recursively enumerates all the test objects under a specified object.


'It looks for all test objects of class Link and removes them from their parent objects.


Dim TOCollection, TestObject, PropertiesCollection, Property




Set TOCollection = RepositoryFrom.GetChildren(Root)




For i = 0 To TOCollection.Count - 1


Set TestObject = TOCollection.Item(i)


TOClass = TestObject.GetTOProperty("micclass")




If TOClass = "Link" Then


RepositoryFrom.RemoveObject Root, TestObject


End If




EnumerateAllChildProperties TestObject


Next




End Function

Monday

QTP/QC - Schedule the testset in QC by VBS

'User must Admin at the machine where he want to run the testset
'This can run manual as well as Automated test suite
' It can be schedule at any partcular future time
' User need not to open the QC

Public Sub RunTestSet(otdc,tsFolderName,tSetName,HostName,runWhere)


Dim TSetFact, tsList
Dim theTestSet
Dim tsTreeMgr
Dim tsFolder
Dim Scheduler
Dim nPath
Dim execStatus
' Get the test set tree manager from the test set factory
'tdc is the global TDConnection object.
Set TSetFact = otdc.TestSetFactory


Set tsTreeMgr = otdc.TestSetTreeManager


' Get the test set folder passed as an argument to the example code


nPath = "Root\" & Trim(tsFolderName)


Set tsFolder = tsTreeMgr.NodeByPath(nPath)


If tsFolder Is Nothing Then


err.Raise vbObjectError + 1, "RunTestSet", "Could not find folder " & nPath


End If



' Search for the test set passed as an argument to the example code



Set tsList = tsFolder.FindTestSets(tSetName)



If tsList Is Nothing Then


err.Raise vbObjectError + 1, "RunTestSet", "Could not find test set in the " & nPath


End If



If tsList.Count > 1 Then


MsgBox "FindTestSets found more than one test set: refine search"


Exit Sub


ElseIf tsList.Count < 1 Then

MsgBox "FindTestSets: test set not found"


Exit Sub


End If


Set theTestSet = tsList.Item(1)


Debug.Print theTestSet.ID


'Start the scheduler on the local machine


Set Scheduler = theTestSet.StartExecution(HostName)



'msgbox "pass"


'Set up for the run depending on where the test instances


' are to execute.




Select Case runWhere


Case "RUN_LOCAL"


'Run all tests on the local machine


Scheduler.RunAllLocally = True


Case "RUN_REMOTE"



'Set Scheduler = theTestSet.StartExecution(HostName)


'Run tests on a specified remote machine


Scheduler.TdHostName = HostName


'Scheduler.TdHostName=runWhere


' RunAllLocally must not be set for


' remote invocation of tests.


' Do not do this:


' Scheduler.RunAllLocally = False


Case "RUN_PLANNED_HOST"


'Run on the hosts as planned in the test set


Dim TSTestFact, TestList


Dim tsFilter


Dim TSTst


'Get the test instances from the test set


Set TSTestFact = theTestSet.TSTestFactory


Set tsFilter = TSTestFact.Filter


tsFilter.Filter("TC_CYCLE_ID") = theTestSet.ID


Set TestList = TSTestFact.NewList(tsFilter.Text)


Scheduler.RunAllLocally = False


End Select



'Run the tests


Scheduler.run



Set execStatus = Scheduler.ExecutionStatus



While (RunFinished = False)


execStatus.RefreshExecStatusInfo "all", True


RunFinished = execStatus.Finished


Wend


End Sub




'================================




Const qcHostName = "GiveQChost:8080"


Const qcDomain = "GiveDomain name"


Const qcProject = "GiveProject" 'Please define here the name of the project


Const qcUser = "User ID" 'Please define here the username



Const qcPassword = "Give Password HGBGH%3&42" 'Please define here the password


Dim tdc


Dim qcServer


Dim objArgs


Dim strArg


Dim strTestSet


Dim bRunCode



'======GETTING ARGUMENTS==============


set objArgs = WScript.Arguments


If WScript.Arguments.Count<1>2 Then


WScript.Echo "Remote_Scheduler"


bRunCode = False


Else


For Each strArg in objArgs


WScript.Echo strArg&" is starting…"


strTestSet = strArg


bRunCode = True


Next


End If


'===========================================================




If bRunCode Then


qcServer = "http://" & qcHostName


qcServer = qcServer & "/qcbin"


Set tdc = CreateObject("tdapiole80.tdconnection")




If (tdc Is Nothing) Then


MsgBox "tdc object is empty"


End If


tdc.InitConnectionEx qcServer


tdc.Login qcUser, qcPassword


tdc.Connect qcDomain, qcProject




RunTestSet tdc, "GiveFolder Name of Test Set","GiveTestSet name ","Givemachinename", "RUN_REMOTE"


'Disconnect from the project


If tdc.Connected Then


tdc.Disconnect


End If


'Log off the server


If tdc.LoggedIn Then


tdc.Logout


End If


'Release the TDConnection object.


tdc.ReleaseConnection


'"Check status (For illustrative purposes.)


Set tdc = Nothing


End IF

Friday

QTP - Thing to know , things of practical learning, small things but worth to spent time with

This post will update whenever I will find anything new/Intresting or just to remember or to know (n FAQ) :

Q1. what is OTA API in QC
The Open Test Architecture API is a COM library that enables you to:
nintegrate external applications with Quality Center
ninteract with the Quality Center application without having to use the GUI front-end
ninteract with the QC databases bypassing DBA

More Info: connectedtesting.com/Presentations/QC%20OTA%20presentation.ppt

QTP/QC - Running bat file from QC

Povide the bat file 'Driverbat.bat' remove ' sign and put bat under folder C:\QTP_Resource.
'cd C:\QTP_Resource
'DriverScript_QTP
'C:\QTP_Resource\Utility2.exe auto some other utility
'Exit

In QC > Create a VAPI-XP test > in test script put the code

Dim objShell


Set objShell = CreateObject("WScript.Shell")


'objShell.Run "CMD.exe"



objShell .Run "%comspec% /k c: & cd C:\QTP_Resource Driverbat.bat"
BR>
'objShell.Run "%comspec% /k c: & cd C:\QTP_Resource\\Driverbat.bat"
BR>
'qtAppWin.sendkeys "~"

QTP - Creating a XML file (Output.xml) by FileSystemObject

Call createLog


Call OpenBrowser


Call TestCase1


Call TestCase2


Call TestCase3


Call CloseLog


Function CreateLog()


Dim TRFSO, MyTRFile,TRFileName


TRFileName = "C:\Automation\Result\Output.xml"


Set TRFSO=CreateObject("Scripting.FileSystemObject")


Set MyTRFile = TRFSO.CreateTextFile(TRFileName)


MyTRFile.WriteLine("")


MyTRFile.WriteLine("")


MyTRFile.close


Set TRFSO=Nothing


End Function




Function CloseLog()


Dim TRFSO, MyTRFile,TRFileName


TRFileName = "C:\Automation\Result\Output.xml"


Set TRFSO=CreateObject("Scripting.FileSystemObject")


Set MyTRFile=TRFSO.OpenTextFile(TRFileName,8,True)


MyTRFile.WriteLine("
")


MyTRFile.close


Set TRFSO=Nothing


End Function




Function WriteLog(Msg)


Dim TRFSO, MyTRFile,TRFileName


TRFileName = "C:\Automation\Result\Output.xml"


Set TRFSO=CreateObject("Scripting.FileSystemObject")


Set MyTRFile=TRFSO.OpenTextFile(TRFileName,8,True)


MyTRFile.WriteLine(Msg)


MyTRFile.close


Set TRFSO=Nothing


End Function




Function OpenBrowser()


SystemUtil.Run "C:\Program Files\Internet Explorer\IEXPLORE.EXE"


'Rerecord SystemUtil step


Browser("X").Page("Y").Sync


Browser("X").Page("Y").Sync.Navigate "http://www.Someapp.com"


End Function




Function TestCase1()


On Error Resume Next


Browser("X").Page("Y").WebEdit("Z").Set "Set Some TestCase"


'do something more and the write in log to post in output.xml


If Err.Number <> 0 Then


WriteLog("Failed")


Else


WriteLog("Passed")


End If


End Function




Function TestCase2()


On Error Resume Next


Browser("X").Page("Y").WebEdit("Z").Set "Set Some TestCase"


'do something more and the write in log to post in output.xml


If Err.Number <> 0 Then


WriteLog("Failed")


Else


WriteLog("Passed")


End If


End Function




Function TestCase3()


On Error Resume Next


Browser("X").Page("Y").WebEdit("Z").Set "Set Some TestCase"


'do something more and the write in log to post in output.xml


If Err.Number <> 0 Then


WriteLog("Failed")


Else


WriteLog("Passed")


wait(2)


if Browser("X").Exist Then


Browser("X").close


End If


End If


End Function

Tuesday

QTP- Execute the bat file , dos command from QTP

dim appset app=createobject("wscript.shell")
SystemUtil.run "cmd.exe"
app.sendkeys "cd C:\Documents and Settings\'<>\"
app.sendkeys "~"
app.sendkeys "MyDosFile.bat"
app.sendkeys "~" app.sendkeys "~"
wait(5)

'In bat file you can give and save
Date
echo "hello World"
pause

Monday

QTP - Blocking/Unblocking the pop-Up by QTP

Sometime the Pop-ups create problem while running the script (Browser pop-ups). To overcome this problem we can manipulate Registry key.
QTP can use this function.

'Create the shell object
Set WshShell = CreateObject("WScript.Shell")

'Path to edit in registry
popupKeyPath = "HKCU\Software\Microsoft\Internet Explorer\New Windows\PopupMgr"

'Disable the IE pop-up blocker
WshShell.RegWrite popupKeyPath, "no", "REG_SZ”

‘Enable the IE pop-up blocker
WshShell.RegWrite popupKeyPath, "yes", "REG_SZ”

QTP - VBSscript to start server

'This VBSscript to start server 'To start servers on Windows/Unix/Linux server
Dim w3sock Set w3sock = CreateObject("socket.tcp")
With w3sock
.timeout = 6000
.DoTelnetEmulation = True
.TelnetEmulation = "TTY"
.Host = "localhost:2023"
.Open
.WaitFor "login:"
WScript.Echo .Buffer
.SendLine "Provide your User ID"
.WaitFor "password:"
.SendLine "Provide your Password"
.WaitFor ">"
.SendLine "net start ""Server Mgr"""
.WaitFor ">"
WScript.Echo .Buffer
.Close
End With
Set w3sock = Nothing
'Install w3socket somewhere like dimac.net/

QTP - Comparison between SilkTest and QTP


FeatureQTPSilkTest
Record and Play Supported Supported
Scripting Language VBScript 4test, Similar to C++
Object recognition based on Object properties, DOM structure based on Object properties, DOM structure
Browser Support IE & FF are supported IE & FF are supported
QC Integration Possible Found a doc, but not validated yet.
CA License Yes Yes; But, only one we believe
Learning Curve Less effort Considerable effort required
Integration with external libraries Possible NO
Tech Support Yes Yes
Current Release v10.0 v9.2.1
Test Project/TestPlan (Test Orgnization) Not Avilable Avialble
Exception Handling by Tool Excellent Moderate
Virtual Object Concept for Custome Object Avilable
DLL support Both COM and Standard DLLs are supported. Only Standard DLLs. It does not support the COM/ActiveX DLLs, which are created by VB/.NET.
Distributed Testing Remote Agent COM Agent. Remote Agent.
Results Reporting QTP results are stroed as XML files and can be converted to HTML files. Result folder contain many files. One result folder can store results for only one run. Results are stored into *.res binary files. It can be converted into differnt formats. Multiple versions can be stored into single file.
Verification Provided check points for different purposes. Provided Verify and Verify Properties functions.
OOPs Support Not supported Oops concepts are supported for certain extent. User can extend standard classes.
Active Screen Kind Feature to modify test better even when App is down. Avilable - Keyword View, Expert View Not Avilable - Classic 4Test, Visual 4Test
Objects Repository Maintained as separate file. With the help of utility, objects are modified. Two types as per QTP setting. They are 'Per Action Repository' and 'Shared Repository'. File extensions will be varied for each type. Official term is Window declarations. They can be edited directly from the Editor
Custom Classes Virutal Object Wizards available. RecorderClass and Extension Kit are available.
Environment support Can access OS level variables. Can access OS level variables.
Internatioalization (i18N) Support YES YES
Java/>NET/Flex Support YES YES
OS Windows upto Vista Windows upto Vista, Unix (SilkBean)
Data functions DataSheet ( Local and Global) Extensive feature Fair
Documentation Both CHM and PDF files are available. Enough info. HLP file available. PDF docs are only for beginners.
Associated Utilites Provide lots of Utility like batchrunner,OR merge tool, Silent Runner, PasswordEncoder,Remote Agent, Movie Recorder, SilentRunner Less Utilites though Extension kit is there.
Product Name Changes Initially Astra QuickTest. Later changed to HP QuickTest Professional. Initially QA Partner. Later changed to Borland SilkTest
Vendor HP (Hewlett-Packard). Initially developed by Mercury Interactive. HP acquired Mercury on 2006. Microfocus. In past Borland. Initially developed by Segue. Borland acquired Segue on 2006.
Strengths The most popular test tool by great user base, plenty of jobs, good online community, Good cross browser support Good Development language, good online community, recovery system, Good cross browser support, Code Maintenance
Editor Better one with nice look. But using tabs to show more than one script. Good. Simple one. Having Project explorer similar to MS Visual Studio.
Ease of use Record and playback used to help. Very Simple. Easy to learn. Just record and playback, won't help. Medium.
Data types Set of data types are available. User cannot create their own data types Set of data types are available. User can create their own data types also.
Code Samples Few samples from vendor. But many VB Script samples available on Internet. Few samples from vendor.
Batch Run Test Batch Runner utility. Suite (*.s) and Test plan (*.pln) are available.
Test Management Tool Integration Integrated with Quality Center. Integrated with SilkCentral Test Manager.
Dynamic objects Object properties can be passed dynamically. Another term is known as Descriptive Programming. Object properties can be passed dynamically. Variety of methods available to handle them.
Objects Repository Maintained as separate file. With the help of utility, objects are modified. Two types as per QTP setting. They are 'Per Action Repository' and 'Shared Repository'. File extensions will be varied for each type. Official term is Window declarations. They can be edited directly from the Editor.
Test Script Actually Script is a folder and have set of supporting files. Script is a single file.
Tests Termed as Actions. Each Action has block of coding statements. Termed as Testcase. Each Testcase has block of coding statements.
Database tests With the help of DSN (ODBC32 Interface) plus VB Scripting With the help of DSN (ODBC32 Interface)
Browsers support Internet Explorer, Netscape, FireFox, AOL Internet Explorer, Netscape, FireFox, AOL


Comon Object Identification Issues (including label changes) and how QTP and Silk approach to resolve that. The Object Identification Cases and resolution:
1. Name/label Change

QTP: Only need to Modify property/properties in OR. It will reflect the same in all scripts.

SilkTest: Modifying the Window tag will solve the purpose.Conclusion: Logically both are doing same thing. The appearance and organization of keeping Object property is different.We need to keep the logical and physical name separate for both.
2. A DialogBox that can have different parents

QTP: QTP physically Store the hierarchy, so there will not be any issue. We can use DP ( descriptive programming) to handle this scenario.

SilkTest: Using windowtag, tag “..\{Object-name}” can associate any object to any parentConclusion: QTP might take DP effort if hierarchy changes very frequently . On the other hand Silk can associate parent on the fly.
3. A Browser Child with a non-unique tag

QTP: Creation Time and separate hierarchy in OR makes things easier

SilkTest: BrowserChild indexing solve problem but have restriction.Conclusion: QTP having better mechanism for it.
4. A window tag that contains variable characters

QTP: Regular expression, DP, Get/Set properties are the example to resolve this kind of issue

SilkTest: Using wildcard characters/Reg Exp can solve the issueConclusion: QTP provide multiple ways to handle it as mentioned above.
5. An object whose index varies based on application context

QTP: Indexing at the level of OR, We can use it in Code also but not very encouraging

SilkTest: It use index property with variety.Conclusion: Silk use programming approach and it support indexing property in great detail.
6. An object where one or more instance may exists

QTP: Exist, Wait, WaitProperty, OST,Timeout are the way to find that Object exist or not. Can be write simple logic for timeout also.

SilkTest: Sleep, Exist function available. Can be write simple logic for timeout also.Conclusion: Logically both are doing same thing.
7. Non-Unique Properties

QTP: Smart Identification, Ordinal Identifier

Silktest: MultiTagingConclusion: Logically both are doing same thing. It is not recommended to enable theses option for robust automation.

Sunday

QTP - Terminate process , Close all browser

'************************************************' Killing the process By QTP'************************************************Killprocess ="EXCEL.EXE"Killprocess2 = "calc.exe"Killprocess3 = "mspaint.exe"Set ProcessList = GetObject("winmgmts://.").InstancesOf("win32_process")For Each Process In ProcessList If Process.Name = KillProcess Then Process.Terminate End IfIf Process.Name = KillProcess2 Then Process.Terminate End ifIf Process.Name = KillProcess3 Then Process.Terminate End ifNext
'************************************************'Closing all the Browser Locally'************************************************KillprocessIE ="IEXPLORE.EXE"Set ProcessList2 = GetObject("winmgmts://.").InstancesOf("win32_process")
For Each Process In ProcessList2 If Process.Name = KillProcessIE Then Process.Terminate End IfNext
While Browser("CreationTime:=0").Exist Browser("CreationTime:=0").CloseWend
'************************************************'Closing all the Browser by WBI Object remotely'************************************************'Alternatively WMI (Window management instrumentation ) object can be Used'sComp is IP of the remote machine
SystemUtil.Run "iexplore.exe"SystemUtil.Run "iexplore.exe"sComp="shukr02-xp"Set WMIobj = GetObject("winmgmts:\\" & sComp & "\root\cimv2") ' Find All the iexplore.exe processes Set IEExp = WMIobj.ExecQuery("Select * from Win32_Process Where Name = 'IEXPLORE.EXE'")
For Each IEx in IEExp IEx.Terminate()Next'************************************************'SystemUtil Object'************************************************SystemUtil.Run "iexplore.exe"SystemUtil.Run "iexplore.exe"NumberOfProcess = SystemUtil.CloseProcessByName("iexplore.exe")
'Check If Browser Exist and if the close it'SystemUtil.Run "iexplore.exe"SystemUtil.Run "iexplore.exe"While Browser("creationtime:=0").Exist(0) Browser("creationtime:=0").CloseWend'**********************************************

QTP Tip1: The first browser that opens receives the value "CreationTime" = 0, the second browser receives "CreationTime" = 1, and so on...QTP Tip2: To specify value of property in Descriptive Programming, please use ":=" operator.For example, "Title:=My application".Since we cannot know in advance - what browser will be selected and closed, we use its "age", i.e. "CreationTime" property. We decide, which browser should be closed, during the QTP script execution only.Let's return to above QTP script...
Browser("CreationTime:=0").Exist - it checks whether the first opened browser exists or not
If the browser exists, we close it - Browser("CreationTime:=0").Close - and repeat checkingLet's continue сomplicating our task:
How to close browsers by mask?For example, we have to close all browsers navigated to any Google's sites (URL contains 'google.com').In this case, QTP script will look like:
(Click the image to enlarge it)Using this QTP code, you can close dynamically browsers by mask.Please, note several useful QTP tips.QTP Tip3: To get browser's URL, use: GetROProperty("URL") function.For example, this line returns URL of the first opened browser:
Browser("CreationTime:=" & CreationTime).GetROProperty("URL")QTP Tip2: Analogously, to get browser's Title, use: GetROProperty("Title") function.
Browser("CreationTime:=" & CreationTime).GetROProperty("Title")

Thursday

Dictionary Object in QTP

Dictionary Object
Dictionary Object stores data key, item pairs. A Dictionary object stores the items in the array. Each item is associated with a unique key. The key is used to retrieve an individual item and is usually an integer or a string, but can be anything except an array.

Adavntages of using it in QTP:
1. can be used as Global variable declaration. so that any test can access the values from it in the run time.
2. You can store and retrive any number of run time values in to dictonary.
3. It is one of the Parameterization techique we can use in QTP

Disadvantages:
we can not specify the values in the desingn time like Datatable , Action parameters, environment variable.
So it is useful only in Run time , not design time
Methods:
Add Method
Adds a key and item pair to a Dictionary
object. object.Add (key, item)
Arguments
object Required. Always the name of a Dictionary object.
key Required. The key associated with the item being added.item Required.
The item associated with the key being added.
Remarks
An error occurs if the key already exists.
The following example illustrates the use of the Add method.
Dim d ‘ Create a variable.
Set d = CreateObject(”Scripting.Dictionary”)
d.Add “a”, “Athens” ‘ Add some keys and items.
d.Add “b”, “Belgrade”

Items Method
Returns an array containing all the items in a Dictionary object.
object.Items( )
Remarks The object is always the name of a Dictionary object.The following code illustrates use of the Items method:
Set d = CreateObject(”Scripting.Dictionary”)
d.Add “a”, “Athens” ‘ Add some keys and items.
d.Add “b”, “Belgrade”
a = d.Items ‘ Get the items.
For i = 0 To d.Count -1 ‘ Iterate the array.
s = s & a(i) & “
” ‘ Create return string.
Next
Msgbox s
Exists Method
Returns true if a specified key exists in the Dictionary object, false if it does not.
object.Exists(key)
Arguments
object Required. Always the name of a Dictionary object.
key Required. Key value being searched for in the Dictionary object.
Remarks
The following example illustrates the use of the Exists method.
Set d = CreateObject(”Scripting.Dictionary”)
d.Add “a”, “Athens” ‘ Add some keys and items.
d.Add “b”, “Belgrade”
If d.Exists(”c”) Then
Msgbox “Specified key exists.”
Else
Msgbox “Specified key doesn’t exist.”
End If
Keys Method
Returns an array containing all existing keys in a Dictionary object.
object.Keys( )
Remarks
The object is always the name of a Dictionary object.
The following code illustrates use of the Keys method:
Dim a, d, i ‘ Create some variables.
Set d = CreateObject(”Scripting.Dictionary”)
d.Add “a”, “Athens” ‘ Add some keys and items.
d.Add “b”, “Belgrade”
a = d.Keys ‘ Get the keys.
For i = 0 To d.Count -1 ‘ Iterate the array.
s = s & a(i) & “
” ‘ Return results.
Next
Msgbox s
Remove Method
Removes a key, item pair from a Dictionary object.
object.Remove(key)
Arguments
object Required. Always the name of a Dictionary object.
key Required. Key associated with the key, item pair you want to remove from the Dictionary object.
Remarks
An error occurs if the specified key, item pair does not exist.
The following code illustrates use of the Remove method:
Dim a, d ‘ Create some variables.
Set d = CreateObject(”Scripting.Dictionary”)
d.Add “a”, “Athens” ‘ Add some keys and items.
d.Add “b”, “Belgrade”
d.Add “c”, “Cairo” …
d.Remove(”b”) ‘ Remove second pair.
RemoveAll Method
The RemoveAll method removes all key, item pairs from a Dictionary object.
object.RemoveAll( )
Dim a, d, i ‘ Create some variables.
Set d = CreateObject(”Scripting.Dictionary”)
d.Add “a”, “Athens” ‘ Add some keys and items.
d.Add “b”, “Belgrade”
d.Add “c”, “Cairo” …
a = d.RemoveAll ‘ Clear the dictionary.

Example :
'Defining The Dictionary ObjectDim dict Set dict = CreateObject("Scripting.Dictionary")
'Add Methoddict.Add "Company", "Indian Railway" ' Adding keys and corresponding items.dict.Add "Tool", "QuickTest Pro"dict.Add "Website", "QTPDictionary"dict.Add "Country", "India" x= dict.CountmsgBox "Total Number of Object in dictionary:: " & x
'Exist MethodIf dict.Exists("Country") Thenmsg = "This is India."msgBox msgElsemsg = "India is not in a country list."End If
'Item Methodi = dict.Itemsk = dict.KeysFor x = 0 To dict.Count-1 'Iterate the array.msgbox i(x) & " :" & k(x)Next
'Remove dict.Remove("Website")
'Remove All
dict.RemoveAll

Wednesday

SendKey and QTP - Sending Keyboard Command

Please find the three ways to send the keyboard command to application.

Please find the script below and just run in QTP. It will invoke Notepad. It will put the time stamp, find the string in the text by these function.


'**********************************************************************************
''Start The Type/Send Key / Device Reply
'*********************************************************************************
' Open Notepad
SystemUtil.Run "notepad","","C:\Documents and Settings\shukr02",""

'**********************************************************************************
'Type Method Sending to Application
'**********************************************************************************
Window("Notepad").WinEditor("Edit").Type "This is Type Method Example"
Window("Notepad").WinEditor("Edit").Type micReturn
Window("Notepad").WinEditor("Edit").Type "We Will enter the Current Date from Menu > Edit > F5 Keyboard, The Date will come in Next line below:::"
Window("Notepad").WinEditor("Edit").Type micReturn
wait(1)
Window("Notepad").WinEditor("Edit").Type micF5

wait(2)
Window("Notepad").Close
Window("Notepad_2").Dialog("Notepad").WinButton("No").Click

'**********************************************************************************
''SendKey Methoid to Application
'**********************************************************************************
wait(2)
SystemUtil.Run "notepad","","C:\Documents and Settings\shukr02",""
Set WshShell = CreateObject("WScript.Shell")
WshShell.AppActivate("Untitled - Notepad")
WshShell.AppActivate "Notepad" ' Activate the browser window
Window("Notepad").WinEditor("Edit").Type "This is SendKey Example "
Window("Notepad").WinEditor("Edit").Type micReturn
Window("Notepad").WinEditor("Edit").Type "We are finding the word Opened by upword Searching and then cancling the findings"
Window("Notepad").WinEditor("Edit").Type micReturn
wait(3)
WshShell.SendKeys "^f"


wait(1)
Window("Notepad_2").Dialog("Find").WinRadioButton("Up").Set
Window("Notepad_2").Dialog("Find").WinEdit("Find what:").Set "opened"
Window("Notepad_2").Dialog("Find").WinButton("Find Next").Click
Wait(2)
Window("Notepad_2").Dialog("Find").WinButton("Cancel").Click
wait(2)
Window("Notepad").Close
Window("Notepad_2").Dialog("Notepad").WinButton("No").Click

'**********************************************************************************
'Device Reply Method to application using DeviceReplay.
'**********************************************************************************

Set obj = CreateObject("Mercury.DeviceReplay")
SystemUtil.Run "notepad","","C:\Documents and Settings\shukr02",""
Window("Notepad").Activate

Window("Notepad").WinEditor("Edit").Type "This is Device Reply Example"
Window("Notepad").WinEditor("Edit").Type micReturn
Window("Notepad").WinEditor("Edit").Type "We Will enter the Current Date from F5 hot Key, The Date will come in Next line below:::"
Window("Notepad").WinEditor("Edit").Type micReturn
wait(1)
obj.PressKey 63 '63 is the ASCII value for F5
Wait(2)
Window("Notepad").Close
Window("Notepad_2").Dialog("Notepad").WinButton("No").Click
'ASCII values for other keys: F1 - 59 F2 - 60 F3 - 61 F4 - 62 F5 - 63 F6 - 64 F7 - 65 F8 - 66 F9 - 67 F10 - 68 F11 - 87 F12 - 88
‘ For More Value see the http://www.lookuptables.com/
'**********************************************************************************
'End The Type/Send Key / Device Reply
'**********************************************************************************

You can use SendKeys to send more than one keystroke at a time. To do this, create a compound string argument that represents a sequence of keystrokes by appending each keystroke in the sequence to the one before it. For example, to send the keystrokes a, b, and c, you would send the string argument “abc”. The SendKeys method uses some characters as modifiers of characters (instead of using their face-values). This set of special characters consists of parentheses, brackets, braces, and the:
plus sign ”+”,
caret ”^”,
percent sign “%”,
and tilde ”~”
Send these characters by enclosing them within braces “{}”. For example, to send the plus sign, send the string argument “{+}”. Brackets “[ ]” have no special meaning when used with SendKeys, but you must enclose them within braces to accommodate applications that do give them a special meaning (for dynamic data exchange (DDE) for example).
To send bracket characters, send the string argument “{[}" for the left bracket and "{]}” for the right one.
To send brace characters, send the string argument “{{}” for the left brace and “{}}” for the right one.
Some keystrokes do not generate characters (such as ENTER and TAB). Some keystrokes represent actions (such as BACKSPACE and BREAK). To send these kinds of keystrokes, send the arguments shown in the following table:
Key
Argument
BACKSPACE
{BACKSPACE}, {BS}, or {BKSP}
BREAK
{BREAK}
CAPS LOCK
{CAPSLOCK}
DEL or DELETE
{DELETE} or {DEL}
DOWN ARROW
{DOWN}
END
{END}
ENTER
{ENTER} or ~
ESC
{ESC}
HELP
{HELP}
HOME
{HOME}
INS or INSERT
{INSERT} or {INS}
LEFT ARROW
{LEFT}
NUM LOCK
{NUMLOCK}
PAGE DOWN
{PGDN}
PAGE UP
{PGUP}
PRINT SCREEN
{PRTSC}
RIGHT ARROW
{RIGHT}
SCROLL LOCK
{SCROLLLOCK}
TAB
{TAB}
UP ARROW
{UP}
F1
{F1}
F2
{F2}
F3
{F3}
F4
{F4}
F5
{F5}
F6
{F6}
F7
{F7}
F8
{F8}
F9
{F9}
F10
{F10}
F11
{F11}
F12
{F12}
F13
{F13}
F14
{F14}
F15
{F15}
F16
{F16}
To send keyboard characters that are comprised of a regular keystroke in combination with a SHIFT, CTRL, or ALT, create a compound string argument that represents the keystroke combination. You do this by preceding the regular keystroke with one or more of the following special characters:
Key
Special Character
SHIFT
+
CTRL
^
ALT
%
Note When used this way, these special characters are not enclosed within a set of braces.
To specify that a combination of SHIFT, CTRL, and ALT should be held down while several other keys are pressed, create a compound string argument with the modified keystrokes enclosed in parentheses. For example, to send the keystroke combination that specifies that the SHIFT key is held down while:
e and c are pressed, send the string argument “+(ec)”.
e is pressed, followed by a lone c (with no SHIFT), send the string argument “+ec”.
You can use the SendKeys method to send a pattern of keystrokes that consists of a single keystroke pressed several times in a row. To do this, create a compound string argument that specifies the keystroke you want to repeat, followed by the number of times you want it repeated. You do this using a compound string argument of the form {keystroke number}. For example, to send the letter “x” ten times, you would send the string argument “{x 10}”. Be sure to include a space between keystroke and number.
Note The only keystroke pattern you can send is the kind that is comprised of a single keystroke pressed several times. For example, you can send “x” ten times, but you cannot do the same for “Ctrl+x”.
Note You cannot send the PRINT SCREEN key {PRTSC} to an application.