static void Main(string[] args) { if (args.Count() == 0) { RunSample(); } switch( args[0].ToLower()) { case "/f": CommandEnvironment commandEnv = new CommandEnvironment(); commandEnv.Run(RunFile(args[1])); // /f <filenam> break; case "/h": case "/?": ShowHelp(); break; } }
static void RunSample() { string[] commands = { "Report", "Place 2,2,West", "Report", "Move", "Open Pod Bay Doors", "Report", "Place 3, 3, South", "Report", "Left", "Move", "Exterminate", "Report" }; CommandEnvironment commandEnv = new CommandEnvironment(); commandEnv.Run(commands.ToList()); }
public Handler(AutomationElement automationElement, IntPtr hWnd, CommandEnvironment commandEnvironment) { var behavior = commandEnvironment.UnexpectedAlertBehavior; if (behavior == UnexpectedAlertBehaviorReaction.Ignore) { return; } _rootWindow = new SystemWindow(hWnd); IList <SystemWindow> GetWindows() { // dialog windows happen not be in the same tree as the root window return(SystemWindow.DesktopWindow.AllDescendantWindows .Where(w => w.Visible && w.TopMost && w.Process.MainWindowHandle == hWnd) .ToList()); } _childWindows = GetWindows(); var token = _cancellationTokenSource.Token; _thread = new Thread(() => { while (true) { //System.Diagnostics.Debug.WriteLine("Thread work ... " + Thread.CurrentThread.ManagedThreadId); if (token.IsCancellationRequested) { break; } var windows = GetWindows(); UnexpectedAlertEventArgs args = null; var raiseEvent = false; foreach (var window in windows) { if (_childWindows.Contains(window) || !window.Visible) { continue; } raiseEvent = behavior == UnexpectedAlertBehaviorReaction.DismissAndNotify || behavior == UnexpectedAlertBehaviorReaction.AcceptAndNotify; if (raiseEvent) { args = new UnexpectedAlertEventArgs { Title = window.Title, Content = window.AllDescendantWindows .Where(s => s.Visible) .Select(d => d.Title?.Trim()) .Where(s => !string.IsNullOrEmpty(s)) .ToArray() }; } // menus slip through AutomationElement aw = null; try { aw = AutomationElement.FromHandle(window.HWnd); } catch (ElementNotAvailableException) { continue; // menus are causing this exception } if (aw.Current.ControlType != ControlType.Window) { continue; // but sometimes they slip through } System.Diagnostics.Debug.WriteLine("New modal window " + window.HWnd); switch (behavior) { case UnexpectedAlertBehaviorReaction.Ignore: break; case UnexpectedAlertBehaviorReaction.Dismiss: case UnexpectedAlertBehaviorReaction.DismissAndNotify: case UnexpectedAlertBehaviorReaction.Accept: case UnexpectedAlertBehaviorReaction.AcceptAndNotify: //window.SendClose(); break; } } if (raiseEvent) { OnUnexpectedAlert?.Invoke(this, args); } _childWindows = GetWindows(); Thread.Sleep(1000); } }); _thread.Start(); // TODO new thread for each session (OK), not disposed properly }
/// <summary> /// Executes the command. /// </summary> /// <param name="environment">The <see cref="CommandEnvironment"/> to use in executing the command.</param> /// <param name="parameters">The <see cref="Dictionary{string, object}"/> containing the command parameters.</param> /// <returns>The JSON serialized string representing the command response.</returns> public override Response Execute(CommandEnvironment environment, Dictionary <string, object> parameters) { object[] handles = new object[] { CommandEnvironment.GlobalWindowHandle }; return(Response.CreateSuccessResponse(handles)); }
public override Response Execute(CommandEnvironment commandEnvironment, Dictionary <string, object> parameters, System.Threading.CancellationToken cancellationToken) { if (!parameters.TryGetValue("actions", out object o)) { return(Response.CreateMissingParametersResponse("actions")); } var release = new Stack <Microsoft.Test.Input.Key>(); var actionsToExecute = new List <Action>(); var numberOfRetries = 10; Exception e = null; while (numberOfRetries-- >= 0) { if (cancellationToken.IsCancellationRequested) { return(null); } try { SetForegroundWindow(commandEnvironment.WindowHandle); //System.Windows.Automation.AutomationElement.FromHandle(commandEnvironment.WindowHandle).SetFocus(); commandEnvironment.Window.SetFocus(); e = null; break; } catch (COMException comEx) { e = comEx; if (comEx.Message.Contains("0x80131505")) { System.Threading.Thread.Sleep(250); continue; } throw; } } if (e != null) { throw e; } try { foreach (var block in (JArray)o) { var actions = (JArray)block["actions"]; var type = block["type"].Value <string>(); switch (type) { case "pointer": new MouseActions(actions, commandEnvironment).Execute(); break; case "key": new KeyboardActions(actions, commandEnvironment).Execute(); break; } } } finally { Microsoft.Test.Input.Mouse.Reset(); Microsoft.Test.Input.Keyboard.Reset(); } return(Response.CreateSuccessResponse()); }
/// <summary> /// Executes the command. /// </summary> /// <param name="environment">The <see cref="CommandEnvironment"/> to use in executing the command.</param> /// <param name="parameters">The <see cref="Dictionary{string, object}"/> containing the command parameters.</param> /// <returns>The JSON serialized string representing the command response.</returns> public override Response Execute(CommandEnvironment environment, Dictionary <string, object> parameters) { object url; if (!parameters.TryGetValue("url", out url)) { return(Response.CreateMissingParametersResponse("url")); } Uri targetUri = null; if (!Uri.TryCreate(url.ToString(), UriKind.Absolute, out targetUri)) { return(Response.CreateErrorResponse(WebDriverStatusCode.UnhandledError, string.Format("Could not create valie URL from {0}", url.ToString()))); } int timeoutInMilliseconds = environment.PageLoadTimeout; if (timeoutInMilliseconds < 0) { timeoutInMilliseconds = 15000; } else { // If a page load timeout has been set, don't retry the page load. this.retryCount = 1; } WebBrowserNavigationMonitor monitor = new WebBrowserNavigationMonitor(environment); for (int retries = 0; retries < this.retryCount; retries++) { monitor.MonitorNavigation(() => { environment.Browser.Dispatcher.BeginInvoke(() => { environment.Browser.Navigate(targetUri); }); }); if ((monitor.IsSuccessfullyNavigated && monitor.IsLoadCompleted) || monitor.IsNavigationError) { break; } } if (monitor.IsNavigationTimedOut) { return(Response.CreateErrorResponse(WebDriverStatusCode.Timeout, "Timed out loading page")); } if (!monitor.IsNavigationError) { environment.FocusedFrame = string.Empty; } if (this.handleAlerts) { this.EvaluateAtom(environment, AlertHandler); } return(Response.CreateSuccessResponse()); }
protected abstract Response GetResponse(AutomationElement automationElement, CommandEnvironment environment, Dictionary <string, object> parameters, System.Threading.CancellationToken cancellationToken);
protected override Response GetResponse(AutomationElement automationElement, CommandEnvironment environment, Dictionary <string, object> parameters) { var isEnabled = automationElement.GetAutomationElementPropertyValue("IsEnabled"); return(Response.CreateSuccessResponse(isEnabled)); }
protected string EvaluateAtom(CommandEnvironment environment, string atom, params object[] args) { throw new NotImplementedException(); }
protected abstract Task <Response> GetResponseAsync(AutomationElement automationElement, CommandEnvironment environment, Dictionary <string, object> parameters);
public Handler(AutomationElement automationElement, IntPtr hWnd, CommandEnvironment commandEnvironment) { /*return; * var behavior = commandEnvironment.UnexpectedAlertBehavior; * if (behavior == UnexpectedAlertBehaviorReaction.Ignore) * { * return; * } */ _rootWindow = new SystemWindow(hWnd); _childWindows = GetWindows(); /*var token = _cancellationTokenSource.Token; * _thread = new Thread(() => * { * while (true) * { * System.Diagnostics.Debug.WriteLine("Thread work ... " + Thread.CurrentThread.ManagedThreadId); * if (token.IsCancellationRequested) * { * break; * }*/ /* * var windows = GetWindows(); * UnexpectedAlertEventArgs args = null; * var raiseEvent = false; * * foreach (var window in windows) * { * if (_childWindows.Contains(window)) * { * continue; * } */ /*raiseEvent = * behavior == UnexpectedAlertBehaviorReaction.DismissAndNotify || * behavior == UnexpectedAlertBehaviorReaction.AcceptAndNotify;*/ /* * if (raiseEvent) * { * args = new UnexpectedAlertEventArgs * { * Title = window.Title, * Hwnd = window.HWnd, * Content = window.AllDescendantWindows * .Where(s => s.Visible) * .Select(d => d.Title?.Trim()) * .Where(s => !string.IsNullOrEmpty(s)) * .ToArray() * }; * } * * System.Diagnostics.Debug.WriteLine("New modal window " + window.HWnd);*/ /* * switch (behavior) * { * case UnexpectedAlertBehaviorReaction.Ignore: * break; * case UnexpectedAlertBehaviorReaction.Dismiss: * case UnexpectedAlertBehaviorReaction.DismissAndNotify: * case UnexpectedAlertBehaviorReaction.Accept: * case UnexpectedAlertBehaviorReaction.AcceptAndNotify: * window.SendClose(); * break; * }*/ //} /*if (raiseEvent) * { * OnUnexpectedAlert?.Invoke(this, args); * } * * _childWindows = GetWindows(); * * Thread.Sleep(1000);*/ }
/// <summary> /// Executes the command. /// </summary> /// <param name="environment">The <see cref="CommandEnvironment"/> to use in executing the command.</param> /// <param name="parameters">The <see cref="Dictionary{string, object}"/> containing the command parameters.</param> /// <returns>The JSON serialized string representing the command response.</returns> public override Response Execute(CommandEnvironment environment, Dictionary <string, object> parameters, System.Threading.CancellationToken cancellationToken) { object script; if (!parameters.TryGetValue("script", out script)) { return(Response.CreateMissingParametersResponse("script")); } object args; if (!parameters.TryGetValue("args", out args)) { return(Response.CreateMissingParametersResponse("args")); } // TODO for some reason the GetAttribute method is invoked through this ... // if (driver.IsSpecificationCompliant) Execute(DriverCommand.ExecuteScript, dictionary); var getAtomMethod = typeof(RemoteWebElement).GetMethod("GetAtom", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic); var atom = getAtomMethod.Invoke(null, new object[] { "getAttribute.js" }); if (atom.Equals(script.ToString())) { var keyValuePairs = JArray.Parse(args.ToString()); var elementId = keyValuePairs[0].Last().Last().ToString(); var attributeName = keyValuePairs[1].ToString(); return(CommandHandlerFactory.Instance.GetHandler(DriverCommand.GetElementAttribute).Execute(environment, new Dictionary <string, object> { { "NAME", attributeName }, { "ID", elementId } }, cancellationToken)); } atom = getAtomMethod.Invoke(null, new object[] { "isDisplayed.js" }); if (atom.Equals(script.ToString())) { var keyValuePairs = JArray.Parse(args.ToString()); var elementId = keyValuePairs[0].Last().Last().ToString(); return(CommandHandlerFactory.Instance.GetHandler(DriverCommand.IsElementDisplayed).Execute(environment, new Dictionary <string, object> { { "ID", elementId } }, cancellationToken)); } if (script.ToString() == "var rect = arguments[0].getBoundingClientRect(); return {'x': rect.left, 'y': rect.top};") { var keyValuePairs = JArray.Parse(args.ToString()); var elementId = keyValuePairs[0].Last().Last().ToString(); return(CommandHandlerFactory.Instance.GetHandler(DriverCommand.GetElementRect).Execute(environment, new Dictionary <string, object> { { "ID", elementId } }, cancellationToken)); } if (script.ToString() == "return window.name") { var keyValuePairs = JArray.Parse(args.ToString()); /*var elementId = keyValuePairs[0].Last().Last().ToString(); * return CommandHandlerFactory.Instance.GetHandler(DriverCommand.GetElementRect).Execute(environment, new Dictionary<string, object> * { * { "ID", elementId } * });*/ return(Response.CreateErrorResponse(WebDriverStatusCode.UnexpectedJavaScriptError, "Cannot get window.name")); } return(Response.CreateErrorResponse(WebDriverStatusCode.UnexpectedJavaScriptError, "Scripting is not supported.")); }
/// <summary> /// Executes the command. /// </summary> /// <param name="environment">The <see cref="CommandEnvironment"/> to use in executing the command.</param> /// <param name="parameters">The <see cref="Dictionary{string, object}"/> containing the command parameters.</param> /// <returns>The JSON serialized string representing the command response.</returns> public override Response Execute(CommandEnvironment environment, Dictionary <string, object> parameters) { Dictionary <string, object> responseValue = new Dictionary <string, object>(); responseValue["browserName"] = "WinFormsApp"; responseValue["cssSelectorsEnabled"] = false; responseValue["javascriptEnabled"] = false; responseValue["takesScreenshot"] = true; responseValue["handlesAlerts"] = true; var desiredCapabilities = JObject.Parse(parameters["desiredCapabilities"]?.ToString() ?? "{}").ToObject <Dictionary <string, object> >(); //parameters["desiredCapabilities"] as Dictionary<string, string> ?? new Dictionary<string, string>(); // extend capabilities with one more required parameter if (!desiredCapabilities.TryGetValue("mode", out var mode)) { return(Response.CreateMissingParametersResponse("mode")); } // check does mode is process and capabilities contain processName simultaneounsy if (mode?.ToString() == "attach" & !desiredCapabilities.TryGetValue("processName", out var processName)) { return(Response.CreateMissingParametersResponse("processName")); } // check does mode is process and capabilities contain exePath simultaneounsy if (mode?.ToString() == "start" & !desiredCapabilities.TryGetValue("exePath", out var exePath)) { return(Response.CreateMissingParametersResponse("exePath")); } Process process = null; if (processName != null) { process = Process.GetProcessesByName(processName.ToString()).FirstOrDefault(); // searching by name as regular expression pattern if (process == null) { var regex = new Regex(processName.ToString()); process = Process.GetProcesses() .Where(x => regex.IsMatch(x.ProcessName)).FirstOrDefault(); } if (process == null) { return(Response.CreateErrorResponse(-1, $"Cannot attach to process '{processName}', no such process found.")); } } if (exePath != null) { process = ApplicationProcess.StartProcessFromPath(exePath.ToString()); if (process == null) { return(Response.CreateErrorResponse(-1, "Cannot start process.")); } } var sessionId = process?.MainWindowHandle.ToString(); if (sessionId != null) { /*if (CacheStore.Store.TryGetValue(sessionId, out var elementCache)) * { * CacheStore.Store.TryRemove(sessionId, out elementCache); * } * else * { * CacheStore.Store.AddOrUpdate(sessionId, ElementCacheFactory.Get(sessionId), (k, c) => * { * c.Handle = process.MainWindowHandle; * return c; * }); * }*/ if (CacheStore.CommandStore.TryGetValue(sessionId, out var commandEnvironment)) { CacheStore.CommandStore.TryRemove(sessionId, out commandEnvironment); } //var cache = ElementCacheFactory.Get(sessionId); commandEnvironment = new CommandEnvironment(sessionId, desiredCapabilities); //var e = cache.AutomationElement; //e = AutomationElement.FromHandle(cache.Handle); //cache.AddHandler(UnexpectedAlertBehavior.CreateHandler(e, cache.Handle, commandEnvironment)); //CacheStore.CommandStore.AddOrUpdate(sessionId, commandEnvironment, (k, c) => c); } Response response = Response.CreateSuccessResponse(responseValue); response.SessionId = sessionId; response.Status = null; return(response); }
protected override Response GetResponse(AutomationElement automationElement, CommandEnvironment environment, Dictionary <string, object> parameters, System.Threading.CancellationToken cancellationToken) { var value = (ControlType)automationElement.GetAutomationElementPropertyValue("ControlType"); return(Response.CreateSuccessResponse(value.ProgrammaticName)); }
/// <summary> /// Executes the command. /// </summary> /// <param name="environment">The <see cref="CommandEnvironment"/> to use in executing the command.</param> /// <param name="parameters">The <see cref="Dictionary{string, object}"/> containing the command parameters.</param> /// <returns>The JSON serialized string representing the command response.</returns> public abstract Response Execute(CommandEnvironment environment, Dictionary <string, object> parameters);
/// <summary> /// Executes the command. /// </summary> /// <param name="environment">The <see cref="CommandEnvironment"/> to use in executing the command.</param> /// <param name="parameters">The <see cref="Dictionary{string, object}"/> containing the command parameters.</param> /// <returns>The JSON serialized string representing the command response.</returns> public abstract Task <Response> ExecuteAsync(CommandEnvironment environment, Dictionary <string, object> parameters);
/// <summary> /// Executes the command. /// </summary> /// <param name="environment">The <see cref="CommandEnvironment"/> to use in executing the command.</param> /// <param name="parameters">The <see cref="Dictionary{string, object}"/> containing the command parameters.</param> /// <returns>The JSON serialized string representing the command response.</returns> public virtual Response Execute(CommandEnvironment environment, Dictionary <string, object> parameters) { throw new NotImplementedException(); }
/// <summary> /// Disposes the session. /// </summary> /// <param name="environment">The <see cref="CommandEnvironment"/> to use in executing the command.</param> /// <param name="parameters">The <see cref="Dictionary{string, object}"/> containing the command parameters.</param> /// <returns>The JSON serialized string representing the command response.</returns> public override Response Execute(CommandEnvironment environment, Dictionary <string, object> parameters, System.Threading.CancellationToken cancellationToken) { environment.Dispose(); return(Response.CreateSuccessResponse()); }
/// <summary> /// Executes the command. /// </summary> /// <param name="environment">The <see cref="CommandEnvironment"/> to use in executing the command.</param> /// <param name="parameters">The <see cref="Dictionary{string, object}"/> containing the command parameters.</param> /// <returns>The JSON serialized string representing the command response.</returns> public override Response Execute(CommandEnvironment environment, Dictionary <string, object> parameters, System.Threading.CancellationToken cancellationToken) { var rect = environment.Cache.AutomationElement.Current.BoundingRectangle; return(Response.CreateSuccessResponse(new { x = (int)rect.Left, y = (int)rect.Top, width = (int)rect.Width, height = (int)rect.Height })); }
/// <summary> /// Executes the command. /// </summary> /// <param name="environment">The <see cref="CommandEnvironment"/> to use in executing the command.</param> /// <param name="parameters">The <see cref="Dictionary{string, object}"/> containing the command parameters.</param> /// <returns>The JSON serialized string representing the command response.</returns> public override Response Execute(CommandEnvironment environment, Dictionary <string, object> parameters, System.Threading.CancellationToken cancellationToken) { Dictionary <string, object> responseValue = new Dictionary <string, object>(); responseValue["browserName"] = "WinFormsApp"; responseValue["cssSelectorsEnabled"] = false; responseValue["javascriptEnabled"] = false; responseValue["takesScreenshot"] = true; responseValue["handlesAlerts"] = true; var desiredCapabilities = JObject.Parse(parameters["desiredCapabilities"]?.ToString() ?? "{}").ToObject <Dictionary <string, object> >(); // extend capabilities with one more required parameter if (!desiredCapabilities.TryGetValue("mode", out var mode)) { mode = "start"; //return Response.CreateMissingParametersResponse("mode"); } var mainWindowTitle = ""; if (desiredCapabilities.TryGetValue("mainWindowTitle", out var mwt)) { mainWindowTitle = mwt?.ToString() ?? ""; } var attached = false; Process process = null; // check does mode is process and capabilities contain processName simultaneounsy if (mode?.ToString() == "attach")// & !desiredCapabilities.TryGetValue("processName", out var processName)) { process = ApplicationProcess.AttachToProcess(desiredCapabilities); if (process == null) { return(Response.CreateErrorResponse(-1, $"Cannot attach to process by id or name no such process found.")); } attached = true; } else { object exePath = string.Empty; // check does mode is process and capabilities contain exePath simultaneounsy if (mode?.ToString() == "start") { if (!desiredCapabilities.TryGetValue("exePath", out exePath) && !desiredCapabilities.TryGetValue("app", out exePath)) { return(Response.CreateMissingParametersResponse("exePath or app")); } desiredCapabilities.TryGetParameterValue <string>("processName", out var processName); desiredCapabilities.TryGetParameterValue <string>("appWorkingDir", out var workingDirectory); process = ApplicationProcess.StartProcessFromPath(exePath.ToString(), cancellationToken, processName, mainWindowTitle, workingDirectory); if (process == null) { return(Response.CreateErrorResponse(-1, "Cannot start process.")); } } } if (process == null) { return(Response.CreateErrorResponse(WebDriverStatusCode.UnhandledError, $"Cannot start process or attach to process")); } var sessionId = process.MainWindowHandle.ToString(); NLog.MappedDiagnosticsContext.Set("SessionId", sessionId); var processId = $"'{process.ProcessName}', pid = {process.Id}"; if (sessionId == null) { return(Response.CreateErrorResponse(WebDriverStatusCode.UnhandledError, $"Cannot get main windows handle for the process {processId}.")); } // new session is starting, remove the old command environment context if (CacheStore.CommandStore.TryGetValue(sessionId, out var commandEnvironment)) { CacheStore.CommandStore.TryRemove(sessionId, out commandEnvironment); commandEnvironment.Dispose(); } commandEnvironment = new CommandEnvironment(sessionId, desiredCapabilities); if (!attached) { commandEnvironment.Pid = process.Id; Logger.Info($"Session '{sessionId}' created process {processId}."); } else { Logger.Info($"Session '{sessionId}' attached to process {processId}."); } CacheStore.CommandStore.AddOrUpdate(sessionId, commandEnvironment, (key, _) => _); Response response = Response.CreateSuccessResponse(responseValue); response.SessionId = sessionId; response.Status = null; return(response); }
static void Main(string[] args) { CommandEnvironment app = new CommandEnvironment(); app.run(); }
public KeyboardActions(JArray actions, CommandEnvironment commandEnvironment) { _actions = actions; _commandEnvironment = commandEnvironment; }
private Response FromException(AutomationElement element, Exception exception, CommandEnvironment environment, CancellationToken cancellationToken) { if (exception is AggregateException aggregateException) { return(FromException(element, aggregateException.InnerException, environment, cancellationToken)); } if (exception is ElementNotEnabledException enee) { // maybe the interaction is not possible, because there is a modal window blocking the UI var parentWindow = element.GetTopLevelWindow(); if (parentWindow.IsBlockedByModalWindow()) { var modalWindow = environment.GetModalWindow(cancellationToken); return(Response.CreateErrorResponse( WebDriverStatusCode.UnexpectedAlertOpen, "Interaction with the element is not possible, because there is a modal window blocking the UI.", payload: modalWindow?.GetWindowCaption(), error: "Invalid element state", sessionId: environment.SessionId)); } return(Response.CreateErrorResponse(WebDriverStatusCode.InvalidElementState, enee.Message)); } ExceptionDispatchInfo.Capture(exception).Throw(); return(null); }
protected override Response GetResponse(AutomationElement automationElement, CommandEnvironment environment, Dictionary <string, object> parameters) { return(Response.CreateSuccessResponse(!automationElement.Current.IsOffscreen)); }
protected override Response GetResponse(AutomationElement automationElement, CommandEnvironment environment, Dictionary <string, object> parameters) { var rect = automationElement.Current.BoundingRectangle; return(Response.CreateSuccessResponse(new { x = (int)rect.Left, y = (int)rect.Top, width = (int)rect.Width, height = (int)rect.Height })); }
protected override Response GetResponse(AutomationElement automationElement, CommandEnvironment environment, Dictionary <string, object> parameters, System.Threading.CancellationToken cancellationToken) { automationElement.SetText(""); return(Response.CreateSuccessResponse()); }
/// <summary> /// Executes the command. /// </summary> /// <param name="environment">The <see cref="CommandEnvironment"/> to use in executing the command.</param> /// <param name="parameters">The <see cref="Dictionary{string, object}"/> containing the command parameters.</param> /// <returns>The JSON serialized string representing the command response.</returns> public override Response Execute(CommandEnvironment environment, Dictionary <string, object> parameters, System.Threading.CancellationToken cancellationToken) { return(new FindChildElementCommandHandler().TryGetResponse(environment.Cache.AutomationElement, environment, parameters, cancellationToken)); }
/// <summary> /// Executes the command. /// </summary> /// <param name="environment">The <see cref="CommandEnvironment"/> to use in executing the command.</param> /// <param name="parameters">The <see cref="Dictionary{string, object}"/> containing the command parameters.</param> /// <returns>The JSON serialized string representing the command response.</returns> public override Response Execute(CommandEnvironment environment, Dictionary <string, object> parameters) { return(Response.CreateSuccessResponse()); }
public static IDisposable CreateHandler(AutomationElement automationElement, IntPtr hWnd, CommandEnvironment commandEnvironment) { return(new Handler(automationElement, hWnd, commandEnvironment)); }
/// <summary> /// Executes the command. /// </summary> /// <param name="environment">The <see cref="CommandEnvironment"/> to use in executing the command.</param> /// <param name="parameters">The <see cref="Dictionary{string, object}"/> containing the command parameters.</param> /// <returns>The JSON serialized string representing the command response.</returns> public override Response Execute(CommandEnvironment environment, Dictionary <string, object> parameters) { string errorMessage = string.Format(CultureInfo.InvariantCulture, "Command '{0}' not implemented", this.commandName); return(Response.CreateErrorResponse(501, errorMessage)); }
protected override Response GetResponse(AutomationElement automationElement, CommandEnvironment environment, Dictionary <string, object> parameters) { return(Response.CreateSuccessResponse(automationElement.GetText())); }
protected override Response GetResponse(AutomationElement automationElement, CommandEnvironment environment, Dictionary <string, object> parameters) { if (!parameters.TryGetValue("using", out var mechanism)) { return(Response.CreateMissingParametersResponse("using")); } if (!parameters.TryGetValue("value", out var criteria)) { return(Response.CreateMissingParametersResponse("value")); } var tokenSource = new CancellationTokenSource(); tokenSource.CancelAfter(environment.ImplicitWaitTimeout); var token = tokenSource.Token; try { var elements = environment.Cache.FindElements(automationElement, mechanism.ToString(), criteria.ToString(), token) .ToList() .Distinct(new TupleEqualityComparer()) .ToList(); foreach (var e in elements) { System.Diagnostics.Debug.WriteLine($"{e.Item1} :: {e.Item2.ToDiagString()}"); } environment.Cache.AddToCache(elements.ToArray()); var response = new Response { Status = WebDriverStatusCode.Success, SessionId = "", Value = elements.Select(e => new Dictionary <string, object> { { CommandEnvironment.ElementObjectKey, e.Item1 }, { string.Empty, e.Item2.Current.AutomationId } }).ToList() }; if (response.Status == WebDriverStatusCode.Success) { // Return early for success return(response); } if (response.Status != WebDriverStatusCode.NoSuchElement) { if (mechanism.ToString().ToUpperInvariant() != "XPATH" && response.Status == WebDriverStatusCode.InvalidSelector) { //continue; } // Also return early for response of not NoSuchElement. return(response); } string errorMessage = string.Format(CultureInfo.InvariantCulture, "No element found for {0} == '{1}'", mechanism.ToString(), criteria.ToString()); response = Response.CreateErrorResponse(WebDriverStatusCode.NoSuchElement, errorMessage); return(response); } catch (Exception e) { throw; } }