Exemplo n.º 1
0
        /// <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))
            {
                var processName = desiredCapabilities.GetParameterValue <string>("processName");

                process = Process.GetProcessesByName(processName).FirstOrDefault();

                // searching by name as regular expression pattern
                if (process == null)
                {
                    var regex = new Regex(processName);
                    process = Process.GetProcesses().FirstOrDefault(x => regex.IsMatch(x.ProcessName));
                }

                if (process == null)
                {
                    return(Response.CreateErrorResponse(-1, $"Cannot attach to process '{processName}', 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);

                    process = ApplicationProcess.StartProcessFromPath(exePath.ToString(), processName, mainWindowTitle);
                    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);
        }
        /// <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);
        }