public ServerResponse GetAutomations()
        {
            try
            {
                var apiResponse            = AutomationsAPIManager.GetAutomations(_authAPIManager);
                var automationPackageNames = apiResponse.Data.Items.Where(
                    a => !string.IsNullOrEmpty(a.OriginalPackageName) &&
                    a.OriginalPackageName.EndsWith(".nupkg") &&
                    a.AutomationEngine.Equals("OpenBots")
                    ).Select(a => a.OriginalPackageName).ToList();
                return(new ServerResponse(automationPackageNames, apiResponse.StatusCode.ToString()));
            }
            catch (Exception ex)
            {
                var errorCode    = ex.GetType().GetProperty("ErrorCode")?.GetValue(ex, null)?.ToString() ?? string.Empty;
                var errorMessage = ex.GetType().GetProperty("ErrorContent")?.GetValue(ex, null)?.ToString() ?? ex.Message;

                // Log Event (Error)
                _fileLogger.LogEvent("Get Automations", $"Error occurred while getting automations from the Server; " +
                                     $"Error Code = {errorCode}; Error Message = {errorMessage}", LogEventLevel.Error);

                // Form Server Response
                return(new ServerResponse(null, errorCode, errorMessage));
            }
        }
Beispiel #2
0
        public bool ExecuteTask(string projectPackage, ServerConnectionSettings settings, bool isServerAutomation)
        {
            if (!_executionManager.IsEngineBusy)
            {
                bool   isSuccessful;
                string projectDirectoryPath, configFilePath, mainScriptFilePath;
                projectDirectoryPath = configFilePath = mainScriptFilePath = string.Empty;
                try
                {
                    _executionManager.SetEngineStatus(true);
                    if (isServerAutomation)
                    {
                        // projectPackage is "Name" of the Project Package here
                        string filter     = $"originalPackageName eq '{projectPackage}'";
                        var    automation = AutomationsAPIManager.GetAutomations(_authAPIManager, filter).Data?.Items.FirstOrDefault();
                        mainScriptFilePath = AutomationManager.DownloadAndExtractAutomation(_authAPIManager, automation, string.Empty, settings.DNSHost, settings.UserName, out configFilePath);
                    }
                    else
                    {
                        // projectPackage is "Path" of the Project Package here
                        mainScriptFilePath = AutomationManager.GetMainScriptFilePath(projectPackage, out configFilePath);
                    }

                    projectDirectoryPath = Path.GetDirectoryName(mainScriptFilePath);
                    NugetPackageManager.InstallProjectDependencies(configFilePath, settings.DNSHost, settings.UserName);
                    var assembliesList = NugetPackageManager.LoadPackageAssemblies(configFilePath, settings.DNSHost, settings.UserName);

                    RunAttendedAutomation(mainScriptFilePath, settings, assembliesList);

                    isSuccessful = true;
                }
                catch (Exception)
                {
                    isSuccessful = false;
                }
                finally
                {
                    // Delete Project Directory
                    if (Directory.Exists(projectDirectoryPath))
                    {
                        Directory.Delete(projectDirectoryPath, true);
                    }

                    _executionManager.SetEngineStatus(false);
                }

                return(isSuccessful);
            }
            return(false);
        }
Beispiel #3
0
        public bool ExecuteTask(string projectPackage, ServerConnectionSettings settings, bool isServerAutomation)
        {
            if (!_executionManager.IsEngineBusy)
            {
                bool   isSuccessful;
                string projectDirectoryPath, configFilePath, mainScriptFilePath;
                projectDirectoryPath = configFilePath = mainScriptFilePath = string.Empty;
                try
                {
                    _executionManager.SetEngineStatus(true);
                    if (isServerAutomation)
                    {
                        // projectPackage is "Name" of the Project Package here
                        string filter     = $"originalPackageName eq '{projectPackage}'";
                        var    automation = AutomationsAPIManager.GetAutomations(_authAPIManager, filter).Data?.Items.FirstOrDefault();
                        mainScriptFilePath = AutomationManager.DownloadAndExtractAutomation(_authAPIManager, automation, string.Empty, settings.DNSHost, settings.UserName, out projectDirectoryPath, out configFilePath);
                    }
                    else
                    {
                        // projectPackage is "Path" of the Project Package here
                        mainScriptFilePath = AutomationManager.GetMainScriptFilePath(projectPackage, out configFilePath);
                    }

                    projectDirectoryPath = Path.GetDirectoryName(mainScriptFilePath);
                    string projectType    = JObject.Parse(File.ReadAllText(configFilePath))["ProjectType"].ToString();
                    var    automationType = (AutomationType)Enum.Parse(typeof(AutomationType), projectType);
                    switch (automationType)
                    {
                    case AutomationType.OpenBots:
                        NugetPackageManager.InstallProjectDependencies(configFilePath, settings.DNSHost, settings.UserName);
                        var assembliesList = NugetPackageManager.LoadPackageAssemblies(configFilePath, settings.DNSHost, settings.UserName);
                        RunOpenBotsAutomation(mainScriptFilePath, Path.GetFileNameWithoutExtension(projectPackage), settings, assembliesList);
                        break;

                    case AutomationType.Python:
                        RunPythonAutomation(mainScriptFilePath, Path.GetFileNameWithoutExtension(projectPackage), settings);
                        break;

                    case AutomationType.TagUI:
                        RunTagUIAutomation(mainScriptFilePath, Path.GetFileNameWithoutExtension(projectPackage), settings, projectDirectoryPath);
                        break;

                    case AutomationType.CSScript:
                        RunCSharpAutomation(mainScriptFilePath, Path.GetFileNameWithoutExtension(projectPackage), settings);
                        break;

                    default:
                        throw new NotImplementedException($"Specified automation type \"{automationType}\" is not supported in the OpenBots Agent.");
                    }

                    isSuccessful = true;
                }
                catch (Exception)
                {
                    isSuccessful = false;
                }
                finally
                {
                    // Delete Project Directory
                    if (Directory.Exists(projectDirectoryPath))
                    {
                        Directory.Delete(projectDirectoryPath, true);
                    }

                    _executionManager.SetEngineStatus(false);
                }

                return(isSuccessful);
            }
            return(false);
        }
        private void ExecuteJob()
        {
            // Log Event
            _fileLogger.LogEvent("Job Execution", "Job execution started");

            // Peek Job
            var job = JobsQueueManager.PeekJob();

            // Log Event
            _fileLogger.LogEvent("Job Execution", "Attempt to fetch Automation Detail");

            // Get Automation Info
            var automation = AutomationsAPIManager.GetAutomation(_authAPIManager, job.AutomationId.ToString());

            // Update LastReportedMessage and LastReportedWork
            _agentHeartbeat.LastReportedMessage = "Job execution started";
            _agentHeartbeat.LastReportedWork    = automation.Name;

            // Log Event
            _fileLogger.LogEvent("Job Execution", "Attempt to download/retrieve Automation");

            string connectedUserName = _connectionSettingsManager.ConnectionSettings.UserName;
            string userDomainName    = _connectionSettingsManager.ConnectionSettings.DNSHost;

            // Download Automation and Extract Files and Return File Paths of ProjectConfig and MainScript
            automation.AutomationEngine = string.IsNullOrEmpty(automation.AutomationEngine) ? "OpenBots" : automation.AutomationEngine;
            string configFilePath;
            string executionDirPath;
            var    mainScriptFilePath = AutomationManager.DownloadAndExtractAutomation(_authAPIManager, automation, job.Id.ToString(), userDomainName, connectedUserName, out executionDirPath, out configFilePath);

            // Install Project Dependencies
            List <string> assembliesList = null;

            if (automation.AutomationEngine == "OpenBots")
            {
                NugetPackageManager.InstallProjectDependencies(configFilePath, userDomainName, connectedUserName);
                assembliesList = NugetPackageManager.LoadPackageAssemblies(configFilePath, userDomainName, connectedUserName);
            }

            // Log Event
            _fileLogger.LogEvent("Job Execution", "Attempt to update Job Status (Pre-execution)");

            // Create Automation Execution Log (Execution Started)
            _executionLog = ExecutionLogsAPIManager.CreateExecutionLog(_authAPIManager, new AutomationExecutionLog(
                                                                           null, false, null, DateTime.UtcNow, null, null, null, null, null, job.Id, job.AutomationId, job.AgentId,
                                                                           DateTime.UtcNow, null, null, null, "Job has started processing"));

            // Update Job Status (InProgress)
            JobsAPIManager.UpdateJobStatus(_authAPIManager, job.AgentId.ToString(), job.Id.ToString(),
                                           JobStatusType.InProgress, new JobErrorViewModel());

            // Update Job Start Time
            JobsAPIManager.UpdateJobPatch(_authAPIManager, job.Id.ToString(),
                                          new List <Operation>()
            {
                new Operation()
                {
                    Op = "replace", Path = "/startTime", Value = DateTime.UtcNow.ToString("yyyy-MM-dd'T'HH:mm:ss.fffffff'Z'")
                }
            });

            // Log Event
            _fileLogger.LogEvent("Job Execution", "Attempt to execute process");

            AgentViewModel    agent          = AgentsAPIManager.GetAgent(_authAPIManager, job.AgentId.ToString());
            var               userCredential = CredentialsAPIManager.GetCredentials(_authAPIManager, agent.CredentialId.ToString());
            MachineCredential credential     = new MachineCredential
            {
                Name           = userCredential.Name,
                Domain         = userCredential.Domain,
                UserName       = userCredential.UserName,
                PasswordSecret = userCredential.PasswordSecret
            };

            // Run Automation
            RunAutomation(job, automation, credential, mainScriptFilePath, executionDirPath, assembliesList);

            // Log Event
            _fileLogger.LogEvent("Job Execution", "Job execution completed");

            // Log Event
            _fileLogger.LogEvent("Job Execution", "Attempt to update Job Status (Post-execution)");

            // Update Job End Time
            JobsAPIManager.UpdateJobPatch(_authAPIManager, job.Id.ToString(),
                                          new List <Operation>()
            {
                new Operation()
                {
                    Op = "replace", Path = "/endTime", Value = DateTime.UtcNow.ToString("yyyy-MM-dd'T'HH:mm:ss.fffffff'Z'")
                },
                new Operation()
                {
                    Op = "replace", Path = "/isSuccessful", Value = true
                }
            });

            // Delete Job Directory
            try
            {
                Directory.Delete(executionDirPath, true);
            }
            catch (Exception)
            {
                // Appended 'Long Path Specifier' before the Directory Path
                Directory.Delete(@"\\?\" + executionDirPath, true);
            }

            // Update Automation Execution Log (Execution Finished)
            _executionLog.CompletedOn = DateTime.UtcNow;
            _executionLog.Status      = "Job has finished processing";
            ExecutionLogsAPIManager.UpdateExecutionLog(_authAPIManager, _executionLog);

            // Update Job Status (Completed)
            JobsAPIManager.UpdateJobStatus(_authAPIManager, job.AgentId.ToString(), job.Id.ToString(),
                                           JobStatusType.Completed, new JobErrorViewModel());

            _fileLogger.LogEvent("Job Execution", "Job status updated. Removing from queue.");

            // Dequeue the Job
            JobsQueueManager.DequeueJob();

            _isSuccessfulExecution = true;
            _agentHeartbeat.LastReportedMessage = "Job execution completed";
        }
Beispiel #5
0
        public static string DownloadAndExtractAutomation(AuthAPIManager authAPIManager, Automation automation, string jobId, string domainName, string userName, out string executionDirectoryPath, out string configFilePath)
        {
            configFilePath         = "";
            executionDirectoryPath = "";

            // Check if (Root) Automations Directory Exists (under User's AppData Folder), If Not create it
            var automationsDirectory = Path.Combine(new EnvironmentSettings().GetEnvironmentVariablePath(domainName, userName), "Automations",
                                                    automation.AutomationEngine);

            if (!Directory.Exists(automationsDirectory))
            {
                Directory.CreateDirectory(automationsDirectory);
            }

            // Automation Directory
            var processDirectoryPath = Path.Combine(automationsDirectory, automation.Id.ToString());


            // Create Automation Directory named as Automation Id If it doesn't exist
            if (!Directory.Exists(processDirectoryPath))
            {
                Directory.CreateDirectory(processDirectoryPath);
            }

            // Automation Nuget Package Path
            var processNugetFilePath = Path.Combine(processDirectoryPath, automation.Name.ToString() + ".nupkg");

            // Execution Directory Path
            executionDirectoryPath = Path.Combine(processDirectoryPath, string.IsNullOrEmpty(jobId) ? new Guid().ToString() : jobId);
            if (!Directory.Exists(executionDirectoryPath))
            {
                Directory.CreateDirectory(executionDirectoryPath);
            }

            var processZipFilePath = Path.Combine(executionDirectoryPath, automation.Name.ToString() + ".zip");

            // Check if Automation (.nupkg) file exists if Not Download it
            if (!File.Exists(processNugetFilePath))
            {
                // Download Automation by Id
                var apiResponse = AutomationsAPIManager.ExportAutomation(authAPIManager, automation.Id.ToString());

                // Write Downloaded(.nupkg) file in the Automation Directory
                File.WriteAllBytes(processNugetFilePath, apiResponse.Data.ToArray());
            }

            // Create .zip file if it doesn't exist
            if (!File.Exists(processZipFilePath))
            {
                File.Copy(processNugetFilePath, processZipFilePath);
            }

            var extractToDirectoryPath = Path.ChangeExtension(processZipFilePath, null);

            // Extract Files/Folders from (.zip) file
            DecompressFile(processZipFilePath, extractToDirectoryPath);

            // Delete .zip File
            File.Delete(processZipFilePath);

            configFilePath = Directory.GetFiles(extractToDirectoryPath, "project.obconfig", SearchOption.AllDirectories).First();
            string mainFileName = JObject.Parse(File.ReadAllText(configFilePath))["Main"].ToString();

            // Return "Main" Script File Path of the Automation
            return(Directory.GetFiles(extractToDirectoryPath, mainFileName, SearchOption.AllDirectories).First());
        }