The following code examples explain how to use Ranorex API in order to write code modules or to extend recording modules with user specific code.
[TestModule("D451F1D1-C347-4B58-939F-F6187642EB56", ModuleType.UserCode, 1)]
public class UsingRepository : ITestModule
{
// Repository object to access UI elements
MyFirstTestProjectRepository repo = MyFirstTestProjectRepository.Instance;
/// <summary>
/// Constructs a new instance.
/// </summary>
public UsingRepository()
{
// Do not delete - a parameterless constructor is required!
}
void ITestModule.Run()
{
Mouse.DefaultMoveTime = 300;
Keyboard.DefaultKeyPressTime = 100;
Delay.SpeedFactor = 1.0;
// Using Ranorex.Form adapter represented by 'MyApp'
// 'MyApp' is used as a folder within the repository;
// the 'Self' property returns an object of type Ranorex.Form
// Activates application
repo.MyApp.Self.Activate();
// Log 'Active' state
Report.Info(repo.MyApp.Self.Active.ToString());
// Maximize, Minimize and Restore
repo.MyApp.Self.Maximize();
repo.MyApp.Self.Minimize();
repo.MyApp.Self.Restore();
// Closes application
repo.MyApp.Self.Close();
// Using Ranorex.Button adapter represented by 'ButtonAdd'
// Read and log value of 'Text' attribute
Report.Info(repo.MyApp.Buttons.ButtonAdd.Text);
// Press button
repo.MyApp.Buttons.ButtonAdd.Press();
// Read and log value of 'Enabled' attribute
Report.Info(repo.MyApp.Buttons.ButtonAdd.Enabled.ToString());
// Using Ranorex.RadioButton adapter
// represented by 'GenderOption'
// Select radio button
repo.MyApp.GenderOption.Select();
// Accessing listitems of Ranorex.List adapter
// represented by 'CategoryList'
IList<Ranorex.ListItem> listItems = repo.MyApp.CategoryList.Items;
foreach ( Ranorex.ListItem item in listItems )
{
Report.Info(item.Text + " is member of CategoryList");
}
// Using Ranorex.MenuItem to open 'File' menu
repo.MyApp.MenuItemFile.Select();
// Selecting sub menu item 'Connect'
repo.FileMenu.Connect.Select();
// Read and log 'Enabled' state of menu item 'Connect'
Report.Info(repo.FileMenu.Connect.Enabled.ToString());
}
}
Public Class UsingRepository Implements ITestModule ' Repository object to access UI elements Private repo As MyFirstTestProjectRepository = MyFirstTestProjectRepository.Instance ''' <summary> ''' Constructs a new instance. ''' </summary> ' Do not delete - a parameterless constructor is required! Public Sub New() End Sub ''' <summary> ''' Performs the playback of actions in this module. ''' </summary> ''' <remarks>You should not call this method directly, instead pass the module ''' instance to the <see cref="TestModuleRunner.Run(ITestModule)"/> method ''' that will in turn invoke this method.</remarks> Private Sub ITestModule_Run() Implements ITestModule.Run Mouse.DefaultMoveTime = 300 Keyboard.DefaultKeyPressTime = 100 Delay.SpeedFactor = 1.0 ' Using Ranorex.Form adapter represented by 'MyApp' ' 'MyApp' is used as a folder within the repository; ' the 'Self' property returns a Ranorex.Form object ' Activates application repo.MyApp.Self.Activate() ' Log 'Active' state Report.Info(repo.MyApp.Self.Active.ToString()) ' Maximize, Minimize and Restore repo.MyApp.Self.Maximize() repo.MyApp.Self.Minimize() repo.MyApp.Self.Restore() ' Closes application repo.MyApp.Self.Close() ' Using Ranorex.Button adapter represented by ButtonAdd' ' Read and log value of 'Text' attribute Report.Info(repo.MyApp.Buttons.ButtonAdd.Text) ' Press button repo.MyApp.Buttons.ButtonAdd.Press() ' Read and log value of 'Enabled' attribute Report.Info(repo.MyApp.Buttons.ButtonAdd.Enabled.ToString()) ' Using Ranorex.RadioButton adapter ' represented by 'GenderOption' ' Select radio button repo.MyApp.GenderOption.[Select]() ' Accessing listitems of Ranorex.List adapter ' represented by 'CategoryList' Dim listItems As IList(Of Ranorex.ListItem) = repo.MyApp.CategoryList.Items For Each item As Ranorex.ListItem In listItems Report.Info(item.Text & " is member of CategoryList") Next ' Using Ranorex.MenuItem to open 'File' menu repo.MyApp.MenuItemFile.[Select]() ' Selecting sub menu item 'Connect' repo.FileMenu.Connect.[Select]() ' Read and log 'Enabled' state of menu item 'Connect' Report.Info(repo.FileMenu.Connect.Enabled.ToString()) End Sub End Class
// Use the 'Info' object to check existence of the
// 'SaveDialog' item; Method 'Exists' uses the timeout
// specified for the 'SaveDialog' in the repository
Report.Info("Exists = " + repo.SaveDialog.SelfInfo.Exists().ToString());
// Use the 'Info' object to check existence of the
// 'TextOnline' item which uses the following RxPath:
// statusbar/text[@accessiblename='Online']
// This way you can wait with the timeout specified for
// the item within the repository for the text 'Online'
bool statusTextConnected = repo.MyApp.TextOnlineInfo.Exists();
// Using 'Info' objects for validation
// Throws a Ranorex.ValidationException if validation
// fails. Automatically reports success or failed message
// to log file
Validate.Exists(repo.SaveDialog.ButtonOKInfo);
// Validates the existance of the repository item,
// but does not throw any exception
Validate.Exists(repo.SaveDialog.ButtonOKInfo,"Check Object '{0}'",false);
' Use the 'Info' object to check existence of the
' 'SaveDialog' item; Method 'Exists' uses the timeout
' specified for the 'SaveDialog' in the repository
Report.Info("Exists = " & repo.SaveDialog.SelfInfo.Exists().ToString())
' Use the 'Info' object to check existence of the
' 'TextOnline' item which uses the following RxPath:
' statusbar/text[@accessiblename='Online']
' This way you can wait with the timeout specified for
' the item within the repository for the text 'Online'
Dim statusTextConnected As Boolean = repo.MyApp.TextOnlineInfo.Exists()
' Using 'Info' objects for validation
' Throws a Ranorex.ValidationException if validation
' fails. Automatically reports success or failed message
' to log file
Validate.Exists(repo.SaveDialog.ButtonOKInfo)
' Validates the existance of the repository item,
' but does not throw any exception
Validate.Exists(repo.SaveDialog.ButtonOKInfo, "Check Object '{0}'", False)
// Creating adapter of type 'NativeWindow' using the "...Info" object
Ranorex.NativeWindow nativeWnd = repo.MyApp.SelfInfo.CreateAdapter<Ranorex.NativeWindow>(false);
// ... and read value of attribute 'ProcessName'
Report.Info("Process name of VIP Database: " + nativeWnd.ProcessName);
// Using Control Adapter to access properties and methods of
// .NET WinForms control
Ranorex.Control winFormsControl = repo.MyApp.SelfInfo.CreateAdapter<Ranorex.Control>(false);
// Set background color of VIP application to Color.Black using the
// exposed property 'BackColor'
winFormsControl.SetPropertyValue("BackColor",Color.Black);
// Report screenshot after changing the background color
Report.Screenshot(repo.MyApp.Self);
// Closes VIP Database by invoking the 'Close' method
// exposed by the System.Windows.Forms.Form class
winFormsControl.InvokeMethod("Close");
' Creating adapter of type 'NativeWindow' using the "...Info" object
Dim nativeWnd As Ranorex.NativeWindow = repo.MyApp.SelfInfo.CreateAdapter(Of Ranorex.NativeWindow)(False)
' ... and read value of attribute 'ProcessName'
Report.Info("Process name of VIP Database: " & nativeWnd.ProcessName)
' Using Control Adapter to access properties and methods of
' .NET WinForms control
Dim winFormsControl As Ranorex.Control = repo.MyApp.SelfInfo.CreateAdapter(Of Ranorex.Control)(False)
' Set background color of VIP application to Color.Black using the
' exposed property 'BackColor'
winFormsControl.SetPropertyValue("BackColor", Color.Black)
' Report screenshot after changing the background color
Report.Screenshot(repo.MyApp.Self)
' Closes VIP Database by invoking the 'Close' method
' exposed by the System.Windows.Forms.Form class
winFormsControl.InvokeMethod("Close")
// Create a list of adapters using the "...Info" object
IList<Ranorex.Button> buttonList =
repo.MyApp.EnabledButtonsInfo.CreateAdapters<Ranorex.Button>();
// Move the mouse pointer to each button of the list
// and add a screenshot for each to the report
foreach (Ranorex.Button button in buttonList )
{
button.MoveTo();
Report.Screenshot(button);
}
' Create a list of adapters using the "...Info" object
Dim buttonList As IList(Of Ranorex.Button) =
repo.MyApp.EnabledButtonsInfo.CreateAdapters(Of Ranorex.Button)()
' Move the mouse pointer to each button of the list
' and add a screenshot for each to the report
For Each button As Ranorex.Button In buttonList
button.MoveTo()
Report.Screenshot(button)
Next
// Validate for Existence
// Using 'Info' objects for validation
// Throws a Ranorex.ValidationException if validation
// fails. Automatically reports success or failed message
// to log file
Validate.Exists(repo.SaveDialog.ButtonOKInfo);
// Validates the existance of the repository item,
// but does not throw any exception
bool exists = Validate.Exists(repo.SaveDialog.ButtonOKInfo,"Check Object '{0}'",false);
// Check whether an application form exists using a RanoreXPath
Validate.Exists("/form[@controlname='formVipApplication']");
// Check whether an application does not exists
// for the time specified as timeout for the given repository item
Validate.NotExists(repo.MyApp.SelfInfo);
// Validate 'Enabled' attribute of button 'Delete'
Validate.Attribute(repo.MyApp.Buttons.ButtonDeleteInfo,"Enabled",false);
' Validate for Existence
' Using 'Info' objects for validation
' Throws a Ranorex.ValidationException if validation
' fails. Automatically reports success or failed message
' to log file
Validate.Exists(repo.SaveDialog.ButtonOKInfo)
' Validates the existance of the repository item,
' but does not throw any exception
Dim existsn As Boolean = Validate.Exists(repo.SaveDialog.ButtonOKInfo,"Check Object '{0}'",false)
' Check whether an application form exists using a RanoreXPath
Validate.Exists("/form[@controlname='formVipApplication']")
' Check whether an application does not exists
' for the time specified as timeout for the given repository item
Validate.NotExists(repo.MyApp.SelfInfo)
' Validate 'Enabled' attribute of button 'Delete'
Validate.Attribute(repo.MyApp.Buttons.ButtonDeleteInfo,"Enabled",false)
Ranorex.Cell cellObject = null;
// Try to find a cell object using two
// different RanoreXPath expressions
bool found=false;
found = Host.Local.TryFindSingle<Ranorex.Cell>("/form//table/row/cell[3]", 2000, out cellObject);
found = Host.Local.TryFindSingle<Ranorex.Cell>("/form//table/row/cell[4]", 2000, out cellObject);
// If none of the expressions returns an object
// throw new 'ElementNotFoundException' and test case fails
if (!found)
{
throw new Ranorex.ElementNotFoundException("Both RanoreXPath with no return", null);
}
else
{
// If the value of attribte 'Text' does not equal to the expected value
// throw new 'ValidationException' to break the test case
if ( cellObject.Text == "MyExpectedTextValue" )
{
Report.Success("User Specific Validation","Text validation of cell object succeeded");
}
else
{
throw new Ranorex.ValidationException("Text validation of cell object succeeded failed");
}
}
Dim cellObject As Ranorex.Cell = Nothing
' Try to find a cell object using two
' different RanoreXPath expressions
Dim found As Boolean = Host.Local.TryFindSingle(Of Ranorex.Cell)("/form//table/row/cell[3]", 2000, cellObject)
found = Host.Local.TryFindSingle(Of Ranorex.Cell)("/form//table/row/cell[4]", 2000, cellObject)
' If none of the expressions returns an object
' throw new 'ElementNotFoundException' and test case fails
If Not found Then
Throw New Ranorex.ElementNotFoundException("Both RanoreXPath with no return", Nothing)
Else
' If the value of attribte 'Text' does not equal to the expected value
' throw new 'ValidationException' to break the test case
If cellObject.Text = "MyExpectedTextValue" Then
Report.Success("User Specific Validation", "Text validation of cell object succeeded")
Else
Throw New Ranorex.ValidationException("Text validation of cell object succeeded failed")
End If
End If
void ITestModule.Run()
{
Mouse.DefaultMoveTime = 300;
Keyboard.DefaultKeyPressTime = 100;
Delay.SpeedFactor = 1.0;
}
Private Sub ITestModule_Run() Implements ITestModule.Run
Mouse.DefaultMoveTime = 300
Keyboard.DefaultKeyPressTime = 100
Delay.SpeedFactor = 1.0
End Sub
// ----------------- Code Block used by Code Module A ----------------- // Click 'Save' button to open 'SaveDialog' repo.MyApp.Buttons.ButtonSave.Click(); // Read text message shown with 'SaveDialog' // and assign it to test case parameter 'DialogText' TestCase.Current.DataContext.Parameters["DialogText"] = repo.SaveDialog.TextMessage.TextValue; // -------- Code Block used by User Code Action of recording B -------- // Read value of 'DialogText' paramaeter in other code module // or recording module using a user code action Report.Info(TestCase.Current.DataContext.Parameters["DialogText"]); // Get the current data context and log // the current row index of a data driven run Report.Info(TestCase.Current.DataContext.CurrentRow.ToString());
' ----------------- Code Block used by Code Module A -----------------
' Click 'Save' button to open 'SaveDialog'
repo.MyApp.Buttons.ButtonSave.Click()
' Read text message shown with 'SaveDialog'
' and assign it to test case parameter 'DialogText'
TestCase.Current.DataContext.Parameters("DialogText") = repo.SaveDialog.TextMessage.TextValue
' Read value of 'DialogText' paramaeter in other code module
' or recording module using a user code action
Report.Info(TestCase.Current.DataContext.Parameters("DialogText"))
' Get the current data context and log
' the current row index of a data driven run
Report.Info(TestCase.Current.DataContext.CurrentRow.ToString())
' -------- Code Block used by User Code Action of recording B --------
' Read value of 'DialogText' paramaeter in other code module
' or recording module using a user code action
Report.Info(TestCase.Current.Parameters("DialogText"))
' Get the current data context and log
' the current row index of a data driven run
Report.Info(TestCase.Current.DataContext.CurrentRow.ToString())
// Create Ranorex.Button adapter using 'FindSingle' method
// from Host.Local (starting at root node) with absolute RanoreXPath
// Note: ElementNotFound exception is thrown if item is not found within
// the specified timeout of 2000 ms.
Ranorex.Button addButtonVar1 = Host.Local.FindSingle<Ranorex.Button>("/form[@controlname='formVipApplication']/button[@controlname='btAdd']",2000);
addButtonVar1.MoveTo();
// Alternatively you can use the 'TryFindSingle' method to prevent
// a test case from failing because of an exception thrown if
// the element is not found within the specified timeout of 2000 ms
Ranorex.Button addButtonVar2 = null;
bool found = Host.Local.TryFindSingle<Ranorex.Button>("/form[@controlname='formVipApplication']/button[@controlname='btAdd']", 2000, out addButtonVar2);
// Move mouse pointer to button
addButtonVar2.MoveTo();
// Request a list of buttons shown from the VIP Database application
// and create a screenshot for each button in the report file
IList<Ranorex.Button> buttonList = Host.Local.Find<Ranorex.Button>("/form[@controlname='formVipApplication']/button",500);
foreach (Ranorex.Button bt in buttonList)
{
Report.Screenshot(bt);
}
// Using find methods in combination with existing Ranorex repository items
Ranorex.Button btAdd = repo.MyApp.Self.FindSingle<Ranorex.Button>("button[@controlname='btAdd']",2000);
' Create Ranorex.Button adapter using 'FindSingle' method
' from Host.Local (starting at root node) with absolute RanoreXPath
' Note: ElementNotFound exception is thrown if item is not found within
' the specified timeout of 2000 ms.
Dim addButtonVar1 As Ranorex.Button = Host.Local.FindSingle(Of Ranorex.Button)("/form[@controlname='formVipApplication']/button[@controlname='btAdd']", 2000)
addButtonVar1.MoveTo()
' Alternatively you can use 'TryFindSingle' method to prevent
' a test case from failing because of an exception thrown if
' the element is not found within the specified timeout of 2000 ms
Dim addButtonVar2 As Ranorex.Button = Nothing
Dim found As Boolean = Host.Local.TryFindSingle(Of Ranorex.Button)("/form[@controlname='formVipApplication']/button[@controlname='btAdd']", 2000, addButtonVar2)
' Move mouse pointer to button
addButtonVar2.MoveTo()
' Request a list of buttons from the VIP Database application
' and create a screenshot for each button in the report file
Dim buttonList As IList(Of Ranorex.Button) = Host.Local.Find(Of Ranorex.Button)("/form[@controlname='formVipApplication']/button", 500)
For Each bt As Ranorex.Button In buttonList
Report.Screenshot(bt)
Next
' Using find methods in combination with existing Ranorex repository items
Dim btAdd As Ranorex.Button = repo.MyApp.Self.FindSingle(Of Ranorex.Button)("button[@controlname='btAdd']", 2000)
// Create bitmap to search for
// within application form and
// click it
Bitmap bmp = Ranorex.Imaging.Load(
@"..\..\Green Sea Turtle Small.bmp");
// Performs a right click on the image found
// within the application window based on
// the image location
myRepo.WinFormsApp.Self.Click(MouseButtons.Right,bmp);
// You can also search for images that are slightly different to the
// loaded image by specifying the minimum Similarity for a match (95% = 0.95).
myRepo.WinFormsApp.Self.Click(new Location(bmp, new Imaging.FindOptions(0.95)));
// OR Set the default Similarity value for all following image operations
Imaging.FindOptions.Default.Similarity = 0.95;
myRepo.WinFormsApp.Self.Click(bmp);
Report.Success("Image found and clicked successfully");
' Create bitmap to search for
' within application form and
' click it
Dim bmp As Bitmap = Ranorex.Imaging.Load("..\..\Green Sea Turtle Small.bmp")
' Performs a right click on the image found
' within the application window based
' on the image location
myRepo.WinFormsApp.Self.Click(MouseButtons.Right, bmp)
' You can also search for images that are slightly different to the
' loaded image by specifying the minimum Similarity for a match (95% = 0.95).
myRepo.WinFormsApp.Self.Click(new Location(bmp, new Imaging.FindOptions(0.95)))
' OR Set the default Similarity value for all following image operations
Imaging.FindOptions.Default.Similarity = 0.95
myRepo.WinFormsApp.Self.Click(bmp)
Report.Success("Image displayed successfully")
// Create bitmap
Bitmap bmp = Ranorex.Imaging.Load(
@"..\..\Green Sea Turtle Small.bmp");
// Search for it within the application window
if (Ranorex.Imaging.Contains(myRepo.WinFormsApp.Self,bmp) == true)
{
Report.Success("Image found within WinForms application");
}
' Create bitmap
Dim bmp As Bitmap = Ranorex.Imaging.Load("..\..\Green Sea Turtle Small.bmp")
' Search for it within the application window
If Imaging.Contains(myRepo.WinFormsApp.Self,bmp Then
Report.Success("Image found within WinForms application")
End If
Note: Both examples load an uncompressed file (BMP or PNG format) in order to carry out a one-to-one comparison. Use the FindOptions class to configure similarity, preprocessing and other search settings.
Form optionsDialog = "/form[@title='Folder Options']";
Tree settingsTree = optionsDialog.FindSingle<Ranorex.Tree>
("container[@caption='View']/tree[@controlid='30120']");
foreach (TreeItem item in settingsTree.Items)
{
IterateTree(item);
}
static void IterateTree(Ranorex.TreeItem treeItem)
{
foreach (Ranorex.TreeItem item in treeItem.Items)
{
item.Click();
CheckForWarningDialog();
Thread.Sleep(100);
if (item.Items.Count > 0)
{
IterateTree(item);
}
item.Click();
CheckForWarningDialog();
}
}
// Some mouse clicks causes a warning dialog to popup
// which has to be handled and closed
static void CheckForWarningDialog()
{
Ranorex.Button button=null;
if (Host.Local.TryFindSingle("/form[@title='Warning']/button[@text='&No']", 1000, out button))
button.Click();
}
Dim optionsDialog As Form = "/form[@title='Folder Options']"
Dim settingsTree As Tree = optionsDialog.FindSingle(Of Ranorex.Tree)("container[@caption='View']/tree[@controlid='30120']")
For Each item As TreeItem In settingsTree.Items
IterateTree(item)
Next
Private Shared Sub IterateTree(treeItem As Ranorex.TreeItem)
For Each item As Ranorex.TreeItem In treeItem.Items
item.Click()
CheckForWarningDialog()
Thread.Sleep(100)
If item.Items.Count > 0 Then
IterateTree(item)
End If
item.Click()
CheckForWarningDialog()
Next
End Sub
' Some mouse clicks causes a warning dialog to popup
' which has to be handled and closed
Private Shared Sub CheckForWarningDialog()
Dim button As Ranorex.Button = Nothing
If Host.Local.TryFindSingle("/form[@title='Warning']/button[@text='&No']", 1000, button) Then
button.Click()
End If
End Sub
Online User Guide
download as: PDF (20.3MB)
Ranorex Tutorial
(PDF file, 13.5MB)