Variable use in test.UserCode.cs

Ask general questions here.
User avatar
felixk91
Posts: 34
Joined: Wed Feb 10, 2016 11:16 pm

Variable use in test.UserCode.cs

Post by felixk91 » Wed May 04, 2022 8:25 am

Hi Everyone,

I created a variable that I want to use during the test case run. I have the files test.cs and test.usercode.cs for my "recording" module. The test.cs is looked be Ranorex.
How can I use this variable within the user code file test.usercode.cs?
I tried to read almost all forums in regards to how to use variables in the user code module.
I can't create a module variable because I don't see the menu "Insert module variable".

Thanks,
Felix.

User avatar
odklizec
Ranorex Guru
Ranorex Guru
Posts: 7470
Joined: Mon Aug 13, 2012 9:54 am
Location: Zilina, Slovakia

Re: Variable use in test.UserCode.cs

Post by odklizec » Wed May 04, 2022 8:43 am

Hi,

In case of Recording modules, you should use Variables menu and define the module variable there. Then in usercode, you can simply reference the variable name by typing its name. You should also see it in the code completion context menu.
Pavel Kudrys
Ranorex explorer at Descartes Systems

Please add these details to your questions:
  • Ranorex Snapshot. Learn how to create one >here<
  • Ranorex xPath of problematic element(s)
  • Ranorex version
  • OS version
  • HW configuration

User avatar
felixk91
Posts: 34
Joined: Wed Feb 10, 2016 11:16 pm

Re: Variable use in test.UserCode.cs

Post by felixk91 » Thu May 05, 2022 1:59 am

Hi odklizec,

Thank you for your reply.
I tried it and I am getting the following error message: "An object reference is required for the non-static field, method, or property 'ScriptTestingRun.LoadDescriptions' (CS0120)".
I am using this variable within the call back function for popup watcher.
Any suggestion for this, please.

Thank you,
Felix.

User avatar
odklizec
Ranorex Guru
Ranorex Guru
Posts: 7470
Joined: Mon Aug 13, 2012 9:54 am
Location: Zilina, Slovakia

Re: Variable use in test.UserCode.cs

Post by odklizec » Thu May 05, 2022 7:12 am

Hi,

I'm afraid, without seeing the whole code, it's impossible to tell what's wrong. My guess is, that the variable used in different module without proper declaration? The workflow I suggested, apply for recording module, in which the variable is declared (via Module Variables editor).
Pavel Kudrys
Ranorex explorer at Descartes Systems

Please add these details to your questions:
  • Ranorex Snapshot. Learn how to create one >here<
  • Ranorex xPath of problematic element(s)
  • Ranorex version
  • OS version
  • HW configuration

User avatar
felixk91
Posts: 34
Joined: Wed Feb 10, 2016 11:16 pm

Re: Variable use in test.UserCode.cs

Post by felixk91 » Fri May 06, 2022 2:57 am

Hi odklizec,

Here is the full code for ScriptTestingRun.UserCode.cs:
///////////////////////////////////////////////////////////////////////////////
//
// This file was automatically generated by RANOREX.
// Your custom recording code should go in this file.
// The designer will only add methods to this file, so your custom code won't be overwritten.
// http://www.ranorex.com
//
///////////////////////////////////////////////////////////////////////////////

using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Drawing;
using System.Threading;
using WinForms = System.Windows.Forms;
using System.Diagnostics;
using Ranorex;
using Ranorex.Core;
using Ranorex.Core.Data;
using Ranorex.Core.Repository;
using Ranorex.Core.Reporting;
using Ranorex.Core.Testing;
using Ranorex.AutomationHelpers.UserCodeCollections;
using PrydaBuildTests.CommonUserCode;

namespace PrydaBuildTests.ScriptTestingRun
{
    public partial class ScriptTestingRun
    {
        /// <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.
        }
         
        
        
        private static readonly Dictionary<string, PopupWatcher> watchers = new Dictionary<string, PopupWatcher>();

        public static IList<PopupWatcher> Watchers { get { return new List<PopupWatcher>(watchers.Values); } }

        /// <summary>
        /// Function to start PopupWatcher for Load Area Values dialog and perform values setup
        /// Parameters:
        /// findElement = repository representstion of a dialog to look after
        /// callBackFunction = function that performs required steps for a dilog
        /// </summary>
        public static PopupWatcher StartDialogPopupWatcher(RepoItemInfo findElement)
        {
        	
            CheckArgumentNotNull(findElement, "findElement");
 
            var key = findElement.GetMetaInfos()["id"];

            if (watchers.ContainsKey(key))
            {
                throw new ArgumentException("Popup watcher with given parameters already exists.");
            }

            var watcher = new PopupWatcher();
            watcher.Watch(findElement, LoadAreaValuesSetup);
            watcher.Start();
            watchers.Add(key, watcher);
            Report.Info("Popup watcher started.");
            return watcher;        	
        }

        /// <summary>
        /// Function to stop PopupWatcher for a dialog
        /// Parameters:
        /// findElement = repository representstion of a dialog to look after
        /// </summary>
        public static void StopDialogPopupWatcher(RepoItemInfo findElement)
        {
            CheckArgumentNotNull(findElement, "findElement");

            var key = findElement.GetMetaInfos()["id"];
            PopupWatcher watcher = null;
            if (watchers.TryGetValue(key, out watcher))
            {
	            watcher.Clear();
	            watcher.Stop();
	            Report.Info("Popup watcher stopped.");
	            watchers.Remove(key);
            }
            else
            {
                Report.Warn("The popup watcher you tried to remove does not exist.");
            }
        }


        /// <summary>
        /// Function to start Script testing process
        /// Parameters:
        /// args = nullable list of arguments for script testing command line 
        /// </summary>
        public static void StartScriptTesting(string args = null)
        {
        	var command = "C:\\Program Files (x86)\\Pryda\\Pryda Build\\5.1\\ScriptRunner.exe";
        	
        	if (args == null)
        	{
        		args = string.Empty;
        	}

    		var proc = new Process
			{
    			StartInfo = new ProcessStartInfo
   				 {
        			FileName = command,
        			Arguments = args,
        			UseShellExecute = false,
        			RedirectStandardOutput = true,
        			CreateNoWindow = true,
        			WorkingDirectory = @"C:\Program Files (x86)\Pryda\Pryda Build\5.1\"
    			}
			};

			proc.Start();
        }
        
        /// <summary>
        /// Function waiting for a process to finish
        /// Parameters:
        /// processName = process name, file name without extension 
        /// </summary>
        public static void WaitForProcessToEnd (string processName)
        {
        	while (true)
        	{
	        	Process[] processes = Process.GetProcessesByName(processName);
	        	if (processes.Length == 0)
	        		break;
	        	Thread.Sleep(1000);
        	}
        }

        public static void LoadAreaValuesSetup(RepoItemInfo info, Element target)
        {
        	Report.Log(ReportLevel.Info, "Validation", "Validating Exists on item 'info'.", info);
        	if (!info.Exists())
        	{
        		Report.Log(ReportLevel.Failure, string.Format("Dialog {0} not exist", info.Name));
        		return;
        	}
        	
        	if (repo.LoadAreaValuesDialog.DescriptionDropdownList.Self.Enabled)
        	{
        		CommonFunctions.SelectItemInDropdownList(repo.LoadAreaValuesDialog.DescriptionDropdownList.SelfInfo, LoadDescriptions);
        	}
        	
        	if (repo.LoadAreaValuesDialog.FixingMethodDropdownList.Self.Enabled)
        	{
        		CommonFunctions.SelectItemInDropdownList(repo.LoadAreaValuesDialog.FixingMethodDropdownList.SelfInfo, "Battens");
        	}
        	
        	if (repo.LoadAreaValuesDialog.WeightTextbox.Enabled)
        	{
        		CommonFunctions.SetTextBoxValue(repo.LoadAreaValuesDialog.WeightTextboxInfo, "54.0");
        	}
        	
        	if (repo.LoadAreaValuesDialog.RestraintSpacingTextbox.Enabled)
        	{
        		CommonFunctions.SetTextBoxValue(repo.LoadAreaValuesDialog.RestraintSpacingTextboxInfo, "450");
        	}
        	
        	repo.LoadAreaValuesDialog.ButtonOK.Click();
        }

        private static void CheckArgumentNotNull(object argument, string argumentName)
        {
            if (argument == null)
            {
                throw new ArgumentNullException(argumentName);
            }
        }

     }
}
I got the recording module ScriptTestingRun:
RecordingModule.PNG
Here is the full code locked file ScriptTesting.cs:
///////////////////////////////////////////////////////////////////////////////
//
// This file was automatically generated by RANOREX.
// DO NOT MODIFY THIS FILE! It is regenerated by the designer.
// All your modifications will be lost!
// http://www.ranorex.com
//
///////////////////////////////////////////////////////////////////////////////

using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Drawing;
using System.Threading;
using WinForms = System.Windows.Forms;

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

namespace PrydaBuildTests.ScriptTestingRun
{
#pragma warning disable 0436 //(CS0436) The type 'type' in 'assembly' conflicts with the imported type 'type2' in 'assembly'. Using the type defined in 'assembly'.
    /// <summary>
    ///The ScriptTestingRun recording.
    /// </summary>
    [TestModule("c649a7d1-27ce-47c0-b14e-8ed3c725a615", ModuleType.Recording, 1)]
    public partial class ScriptTestingRun : ITestModule
    {
        /// <summary>
        /// Holds an instance of the global::PrydaBuildTests.PrydaBuildRepository repository.
        /// </summary>
        public static global::PrydaBuildTests.PrydaBuildRepository repo = global::PrydaBuildTests.PrydaBuildRepository.Instance;

        static ScriptTestingRun instance = new ScriptTestingRun();

        /// <summary>
        /// Constructs a new instance.
        /// </summary>
        public ScriptTestingRun()
        {
            Arguments = "--gtest_filter=*RoofAreaValues01*";
            LoadDescriptions = "Concrete tiles - heavy";
        }

        /// <summary>
        /// Gets a static instance of this recording.
        /// </summary>
        public static ScriptTestingRun Instance
        {
            get { return instance; }
        }

#region Variables

        string _Arguments;

        /// <summary>
        /// Gets or sets the value of variable Arguments.
        /// </summary>
        [TestVariable("97fe38d2-db22-411c-92bc-281f0e661419")]
        public string Arguments
        {
            get { return _Arguments; }
            set { _Arguments = value; }
        }

        string _LoadDescriptions;

        /// <summary>
        /// Gets or sets the value of variable LoadDescriptions.
        /// </summary>
        [TestVariable("f3a2e4b3-9ba6-490a-bcf2-07b891c00352")]
        public string LoadDescriptions
        {
            get { return _LoadDescriptions; }
            set { _LoadDescriptions = value; }
        }

#endregion

        /// <summary>
        /// Starts the replay of the static recording <see cref="Instance"/>.
        /// </summary>
        [System.CodeDom.Compiler.GeneratedCode("Ranorex", global::Ranorex.Core.Constants.CodeGenVersion)]
        public static void Start()
        {
            TestModuleRunner.Run(Instance);
        }

        /// <summary>
        /// Performs the playback of actions in this recording.
        /// </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>
        [System.CodeDom.Compiler.GeneratedCode("Ranorex", global::Ranorex.Core.Constants.CodeGenVersion)]
        void ITestModule.Run()
        {
            Mouse.DefaultMoveTime = 300;
            Keyboard.DefaultKeyPressTime = 20;
            Delay.SpeedFactor = 1.00;

            Init();

            Ranorex.AutomationHelpers.UserCodeCollections.PopupWatcherLibrary.StartPopupWatcher(repo.PrydaBuildDesignerDialog.SelfInfo, repo.PrydaBuildDesignerDialog.ButtonOKInfo);
            Delay.Milliseconds(0);
            
            Ranorex.AutomationHelpers.UserCodeCollections.PopupWatcherLibrary.StartPopupWatcher(repo.PrydaBuildWarningDialog.SelfInfo, repo.PrydaBuildWarningDialog.ButtonOKInfo);
            Delay.Milliseconds(0);
            
            StartDialogPopupWatcher(repo.LoadAreaValuesDialog.SelfInfo);
            Delay.Milliseconds(0);
            
            StartScriptTesting(Arguments);
            Delay.Milliseconds(0);
            
            WaitForProcessToEnd("ScriptRunner");
            Delay.Milliseconds(0);
            
            Ranorex.AutomationHelpers.UserCodeCollections.PopupWatcherLibrary.StopAllPopupWatchers();
            Delay.Milliseconds(0);
            
        }

#region Image Feature Data
#endregion
    }
#pragma warning restore 0436
}
As you can see variable "LoadDefinitions" is defined in a locked file using the Variable editor:
RecordingModule.PNG
The variable is used within the function LoadAreaValuesSetup which is a callback function for popup watcher.

Thanks,
Felix.
You do not have the required permissions to view the files attached to this post.

User avatar
odklizec
Ranorex Guru
Ranorex Guru
Posts: 7470
Joined: Mon Aug 13, 2012 9:54 am
Location: Zilina, Slovakia

Re: Variable use in test.UserCode.cs

Post by odklizec » Fri May 06, 2022 7:46 am

Hi,

I'm afraid, I don't see LoadDefinitions anywhere in the code you posted. There is just "LoadDescriptions", if you mean that? Sadly, because there is not shown the definition of SelectItemInDropdownList method, I can only guess that it's a non-static method?
Pavel Kudrys
Ranorex explorer at Descartes Systems

Please add these details to your questions:
  • Ranorex Snapshot. Learn how to create one >here<
  • Ranorex xPath of problematic element(s)
  • Ranorex version
  • OS version
  • HW configuration