Ranorex Help Center How can we help you?

User Code Actions

A user code action is used in situations where standard out-of-the-box features provided by the recorder are not enough. Here are some examples where user code actions could be convenient.

  • User-specific Validation
  • Accessing test case related data and parameters
  • Extended reporting

Looking at a recording file in the project's view you will see that each recording has two associated code files.

Recording 'AddEntry' has two code file items

Recording 'AddEntry' has two code file items


Note User code actions are not available within the standalone Recorder.


Within Ranorex Studio, each recording manages two types of source code files:

  • Automatically generated main recording source code file
    <RecordingName>.<CodeFileExtension>
  • User specific source code file <RecordingName>.UserCode.<CodeFileExtension>

You can jump to the generated code of a recorded action by right-clicking the action and choosing 'View Code' from the context menu. Alternatively you might use the shortcut <CTRL> + <ENTER> to achieve the same as with the context menu.


Jump to generated code of a recorded action

Jump to generated code of a recorded action

Every time you change and save a recording, the main code file 'AddEntry.cs' is newly generated. Any change of code should always be made within the recording's UserCode.cs file.

Create User Code Actions

You can create user specific code actions by converting existing items or by adding a new 'Usercode' action item via the toolbar button 'Add New Action'.


Convert an existing action item to a code action

Convert an existing action item to a code action


Specify method name used for user code item

Specify method name used for user code item


Use the context menu item 'View Code' to jump into the code

Use the context menu item 'View Code' to jump into the code


After the creation of a new user code action within the actions table, a new method is added to the partial class of the recording. If you're converting an existing action item, the code generated for the main recording file is transferred to the new user code method.

namespace MyFirstTestProject  
{  
    public partial class AddEntry  
    {  
        /// <summary>  
        /// This method gets called right after the recording has been started.  
        /// It can be used to execute recording specific initialization code.  
        /// </summary>  
        private void Init()  
        {  
            // Your recording specific initialization code goes here.  
        }  
  
        public void ClickOnPasswordField()  
        {  
            Report.Log(ReportLevel.Info, "Mouse", "Mouse Left Click item 'FormAdd_Entry.TabPageList.InputFields.TextPassword' at 175;9.", repo.FormAdd_Entry.TabPageList.InputFields.TextPasswordInfo);  
            repo.FormAdd_Entry.TabPageList.InputFields.TextPassword.Click("175;9");  
        }  
  
    }  
}  
Namespace MyFirstTestProject  
    Public Partial Class AddEntry  
        ''' <summary>  
        ''' This method gets called right after the recording has been started.  
        ''' It can be used to execute recording specific initialization code.  
        ''' </summary>  
        Private Sub Init()  
            ' Your recording specific initialization code goes here.  
        End Sub  
  
        Public Sub ClickOnPasswordField()  
            Report.Log(ReportLevel.Info, "Mouse", "Mouse Left Click item 'FormAdd_Entry.TabPageList.InputFields.TextPassword' at 175;9.", repo.FormAdd_Entry.TabPageList.InputFields.TextPasswordInfo)  
            repo.FormAdd_Entry.TabPageList.InputFields.TextPassword.Click("175;9")  
        End Sub  
  
    End Class  
End Namespace

User Code Actions and Parameters


With Ranorex it is possible to use parameters for user code actions. You can pass arguments with different types to your user code methods to gain more flexibility in your testing environment. 

Next to passing different types of values it is also possible to pass repository items to user code actions. This enables e.g. combining several actions on one UI object or building up a generic library of smart actions independent of the underlying technology to only name some of the potential applications.

To use parameters for a new user code action, click the 'Args' button next to the method's cell to open the Argument Editor.


Open the Argument Editor

Open the Argument Editor


By pressing the 'Add' button, you can choose the type of the argument you are going to pass to the user code action.
Add argument

Add argument


After adding a new argument, you can edit its properties. To enhance flexibility, you can use variables instead of hardcoded values.
Edit properties of the argument

Edit properties of the argument



After declaring the parameters with values or variables, you can switch to the user code method and use the passed parameters..

public void AddEntryWithParams(string aTitle, string aUsername, string aPassword, string aURL)  
{  
    // Set text fields  
    repo.PwEntryForm.Text.TextValue = aTitle;  
    repo.PwEntryForm.UserName.TextValue = aUsername;  
    repo.PwEntryForm.Password.TextValue = aPassword;  
    repo.PwEntryForm.Repeat.TextValue = aPassword;  
    repo.PwEntryForm.URL.TextValue = aURL;  
}
Public Sub AddEntryWithParams(aTitle As String, aUsername As String, aPassword As String, aURL As String)  
    ' Set text fields  
    repo.PwEntryForm.Title.TextValue = aTitle  
    repo.PwEntryForm.UserName.TextValue = aUsername  
    repo.PwEntryForm.Password.TextValue = aPassword  
    repo.PwEntryForm.Repeat.TextValue = aPassword  
    repo.PwEntryForm.URL.TextValue = aURL  
End Sub



You can bind the return value of a user code method by setting the option 'Return Value Variable' in the properties pane.

Additionally to creating method calls in Ranorex Recorder you are able to define your methods in code and just select the intended method in the Recorder Table. Here you are also able to choose overloaded methods.


Choose one of the overloaded method calls

Choose one of the overloaded method calls


Ranorex Argument Editor with arguments and variable binding from overloaded method

Ranorex Argument Editor with arguments and variable binding from overloaded method


As mentioned above it also is possible to pass repository items to user code actions. This can be accomplished by either choosing the argument type 'Adapter' or 'RepoItemInfo', when adding arguments using the Argument Editor.

After defining the repository item arguments, they can simply be bound to repository items the same way as any other action in the actions table by selecting them in the action table or dragging and dropping them from the repository.


Repository item as argument for a user code action

Repository item as argument for a user code action


After declaring the parameters with repository items, values or variables, you can switch to the user code method and use the passed parameters.

The following example simulates a keyboard input to the given repository item using the given string value. Followed by a validation whether the text value attribute of the given repository equals the given string value. After that a screenshot of the current state of the UI element represented by the repository item will be reported.


public void SetAndValidateTextValue(Ranorex.Adapter repoitem, string val)  
{  
    Keyboard.Press(repoitem, val);  
    Validate.AreEqual(repoitem.As<Ranorex.Text>().TextValue, val);  
    Report.Screenshot(repoitem, true);  
}
Public Sub SetAndValidateTextValue(repoitem As Ranorex.Adapter, val As String)  
    Keyboard.Press(repoitem, val)  
    Validate.AreEqual(repoitem.[As](Of Ranorex.Text)().TextValue, val)  
    Report.Screenshot(repoitem, True)  
End Sub

Using repository items as arguments for user code actions enables a variety of possibilities such as providing a framework of smart test actions, defining generic technology independent get/set value actions, combining several related actions to one user code action, implementing complex validations and many more.


Conditions in Code

Another reason for writing user code is to read text values from UI elements like text boxes and to reuse them for conditional automation steps.


Note Only create small and easy to maintain user code actions for a recording. If an implemented method should also be available for other test cases, create a code module (see Lesson7: Code Modules) instead.


Within the 'DeleteEntry' recording that was created in Lesson 3: Data-Driven Testing, there are three simple actions for deleting the selected entry (selecting the item, opening the context menu and choosing the context menu item). As you can see it is meaningful to only delete an entry if it is selected. To accomplish this, code with a condition can be used.

As a first step, open the 'DeleteEntry' recording and select the last two items as only they should be executed if the entry is selected. Click on the 'Merge Items to User Code Item' menu item in the context menu.


Context menu item to 'Merge Items to User Code Item'

Context menu item to 'Merge Items to User Code Item'

After doing this, these two actions are merged into one user code action. Give this method a meaningful name (e.g. 'DeleteItemIfFocused'). Switch into the code view by clicking on the context menu item 'View User Code'. Now change the converted code so it is only executed if the cell is focused on.

public void DeleteItemIfFocused(RepoItemInfo cellInfo, RepoItemInfo menuitemInfo)  
{  
  if (repo.MainForm.Entry.HasFocus) {  
                  
    Report.Log(ReportLevel.Info, "Mouse", "Mouse Right Click item 'cellInfo' at Center.", cellInfo);  
    cellInfo.FindAdapter<cell>().Click(System.Windows.Forms.MouseButtons.Right, 100);  
                  
    Report.Log(ReportLevel.Info, "Mouse", "Mouse Left Click item 'menuitemInfo' at Center.", menuitemInfo);  
    menuitemInfo.FindAdapter<menuitem>().Click(100);  
  }  
}  



Public Sub DeleteItemIfFocused(cellInfo As RepoItemInfo, menuitemInfo As RepoItemInfo)  
  If repo.MainForm.Entry.HasFocus Then  
      
    Report.Log(ReportLevel.Info, "Mouse", "Mouse Right Click item 'cellInfo' at Center.", cellInfo)  
    cellInfo.FindAdapter(Of Cell)().Click(System.Windows.Forms.MouseButtons.Right, 100)  
  
    Report.Log(ReportLevel.Info, "Mouse", "Mouse Left Click item 'menuitemInfo' at Center.", menuitemInfo)  
    menuitemInfo.FindAdapter(Of MenuItem)().Click(100)  
  End If  
End Sub