Пример #1
0
        /// <summary>
        /// Deserializes a valid JSON file back into user-defined commands
        /// </summary>
        public static Script DeserializeFile(string filePath, bool isDialogResultYes = false)
        {
            var serializerSettings = new JsonSerializerSettings()
            {
                TypeNameHandling = TypeNameHandling.Objects,
                Error            = HandleDeserializationError
            };

            Script  deserializedData = JsonConvert.DeserializeObject <Script>(File.ReadAllText(filePath), serializerSettings);
            Version deserializedScriptVersion;

            if (deserializedData != null)
            {
                if (deserializedData.Version == null)
                {
                    deserializedData.Version = "0.0.0.0";
                }

                deserializedScriptVersion = new Version(deserializedData.Version);
            }
            else
            {
                deserializedScriptVersion = new Version("0.0.0.0");
            }

            //if deserialized Script version is lower than than the current application version
            if (deserializedScriptVersion.CompareTo(new Version(Application.ProductVersion)) < 0)
            {
                var dialogResult = MessageBox.Show($"Attempting to open a Script file from OpenBots Studio {deserializedScriptVersion}. " +
                                                   $"Would you like to attempt to convert this Script to {Application.ProductVersion}?",
                                                   "Convert Script", MessageBoxButtons.YesNo);

                if (dialogResult == DialogResult.Yes || isDialogResultYes)
                {
                    deserializedData = ConvertToLatestVersion(filePath, deserializedScriptVersion.ToString());
                }
            }

            //update ProjectPath variable
            var projectPathVariable = deserializedData.Variables.Where(v => v.VariableName == "ProjectPath").SingleOrDefault();

            if (projectPathVariable != null)
            {
                deserializedData.Variables.Remove(projectPathVariable);
            }

            projectPathVariable = new ScriptVariable
            {
                VariableName  = "ProjectPath",
                VariableValue = "Value Provided at Runtime"
            };
            deserializedData.Variables.Add(projectPathVariable);


            return(deserializedData);
        }
Пример #2
0
        /// <summary>
        /// Deserializes a valid JSON file back into user-defined commands
        /// </summary>
        public static Script DeserializeFile(EngineContext engineContext, bool isDialogResultYes = false)
        {
            var serializerSettings = new JsonSerializerSettings();

            if (engineContext.IsTest)
            {
                serializerSettings = new JsonSerializerSettings()
                {
                    TypeNameHandling = TypeNameHandling.Objects,
                };
            }
            else
            {
                serializerSettings = new JsonSerializerSettings()
                {
                    TypeNameHandling = TypeNameHandling.Objects,
                    Error            = HandleDeserializationError,
                    ContractResolver = new ScriptAutofacContractResolver(engineContext.Container)
                };
            }

            Script  deserializedData = JsonConvert.DeserializeObject <Script>(File.ReadAllText(engineContext.FilePath), serializerSettings);
            Version deserializedScriptVersion;

            if (deserializedData != null)
            {
                if (deserializedData.Version == null)
                {
                    deserializedData.Version = "0.0.0.0";
                }

                deserializedScriptVersion = new Version(deserializedData.Version);
            }
            else
            {
                deserializedScriptVersion = new Version("0.0.0.0");
            }

            //if deserialized Script version is lower than than the current application version
            if (!engineContext.IsTest && deserializedScriptVersion.CompareTo(new Version(Application.ProductVersion)) < 0 && !isDialogResultYes)
            {
                var dialogResult = MessageBox.Show($"Attempting to open a Script file from OpenBots Studio {deserializedScriptVersion}. " +
                                                   $"Would you like to attempt to convert this Script to {Application.ProductVersion}? " +
                                                   "\n\nWarning: Once a Script has been converted, it cannot be undone.",
                                                   "Convert Script", MessageBoxButtons.YesNo);

                if (dialogResult == DialogResult.Yes)
                {
                    deserializedData = ConvertScriptToLatestVersion(engineContext.FilePath, engineContext.Container, deserializedScriptVersion.ToString());
                }
            }
            else if (!engineContext.IsTest && deserializedScriptVersion.CompareTo(new Version(Application.ProductVersion)) < 0 && isDialogResultYes)
            {
                deserializedData = ConvertScriptToLatestVersion(engineContext.FilePath, engineContext.Container, deserializedScriptVersion.ToString());
            }

            //update ProjectPath variable
            var projectPathVariable = deserializedData.Variables.Where(v => v.VariableName == "ProjectPath").SingleOrDefault();

            if (projectPathVariable != null)
            {
                deserializedData.Variables.Remove(projectPathVariable);
            }

            projectPathVariable = new ScriptVariable
            {
                VariableName  = "ProjectPath",
                VariableType  = typeof(string),
                VariableValue = "Value Provided at Runtime"
            };
            deserializedData.Variables.Add(projectPathVariable);


            return(deserializedData);
        }
Пример #3
0
        public virtual void ScriptFinished(ScriptFinishedResult result, string error = null)
        {
            if (ChildScriptFailed && !ChildScriptErrorCaught)
            {
                error  = "Terminate with failure";
                result = ScriptFinishedResult.Error;
                Log.Fatal("Result Code: " + result.ToString());
            }
            else
            {
                Log.Information("Result Code: " + result.ToString());
            }

            //add result variable if missing
            var resultVar = EngineContext.Variables.Where(f => f.VariableName == "OpenBots.Result").FirstOrDefault();

            //handle if variable is missing
            if (resultVar == null)
            {
                resultVar = new OBScriptVariable()
                {
                    VariableName = "OpenBots.Result", VariableValue = ""
                }
            }
            ;

            //check value
            var resultValue = resultVar.VariableValue.ToString();

            if (error == null)
            {
                Log.Information("Error: None");

                if (string.IsNullOrEmpty(resultValue))
                {
                    EngineContext.TaskResult = "Successfully Completed Script";
                }
                else
                {
                    EngineContext.TaskResult = resultValue;
                }
            }

            else
            {
                if (ErrorsOccured.Count > 0)
                {
                    error = ErrorsOccured.OrderByDescending(x => x.LineNumber).FirstOrDefault().StackTrace;
                }

                Log.Error("Error: " + error);
                EngineContext.TaskResult = error;
            }

            if ((EngineContext.ScriptEngine != null && !EngineContext.IsChildEngine) ||
                (EngineContext.IsServerExecution && !EngineContext.IsServerChildExecution))
            {
                Log.CloseAndFlush();
            }

            EngineContext.CurrentEngineStatus = EngineStatus.Finished;
            ScriptFinishedEventArgs args = new ScriptFinishedEventArgs
            {
                LoggedOn      = DateTime.Now,
                Result        = result,
                Error         = error,
                ExecutionTime = _stopWatch.Elapsed,
                FileName      = EngineContext.FilePath
            };

            //convert to json
            var serializedArguments = JsonConvert.SerializeObject(args);

            //write execution metrics
            if (EngineContext.EngineSettings.TrackExecutionMetrics && (EngineContext.FilePath != null))
            {
                string summaryLoggerFilePath = Path.Combine(Folders.GetFolder(FolderType.LogFolder), "OpenBots Execution Summary Logs.txt");
                Logger summaryLogger         = new LoggingMethods().CreateJsonFileLogger(summaryLoggerFilePath, RollingInterval.Infinite);
                summaryLogger.Information(serializedArguments);

                if (!EngineContext.IsChildEngine)
                {
                    summaryLogger.Dispose();
                }
            }

            ScriptFinishedEvent?.Invoke(this, args);
        }
Пример #4
0
        private async void ExecuteScript()
        {
            try
            {
                EngineContext.CurrentEngineStatus = EngineStatus.Running;

                //create stopwatch for metrics tracking
                _stopWatch = new Stopwatch();
                _stopWatch.Start();

                //log starting
                ReportProgress("Bot Engine Started: " + DateTime.Now.ToString());

                //get automation script
                OBScript automationScript;

                ReportProgress("Deserializing File");
                Log.Information("Script Path: " + EngineContext.FilePath);
                automationScript = OBScript.DeserializeFile(EngineContext);

                //initialize roslyn instance
                EngineContext.ImportedNamespaces = automationScript.ImportedNamespaces;
                EngineContext.InitializeEngineInstance();

                ReportProgress("Creating Variable List");

                //set variables if they were passed in
                if (EngineContext.Variables != null)
                {
                    foreach (var var in EngineContext.Variables)
                    {
                        var variableFound = automationScript.Variables.Where(f => f.VariableName == var.VariableName).FirstOrDefault();

                        if (variableFound != null)
                        {
                            variableFound.VariableValue = var.VariableValue;
                        }
                    }
                }

                EngineContext.Variables = automationScript.Variables;

                //update ProjectPath variable
                var projectPathVariable = EngineContext.Variables.Where(v => v.VariableName == "ProjectPath").SingleOrDefault();

                if (projectPathVariable != null)
                {
                    projectPathVariable.VariableValue = "@\"" + EngineContext.ProjectPath + '"';
                }
                else
                {
                    projectPathVariable = new OBScriptVariable
                    {
                        VariableName  = "ProjectPath",
                        VariableType  = typeof(string),
                        VariableValue = "@\"" + EngineContext.ProjectPath + '"'
                    };
                    EngineContext.Variables.Add(projectPathVariable);
                }

                foreach (OBScriptVariable var in EngineContext.Variables)
                {
                    dynamic evaluatedValue = await VariableMethods.InstantiateVariable(var.VariableName, (string)var.VariableValue, var.VariableType, EngineContext);

                    VariableMethods.SetVariableValue(evaluatedValue, EngineContext, var.VariableName);
                }

                ReportProgress("Creating Argument List");

                //set arguments if they were passed in
                if (EngineContext.Arguments != null)
                {
                    foreach (var arg in EngineContext.Arguments)
                    {
                        var argumentFound = automationScript.Arguments.Where(f => f.ArgumentName == arg.ArgumentName).FirstOrDefault();

                        if (argumentFound != null)
                        {
                            argumentFound.ArgumentValue = arg.ArgumentValue;
                        }
                    }
                }

                EngineContext.Arguments = automationScript.Arguments;

                //used by RunTaskCommand to assign parent values to child arguments
                if (EngineContext.IsChildEngine)
                {
                    foreach (ScriptArgument arg in EngineContext.Arguments)
                    {
                        await VariableMethods.InstantiateVariable(arg.ArgumentName, "", arg.ArgumentType, EngineContext);

                        VariableMethods.SetVariableValue(arg.ArgumentValue, EngineContext, arg.ArgumentName);
                    }
                }
                else
                {
                    foreach (ScriptArgument arg in EngineContext.Arguments)
                    {
                        dynamic evaluatedValue = await VariableMethods.InstantiateVariable(arg.ArgumentName, (string)arg.ArgumentValue, arg.ArgumentType, EngineContext);

                        VariableMethods.SetVariableValue(evaluatedValue, EngineContext, arg.ArgumentName);
                    }
                }

                ReportProgress("Creating Element List");

                //set elements if they were passed in
                if (EngineContext.Elements != null)
                {
                    foreach (var elem in EngineContext.Elements)
                    {
                        var elementFound = automationScript.Elements.Where(f => f.ElementName == elem.ElementName).FirstOrDefault();

                        if (elementFound != null)
                        {
                            elementFound.ElementValue = elem.ElementValue;
                        }
                    }
                }

                EngineContext.Elements = automationScript.Elements;

                //execute commands
                ScriptAction startCommand = automationScript.Commands.Where(x => x.ScriptCommand.LineNumber <= EngineContext.StartFromLineNumber)
                                            .Last();

                int startCommandIndex = automationScript.Commands.FindIndex(x => x.ScriptCommand.LineNumber == startCommand.ScriptCommand.LineNumber);

                while (startCommandIndex < automationScript.Commands.Count)
                {
                    if (IsCancellationPending)
                    {
                        ReportProgress("Cancelling Script");
                        ScriptFinished(ScriptFinishedResult.Cancelled);
                        return;
                    }

                    await ExecuteCommand(automationScript.Commands[startCommandIndex]);

                    startCommandIndex++;
                }

                if (IsCancellationPending)
                {
                    ScriptFinished(ScriptFinishedResult.Cancelled);
                }
                else
                {
                    ScriptFinished(ScriptFinishedResult.Successful);
                }
            }
            catch (Exception ex)
            {
                ScriptFinished(ScriptFinishedResult.Error, ex.ToString());
            }

            if (!EngineContext.IsChildEngine || (EngineContext.IsServerExecution && !EngineContext.IsServerChildExecution))
            {
                EngineContext.EngineLogger.Dispose();
            }
        }