Table of Contents

Creating Your First Automation Script

This guide will walk you through creating your first automation script using the Ranorex API, from basic element interaction to a complete working example.

Simple Desktop Automation Example

Let's start with a basic example that automates Windows Notepad, following the same initialization pattern from the basic setup:

using Ranorex;
using Ranorex.Core;
using Ranorex.Core.Resolver;
using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;

namespace FirstAutomationScriptExample
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            InitResolver();

            try
            {
                // Launch Notepad
                Process.Start("notepad.exe");

                // Give Notepad a moment to start before searching for it
                Delay.Milliseconds(1000);

                // Wait for Notepad to appear and get the main window
                var notepadWindow = "/form[@title='Untitled - Notepad']";
                Host.Local.FindSingle<Form>(notepadWindow, 10000);

                // Find the text area and type some text
                var textArea = notepadWindow + "/?/?/element[@class='RichEditD2DPT']";
                var textElement = Host.Local.FindSingle<Unknown>(textArea);
                textElement.Click();
                textElement.PressKeys("Hello, Ranorex API!");

                // Close Notepad (Alt+F4)
                Host.Local.PressKeys("{Alt down}{F4}");

                Console.WriteLine("Automation completed successfully!");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error during automation: {ex.Message}");
            }
        }

        [MethodImpl(MethodImplOptions.NoInlining)]
        private static void InitResolver()
        {
            AssemblyLoader.Initialize();
        }
    }
}

Web Automation Example

Here's an example of automating a web browser:

using Ranorex;
using Ranorex.Core;
using Ranorex.Plugin.Web;
using System;

class WebAutomationExample
{
    static void Main(string[] args)
    {
        Host.Initialize();
        
        try
        {
            // Open a web browser
            Host.Current.OpenBrowser("https://www.google.com", "Chrome");
            
            // Wait for the page to load
            Delay.Milliseconds(2000);
            
            // Find the search box and enter a search term
            var searchBox = "/dom[@domain='google.com']//input[@name='q']";
            var searchElement = Host.Local.FindSingle<InputTag>(searchBox);
            searchElement.Click();
            searchElement.PressKeys("Ranorex Studio");
            
            // Press Enter to search
            searchElement.PressKeys("{Return}");
            
            // Wait for results to load
            Delay.Milliseconds(3000);
            
            // Find and click the first search result
            var firstResult = "/dom[@domain='google.com']//h3[1]";
            var resultElement = Host.Local.FindSingle<DivTag>(firstResult);
            resultElement.Click();
            
            // Wait a moment to see the result
            Delay.Milliseconds(5000);
            
            // Close the browser
            Host.Current.CloseBrowser();
            
            Console.WriteLine("Web automation completed successfully!");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"Error during web automation: {ex.Message}");
        }
        finally
        {
            Host.Shutdown();
        }
    }
}

Understanding the Code Structure

1. Initialization and Cleanup

// Always initialize at the start
Host.Initialize();

try
{
    // Your automation code here
}
finally
{
    // Always clean up at the end
    Host.Shutdown();
}

2. Element Identification

// RanoreXPath - the Ranorex way to identify elements
var elementPath = "/form[@title='MyApp']/button[@text='Click Me']";

// Find a single element
var element = Host.Local.FindSingle<Button>(elementPath);

// Find multiple elements
var elements = Host.Local.Find<Button>(elementPath);

3. Element Interaction

// Click on an element
element.Click();

// Type text
element.PressKeys("Hello World");

// Special key combinations
element.PressKeys("{Ctrl}c");     // Ctrl+C
element.PressKeys("{Alt}{F4}");   // Alt+F4
element.PressKeys("{Return}");    // Enter key

4. Waiting and Timing

// Wait for an element to appear
var element = Host.Local.FindSingle<Button>(path, 10000); // 10 second timeout

// Fixed delay
Delay.Milliseconds(2000); // Wait 2 seconds

// Wait for a condition
Host.Local.WaitForNotExists(loadingSpinner, 30000);

Building a Complete Test Module

For better organization, create a test module class:

using Ranorex;
using Ranorex.Core;
using Ranorex.Core.Testing;

[TestModule("My First Test Module")]
public class MyFirstTestModule : ITestModule
{
    public void Run()
    {
        try
        {
            // Test step 1: Launch application
            Report.Log(ReportLevel.Info, "Starting application");
            LaunchApplication();
            
            // Test step 2: Perform login
            Report.Log(ReportLevel.Info, "Performing login");
            PerformLogin("testuser", "password123");
            
            // Test step 3: Navigate to main feature
            Report.Log(ReportLevel.Info, "Navigating to main feature");
            NavigateToFeature();
            
            // Test step 4: Verify functionality
            Report.Log(ReportLevel.Info, "Verifying functionality");
            VerifyFunctionality();
            
            Report.Log(ReportLevel.Success, "Test completed successfully");
        }
        catch (Exception ex)
        {
            Report.Log(ReportLevel.Error, $"Test failed: {ex.Message}");
            throw; // Re-throw to fail the test
        }
    }
    
    private void LaunchApplication()
    {
        // Launch your application
        Process.Start("MyApp.exe");
        
        // Wait for main window
        var mainWindow = "/form[@title='My Application']";
        Host.Local.FindSingle<Form>(mainWindow, 15000);
    }
    
    private void PerformLogin(string username, string password)
    {
        // Find and fill username field
        var usernameField = "/form[@title='Login']/text[@name='username']";
        var usernameElement = Host.Local.FindSingle<Text>(usernameField);
        usernameElement.Click();
        usernameElement.PressKeys(username);
        
        // Find and fill password field
        var passwordField = "/form[@title='Login']/text[@name='password']";
        var passwordElement = Host.Local.FindSingle<Text>(passwordField);
        passwordElement.Click();
        passwordElement.PressKeys(password);
        
        // Click login button
        var loginButton = "/form[@title='Login']/button[@text='Login']";
        var loginElement = Host.Local.FindSingle<Button>(loginButton);
        loginElement.Click();
    }
    
    private void NavigateToFeature()
    {
        // Click on menu item
        var menuItem = "/form[@title='My Application']/menuitem[@text='Features']";
        var menuElement = Host.Local.FindSingle<MenuItem>(menuItem);
        menuElement.Click();
    }
    
    private void VerifyFunctionality()
    {
        // Verify expected element exists
        var expectedElement = "/form[@title='Features']/text[@text='Feature List']";
        var element = Host.Local.FindSingle<Text>(expectedElement);
        
        // Validate element properties
        Validate.Attribute(element, "Visible", true);
        Validate.Attribute(element, "Text", "Feature List");
    }
}

// Main program to run the test module
class Program
{
    static void Main(string[] args)
    {
        Host.Initialize();
        
        try
        {
            var testModule = new MyFirstTestModule();
            testModule.Run();
        }
        finally
        {
            Host.Shutdown();
        }
    }
}

Best Practices for First Scripts

1. Error Handling

try
{
    var element = Host.Local.FindSingle<Button>(buttonPath, 5000);
    element.Click();
}
catch (RanorexException ex)
{
    Report.Log(ReportLevel.Error, $"Element not found: {ex.Message}");
    // Take screenshot for debugging
    Report.Screenshot();
    throw;
}

2. Robust Element Waiting

// Wait for element to become available
if (Host.Local.TryFindSingle(elementPath, out Element element))
{
    element.Click();
}
else
{
    throw new InvalidOperationException("Required element not found");
}

3. Logging and Reporting

// Use Ranorex reporting
Report.Log(ReportLevel.Info, "Clicking submit button");
submitButton.Click();
Report.Log(ReportLevel.Success, "Submit button clicked successfully");

// Take screenshots at key points
Report.Screenshot("Before action");
performAction();
Report.Screenshot("After action");

Debugging Your Scripts

1. Element Highlighting

// Enable element highlighting to see what Ranorex is finding
Host.Current.HighlightElements = true;

// Highlight specific element
element.Highlight();
Delay.Milliseconds(2000); // Give time to see the highlight

2. RanoreXPath Validation

// Test if your path finds elements
var elements = Host.Local.Find<Unknown>(yourPath);
Console.WriteLine($"Found {elements.Count} elements with path: {yourPath}");

foreach (var elem in elements)
{
    Console.WriteLine($"Element: {elem.GetType().Name}, Text: {elem.GetAttributeValueOrDefault("Text", "")}");
}

Next Steps

Now that you've created your first automation script:

  1. Understanding Element Identification - Master RanoreXPath and element finding
  2. Working with Repository - Organize your elements efficiently
  3. Advanced UI Interaction - Learn complex interaction patterns

Common Issues and Solutions

  • Element not found: Double-check your RanoreXPath expressions
  • Timing issues: Add appropriate waits and timeouts
  • Application state: Ensure your application is in the expected state before interactions
  • Focus issues: Click on elements before typing to ensure they have focus

For more detailed troubleshooting, check our comprehensive guides and examples.