Thursday, June 27, 2013

QTP Real Time Issues


  1. I want to arrange "12789567899012" values in ascending ?
         Sol:

             str="12789567899012"
                  For intx=1 to len(str)
                       Redim preserve strarr(intx)
                       strarr(intx)= Mid(str,intx,1)
                 next
                For intx=Ubound(strarr)-1 to Lbound(strarr) step-1
                      for jntx=Lbound(strarr) to intx
                            If strarr(jntx) > strarr(jntx+1) then
                               temp=strarr(jntx+1)
                                strarr(jntx+1)=strarr(jntx)
                                 strarr(jntx)=temp
                            End IF
                      next      
                 Next
              msgbox Join(strarr)
   
    2. How to create a function which can generates a Unique Cause ID number
         upperbound=10000
         lowerbound=100
              Function randomnumber(upperbound,lowerbound)
                           Randomize
                           randomvalue = CInt(Int((upperbound - lowerbound + 1) * Rnd() + lowerbound))
                           randomnumber=randomvalue
             End Function

               msgbox randomnumber(upperbound,lowerbound)

3.How to find CPU and Memory Usage using QTP? By Uday Kumar
How to find out CPU utilization and Memory usage as displayed in the Windows Task Manager.


strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")

'Get the CPU utilization %
myQuery = "SELECT * FROM Win32_PerfFormattedData_PerfOS_Processor WHERE Name = '_Total'"
For Each objItem in objWMIService.ExecQuery(myQuery)
   msgbox "Processor time " & objItem.PercentProcessorTime & "  %"
next

'Get the total Physical Memory
myQuery="Select * from Win32_ComputerSystem"
Set colItems = objWMIService.ExecQuery(myQuery)
For each objitem in colItems
    msgbox "Total Physical Memory "&objitem.TotalPhysicalMemory/1024
Next

'Get the total available physical memory
myQuery="Select * from Win32_PerfFormattedData_PerfOS_Memory"
Set colItems = objWMIService.ExecQuery(myQuery)
For Each objItem in colItems
    msgbox "Available GB: " & objItem.AvailableKBytes
Next


4.How to execute QTP scripts in a remote machine when the window is minimized? By Uday Kumar

QTP Version : 11 or later
RDP Version : 6 or later

If you want to run QTP scripts run on a remote machine and if that Remote machine/Window is minimized, then the scripts will fail.

In order to overcome the issue, you need to add a registry key in Windows registry on your client machine/from the machine where you initiating the remote desktop.
1. Close all your remote desktops.
2. Create a registry "RemoteDesktop_SuppressWhenMinimized" if does not exist in the below path:
   HKEY_CURRENT_USER\Software\Microsoft\Terminal ServerClient\RemoteDesktop_SuppressWhenMinimized
   or
   HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Terminal Server Client\RemoteDesktop_SuppressWhenMinimized
3. Set the value for this data to 2.

If you would like to add the registry key by just running a .reg file follow below steps:
1. Open Notepad.
2. Cope the below content:
 Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\Software\Microsoft\Terminal ServerClient\RemoteDesktop_SuppressWhenMinimized]
"RemoteDesktop_SuppressWhenMinimized"=dword:00000002

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Terminal Server Client\RemoteDesktop_SuppressWhenMinimized]
"RemoteDesktop_SuppressWhenMinimized"=dword:00000002
3. Save the file as "FileName.reg" format
4. Now, double click on this reg file, so that registry keys will be added.
5.How to get QTP Results in a HTML file?
Once we ran our Regression suite, it is handy if the results are displayed in HTML File, it is easy for us to understand at the same time also easy for the management(Lead/Manager/Customer) to look at it.

They will not show any interest if you zip your QTP Result folders and send it to them.

And for many reasons it is handy if the results are displayed in HTML File, right? How can we get the results in HTML File.

But how can we view results in HTML File?

By changing one registry setting, we have get QTP results in a HTML File.

Open windows registry by entering regedit and clicking enter in Windows run.

HKLM\Software\MercuryInteractive\QuickTestProfessional\Logger\Media\Log

Double click on "Active"

Change the value from 0 to 1.

Restart QTP. 

Now run your QTP Test and see results in the QTP Test folder, where you see a "Log" folder.

In this folder you will see a file called LogFile.html which is the HTML Report.
6.How to check the website you are testing is up and running? By Uday kumar
We can check the website up and running by just pinging the website.

You can do that in couple of ways.

Here is the simplest way to  ping a website.

Appraoch1:

strWebSiteName="www.yahoo.com"
strQuery = "SELECT * FROM Win32_PingStatus WHERE Address = '" & strWebSiteName & "'"
bFlag = False

Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
Set objItems = objWMIService.ExecQuery( strQuery )

For Each objItem In objItems
       If objItem.StatusCode = 0 Then
            bFlag = True
            Exit For
        Else
            bFlag = False
        End If
Next

If bFlag = true Then
    print "Website is avilable"
else
    print "Website not avilable"
End If

Set objItems = Nothing
Set objWMIService = Nothing

Appraoch2:
Set oNetwork = DotNetFactory( "Microsoft.VisualBasic.Devices.Network" ,"Microsoft.VisualBasic")
bFlag=oNetwork.ping(strWebSiteName)
If bFlag Then
  print  "Website is avilable" 
Else
   print  "Website not avilable" 
End If
Set oNetwork=nothing
7.How to check a browser window is minimized? By Uday Kumar
Extern.Declare micLong, "GetMainWindow", "user32" ,"GetAncestor",micLong, micLong 'This is the declaration for the referencing "GetMainWindow" with the GetAncestor method in user32.dll.
GA_ROOT=2

Just opened Gmail and checked whether the browser is minimized or maximized.

We cannot directly use Browser().GetROProperty("minimized") here.


Set oBrowser=description.Create
oBrowser("micclass").value="Browser"
oBrowser("name").value="Gmail.*"

hwnd=Browser(oBrowser).GetROProperty("hwnd")

hwnd = Extern.GetMainWindow(hwnd , GA_ROOT)
msgbox Window("hwnd:=" & hwnd ).GetROProperty("minimized") 

The above code returns False if the Tab/browser is maximized else
returns True if the Tab/browser is minimized

The above code worked well with QTP and IE 7.
8.How to activate, minimize, maximize a browser using QTP? By Uday Kumar
You can use below code to active, minimize, maximize a browser. I put all these three methods in a single function, but you need to tweek this code as per your needs.

Function WinActivate(Object)
   Dim hWnd
    hWnd = Object.GetROProperty("hwnd") 'First get the window handle
    On Error Resume Next
    Window("hwnd:=" & hWnd).Activate 'Put fouse on the window
    If Err.Number <> 0 Then
            hWnd=Browser("hwnd:=" & hWnd).Object.hWnd 'now get the browser handle
            Window("hwnd:=" & hWnd).Activate  
            'Window("hwnd:=" & hWnd).minimize 'To minimize the browser
            'Window("hwnd:=" & hWnd).maximize
            Err.Clear
    End If
    On Error Goto 0
End Function

RegisterUserFunc "Browser","Activate","WinActivate"
RegisterUserFunc "Browser","Minimize","WinMinimize"
RegisterUserFunc "Browser","Maximize","WinMaximize"

Browser(objBrowser).Activate
Browser(objBrowser).Minimize
Browser(objBrowser).Maximize
9.IE scripts are failing or Objects are not recognized in IE.? By Uday Kumar
Scripts are failing when IE is upgraded.
User has scripts developed in IE 6 and they worked fine.
But user updated his IE to IE7, then the scripts which worked earlier are failing now in IE 7.

Reasons could be:
BHOManager add-in could be disabled in IE7.
This add-in is needed for QTP to interact with IE.
Enable this Add-in by:
Open IE -> Tools Menu -> Manage Add-ons -> Enable or Disable add-ons -> Select BHOManager Class
Check whether the add-on is enabled or not. It should be enabled.

Objects are properly recognized in IE 7, but not recognized in IE 8.
Reason could be: Protected mode in IE 8.
Check the above solution, then follow to disable the protected mode in IE.
Open IE -> Tools Menu -> Internet Options -> Security Tab -> Uncheck "Enable Protected Mode" check box.
10.Working with Dictionary Object? By Uday Kumar
Set dictObj=Createobject("Scripting.Dictionary")
dictObj.Add "1","One"
dictObj.Add "2","Two"
dictObj.Add 3,"Three" 'Observe here i am passing key as a integer meaning we can pass different types as Key

msgbox dictObj.Count 'This method returns the number of keys

If dictObj.Exists(3) Then 'This method looks for the Key
msgbox "Key exists"
else
msgbox "Key does not exist"
End If

a=dictObj.Keys 'This method assigns all the keys to an array
For i=1 to dictObj.Count
msgbox dictObj.Item(a(i-1)) 'This method retrieves the value of the key
Next
11.Maximum no. of actions can be created:
From QTP 9.0(or later) max of 120 actions can be created. We can extend this by installing private patch.
From QTP 8.2(or below) max of 255 actions can be created.

12.How to find which version of vbscript you are using?
Search for vbscript.dll in c:\windows\system32. In properties -> Version tab
Programatically we can retrieve this by:
msgbox ScriptEngineMajorVersion &"."& ScriptEngineMinorVersion

13.Associating function library Vs executefile
Use to associate functional libraries to a test rather than using execute file.
By associating functional library, all actions in the test can access those functions.
By calling executefile, all functions are loaded in the calling action only.

14.Recovery Scenario Vs On Error Resume Next
Recovery scenarios can be used when we dont know where an error arises.
We can use On Error Resume Next when we know the occurance of an error and we dont want to halt the execution because of that error.

15.Loading function library at run-time
From QTP 11 onwards we can use "LoadFunctionLibrary" statement to load Function library at run-time.
We can load multiple functional libraries in a single call like
LoadFunctionLibrary "c:\flb1","c:\flb2" etc...

16.Generating Random number
Generating a random number between min and max.
Syntax is: Int((max-min+1)*Rnd +min)
The below example generates a random number between 10 to 50 in each iteration
For i=1 to 5
msgbox Int((50-10+1)*Rnd +10)
Next

17.Arrays with redim
Small example with arrays and redim preserve
a=Array(5,2,50,33,21)
For i=0 to ubound(a)
msgbox a(i)
Next
ReDim preserve a(7)
a(5)=10
a(6)=20
For i=0 to ubound(a)-1
msgbox a(i)
Next
18.Work with command prompt using QTP(vbscript)
We can use Windows Shell object to start a command prompt and execute the command.

In the following i want to list all files\folders in C drive:
Set wscriptObj=createobject("WScript.Shell")
wscriptObj.Run "cmd /K cd c:\ & dir"

When I execute the above statement, it opens the command prompt and execute dir command. You are free to use any command you want as per your needs.
19.Different ways to invoke a IE browser
'commonly used method
systemutil.Run "iexplore.exe"
wait(10)
Browser("name:=.*").Navigate "www.yahoo.com"

'For QTP backward compatability
invokeapplication "C:\Program Files\Internet Explorer\iexplore.exe http://www.yahoo.com"

Set WShelObj=Createobject("WScript.Shell")
WShelObj.Run Chr(34) & "C:\Program Files\Internet Explorer\iexplore.exe" & Chr(34)&" "&"www.yahoo.com"
or
Set WShelObj=Createobject("WScript.Shell")
WShelObj.Run Chr(34) & "C:\Program Files\Internet Explorer\iexplore.exe" & Chr(34)
Browser("name:=.*").Navigate "www.yahoo.com"
Char(34) is used to append double quotes to the IE application path.
20.VB Script to find the number of occurences of a char in a string
Method 1:
str="Hello world"
Set regex=new RegExp
regex.pattern="l"
regex.global=true
Set matches=regex.execute(str)
msgbox matches.count

Method 2:
arr=split(str,"l")
msgbox ubound(arr)

Method 3:
counter=0
For i=1 to len(str)
char=mid(str,i,1)
If char="l" Then
counter=counter+1
End If
Next

msgbox counter
21.How to print the first digit of the numbers?
When i input a number, my result omit the first digit and display the remaining numbers ex: if my input is 4321, it should print 4321, 321, 21, 1.

no=4321
While no>=1
msgbox no
noi=len(no)
div=divVal(noi-1)
no=no mod div
Wend

Function divVal(x)
val=1
For i=1 to x
val=val*10
Next
divVal=val
End Function

If you dont bother of type casting, you can also use:
no=cstr("4321")
for i=1 to len(no)
counter=0
msgbox mid(no,i,len(no)-counter)
counter=counter+1
next
22.Script to reverse a number in vbscript
num=inputbox("Enter a number")
result=0
While num>0
digit=num mod 10
num=int(num/10)
result=result*10+digit
Wend
msgbox result
23.How to find the number of rows and columns used in an Excel sheet
strFilePath="D:\EmpDetails.xls"
Dim fileSysObj
Set xlObj=createobject("Excel.application")
Set xlWorkBookObj=xlObj.workbooks.open(strFilePath)
Set xlWorkSheetObj=xlWorkBookObj.worksheets(1)

intRowCount=xlWorkSheetObj.UsedRange.rows.count 'intRowCount=xlWorkSheetObj.rows.count - it returns the number of rown in an Excel sheet

intColCount=xlWorkSheetObj.UsedRange.columns.count 
' intColCount=xlWorkSheetObj.columns.count - it returns the number of columns in an Excel sheet 

msgbox "No. of rows used "&intRowCount&" and No. of columns used. "&intColCount

xlWorkBookObj.close
xlObj.application.quit

Set xlObj=nothing
Set xlWorkBookObj=nothing
Set xlWorkSheetObj=nothing


24.How to count the no.of characters repeated in a given string using regular expression?
Dim reRegExp 
str="BARBARICB"
 Set reRegExp = New RegExp
 With reRegExp
     .Global = True
     .Pattern = "B"
 Set Regcount = .Execute(str)
 End With

msgbox Regcount.count
 
               or
str="BARBARICB"
For i=1 to Len(str)
M=mid(str,i,1)
set r=new regexp
r.pattern="B"
r.global=true
If r.test(M) then
tmp=tmp+1
End If
Next
Msgbox tmp

25)How to print the each word of string in Reverse order using vb scripting.str="character/share/bangalore/chennai/trap"
NewStr = split(str,"/")
for i = lbound(NewStr) to ubound(NewStr)
 temp = strreverse(NewStr(i))
 RevedStr = RevedStr + "/" + temp
Next
Msgbox RevedStr &"    "& str 

26)How to find Length of String without using String
Str = "My Name is Ravi"
count=1
While (Mid(Str,count,1)<>"")
count=count+1   
Wend
msgbox count-1

27) I have 10 links names. I want to check the link font color for each link and if link color = red, then click on that
U can follow both approaches. Either using OR/DP
Let me show you both methods:
Method 1: Using OR

I here assume that all the links are present on the same page.
msgbox  = Browser("").Page("").link("").getroproperty("color")
repeat the same for all 10 links .This will return you a value in hexadecimal value.
Compare the value and get the color of link.
for example 0000ff is the value for blue link.

Method 2:Using Descriptive Programming

Function ClickLink(LinkName)
Set oLink = Description.Create()
oLink("micclass").Value = "Link"
oLink("name").Value = LinkName
Set collection = browser("").page("").Childobjects(oLink)
For i = 0 to collection.count -1
       ColorValue = collection(i).GetROProperty("color")
       if StrComp(ColorValue,"ff0000") = 0 then
          collection(i).Click
          exit For
       End If
next

End Function
28) How should we scroll down, up, right and left operations on a webpage using QTP.
Let me put a scenario before you which can help you understand.
Scenario : I assume you want to scroll down a webpage.
Answer:
You can use WSH Object and sendkeys method provided by QTP.
Use following code.
Browser("Citibank India Home").Page("Citibank India Home").Highlight
Set objShell=CreateObject("WScript.Shell")
objShell.SendKeys "{PGUP}"
objShell.SendKeys "{PGDN}"
objShell.SendKeys "{END}"

This will scroll up/down your page.
Else

If you want to scroll a webtable then use Object.Fireevent "onmousedown" property in qtp.

29) Script to find the len of the given string without using the Len(Str)  function
Option  Explicit
Dim Str
Str = Inputbox ( "Enter the String with spaces")
Msgbox   "The entered string is:" & Str
Call LenOfString(Str)

Function LenOfString( Byref Str)
                Dim  cnt , sum , ubund, inx, sStr, Temp , Totlenofstr , sArry , sMid
     cnt = 1
     sum = 0
    sArry = Split( Str , " ")
     ubund = Ubound(sArry)
     If ubund >= 0Then
         For inx = 0 To ubund
               Do
                  sStr = sArry(inx)
                 sMid = sMid & Mid(sStr , cnt , 1)
                  cnt = cnt+1
               Loop  While (sStr <> sMid)
            Temp = cnt - 1
              sum =   sum+ Temp
              cnt = 1
             sMid =  Empty
                                            If inx > ubund Then
                                                   Exit  For
                                              End If
                                    Next
                                                    Totlenofstr =   sum+ ubund
             MsgBox   "The Length Of string without using the inbuilt function Len(Str):"   & Totlenofstr 
                End If
 End Function

 ' To check whether  the length  of   string is correct or wrong  use the  Inbuilt  function   Len
Msgbox  " The Length of the given string using Inbuilt function Len(Str) : " & Len(Str)

30) How to check number of capital letters in string?
stra =Inputbox("string")
patt="[A-Z]"
Set a=new Regexp
      a.ignorecase=false
      a.global=true
      a.pattern=patt
set b=a.execute(stra)
      l=b.count
 msgbox l
 msgbox stra