private async void txtSampleSearch_KeyDown(object sender, KeyEventArgs e)
        {
            lblError.Text = "";
            var searchResults = new List <IPackageSearchMetadata>();

            if (e.KeyCode == Keys.Enter)
            {
                try
                {
                    if (lblGalleryProjects.Text == "Gallery Automations")
                    {
                        searchResults.AddRange(await NugetPackageManager.SearchPackages(txtSampleSearch.Text, _galleryAutomationsSourceUrl, false));
                    }
                    else if (lblGalleryProjects.Text == "Gallery Samples")
                    {
                        searchResults.AddRange(await NugetPackageManager.SearchPackages(txtSampleSearch.Text, _gallerySamplesSourceUrl, false));
                    }
                    else if (lblGalleryProjects.Text == "Gallery Templates")
                    {
                        searchResults.AddRange(await NugetPackageManager.SearchPackages(txtSampleSearch.Text, _galleryTemplatesSourceUrl, false));
                    }
                }
                catch (Exception ex)
                {
                    lblError.Text = "Error: " + ex.Message;
                }

                PopulateListBox(searchResults);
                e.Handled = true;
            }
        }
Exemplo n.º 2
0
        private async void frmGalleryProject_LoadAsync(object sender, EventArgs e)
        {
            PopulatetvPackageFeeds();
            pnlProjectVersion.Hide();
            pnlProjectDetails.Hide();

            try
            {
                foreach (DataRow row in _packageSourceDT.Rows)
                {
                    if (row[0].ToString() == "True")
                    {
                        try
                        {
                            _allResults.AddRange(await NugetPackageManager.SearchPackages("", row[2].ToString(), _includePrerelease));
                        }
                        catch (Exception ex)
                        {
                            //invalid source
                            lblError.Text = "Error: " + ex.Message;
                        }
                    }
                }

                await GetCurrentDepencies();

                PopulateListBox(_projectDependencies);
            }
            catch (Exception ex)
            {
                //not connected to internet
                lblError.Text = "Error: " + ex.Message;
            }
        }
Exemplo n.º 3
0
        private async void installDefaultToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                string localPackagesPath = Folders.GetFolder(FolderType.LocalAppDataPackagesFolder);

                if (Directory.Exists(localPackagesPath) && Directory.GetDirectories(localPackagesPath).Length > 0)
                {
                    MessageBox.Show("Close OpenBots and delete all packages first.", "Delete Packages");
                    return;
                }

                //show spinner and disable package manager related buttons
                NotifySync("Installing and loading package assemblies...", Color.White);

                installDefaultToolStripMenuItem.Enabled = false;
                packageManagerToolStripMenuItem.Enabled = false;
                uiBtnPackageManager.Enabled             = false;

                Directory.CreateDirectory(localPackagesPath);

                //require admin access to move/download packages and their dependency .nupkg files to Program Files
                await NugetPackageManager.DownloadCommandDependencyPackages();

                //unpack commands using Program Files as the source repository
                var commandVersion = Regex.Matches(Application.ProductVersion, @"\d+\.\d+\.\d+")[0].ToString();
                Dictionary <string, string> dependencies = Project.DefaultCommandGroups.ToDictionary(x => $"OpenBots.Commands.{x}", x => commandVersion);

                foreach (var dep in dependencies)
                {
                    await NugetPackageManager.InstallPackage(dep.Key, dep.Value, new Dictionary <string, string>(),
                                                             Folders.GetFolder(FolderType.ProgramFilesPackagesFolder));
                }

                //load existing command assemblies
                string configPath   = Path.Combine(ScriptProjectPath, "project.obconfig");
                var    assemblyList = NugetPackageManager.LoadPackageAssemblies(configPath);
                _builder   = AppDomainSetupManager.LoadBuilder(assemblyList, _typeContext.GroupedTypes);
                AContainer = _builder.Build();

                LoadCommands(this);
                ReloadAllFiles();
            }
            catch (Exception ex)
            {
                if (ex is UnauthorizedAccessException)
                {
                    MessageBox.Show("Close Visual Studio and run as Admin to install default packages.", "Unauthorized");
                }
                else
                {
                    Notify("Error: " + ex.Message, Color.Red);
                }
            }

            //hide spinner and enable package manager related buttons
            installDefaultToolStripMenuItem.Enabled = true;
            packageManagerToolStripMenuItem.Enabled = true;
            uiBtnPackageManager.Enabled             = true;
        }
        private async void DownloadAndOpenProject(string projectId, string version)
        {
            try
            {
                string packageName = $"{projectId}.{version}";
                Cursor.Current = Cursors.WaitCursor;
                lblError.Text  = $"Downloading {packageName}";

                if (lblGalleryProjects.Text == "Gallery Automations")
                {
                    await NugetPackageManager.DownloadPackage(projectId, version, _projectLocation, _projectName, _galleryAutomationsSourceUrl);
                }
                else if (lblGalleryProjects.Text == "Gallery Samples")
                {
                    await NugetPackageManager.DownloadPackage(projectId, version, _projectLocation, _projectName, _gallerySamplesSourceUrl);
                }
                else if (lblGalleryProjects.Text == "Gallery Templates")
                {
                    await NugetPackageManager.DownloadPackage(projectId, version, _projectLocation, _projectName, _galleryTemplatesSourceUrl);
                }

                lblError.Text = string.Empty;
                DialogResult  = DialogResult.OK;
            }
            catch (Exception ex)
            {
                lblError.Text = "Error: " + ex.Message;
            }
        }
Exemplo n.º 5
0
        private void packageManagerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (IsScriptRunning)
            {
                Notify("Package Manager cannot be opened while a script is running.", Color.Yellow);
                return;
            }

            string configPath = Path.Combine(ScriptProjectPath, "project.obconfig");
            frmGalleryPackageManager frmManager = new frmGalleryPackageManager(ScriptProject.Dependencies);

            frmManager.ShowDialog();

            if (frmManager.DialogResult == DialogResult.OK)
            {
                ScriptProject.Dependencies = ScriptProject.Dependencies.OrderBy(x => x.Key).ToDictionary(x => x.Key, x => x.Value);
                File.WriteAllText(configPath, JsonConvert.SerializeObject(ScriptProject));

                NotifySync("Loading package assemblies...", Color.White);

                var assemblyList = NugetPackageManager.LoadPackageAssemblies(configPath);
                _builder   = AppDomainSetupManager.LoadBuilder(assemblyList, _typeContext.GroupedTypes);
                AContainer = _builder.Build();

                LoadCommands(this);
                ReloadAllFiles();
            }

            frmManager.Dispose();
        }
        private async void lbxGalleryProjects_ItemClick(object sender, int index)
        {
            try
            {
                string projectId = lbxGalleryProjects.ClickedItem.Id;
                List <IPackageSearchMetadata> metadata = new List <IPackageSearchMetadata>();

                if (lblGalleryProjects.Text == "Gallery Automations")
                {
                    metadata.AddRange(await NugetPackageManager.GetPackageMetadata(projectId, _galleryAutomationsSourceUrl, true));
                }
                else if (lblGalleryProjects.Text == "Gallery Samples")
                {
                    metadata.AddRange(await NugetPackageManager.GetPackageMetadata(projectId, _gallerySamplesSourceUrl, true));
                }
                else if (lblGalleryProjects.Text == "Gallery Templates")
                {
                    metadata.AddRange(await NugetPackageManager.GetPackageMetadata(projectId, _galleryTemplatesSourceUrl, true));
                }

                string latestVersion = metadata.LastOrDefault().Identity.Version.ToString();

                _projectVersions.Clear();
                if (lblGalleryProjects.Text == "Gallery Automations")
                {
                    _projectVersions.AddRange(await NugetPackageManager.GetPackageVersions(projectId, _galleryAutomationsSourceUrl, true));
                }
                else if (lblGalleryProjects.Text == "Gallery Samples")
                {
                    _projectVersions.AddRange(await NugetPackageManager.GetPackageVersions(projectId, _gallerySamplesSourceUrl, true));
                }
                else if (lblGalleryProjects.Text == "Gallery Templates")
                {
                    _projectVersions.AddRange(await NugetPackageManager.GetPackageVersions(projectId, _galleryTemplatesSourceUrl, true));
                }

                List <string> versionList = _projectVersions.Select(x => x.ToString()).ToList();
                versionList.Reverse();

                cbxVersion.Items.Clear();
                foreach (var version in versionList)
                {
                    cbxVersion.Items.Add(version);
                }

                _selectedPackageMetaData = metadata;

                pnlProjectVersion.Show();
                pnlProjectDetails.Show();
                uiBtnOpen.Enabled       = true;
                cbxVersion.SelectedItem = latestVersion;
            }
            catch (Exception)
            {
                pnlProjectVersion.Hide();
                pnlProjectDetails.Hide();
                uiBtnOpen.Enabled = false;
            }
        }
        private void uiBtnReloadCommands_Click(object sender, EventArgs e)
        {
            NotifySync("Loading package assemblies...", Color.White);
            string configPath   = Path.Combine(ScriptProjectPath, "project.obconfig");
            var    assemblyList = NugetPackageManager.LoadPackageAssemblies(configPath);

            _builder   = AppDomainSetupManager.LoadBuilder(assemblyList, _typeContext.GroupedTypes);
            AContainer = _builder.Build();
            LoadCommands(this);
            ReloadAllFiles();
        }
Exemplo n.º 8
0
        private void frmProcessingStatus_LoadAsync(object sender, EventArgs e)
        {
            if (_isParentScheduledTask)
            {
                List <string> assemblyList = NugetPackageManager.LoadPackageAssemblies(_configPath, true);
                Dictionary <string, List <Type> > groupedTypes = new Dictionary <string, List <Type> >();
                var builder = AppDomainSetupManager.LoadBuilder(assemblyList, groupedTypes);
                ScriptEngineContext.Container = builder.Build();
            }

            //move engine form to bottom right and bring to front
            if (_engineSettings.ShowDebugWindow)
            {
                BringToFront();
                MoveFormToBottomRight(this);
            }

            CommandControls = new CommandControls();

            //start running
            EngineInstance = new AutomationEngineInstance(ScriptEngineContext);

            if (IsNewTaskSteppedInto)
            {
                EngineInstance.PauseScript();
                uiBtnPause.Image       = Resources.engine_resume;
                uiBtnPause.DisplayText = "Resume";
                uiBtnStepOver.Visible  = true;
                uiBtnStepInto.Visible  = true;

                ScriptEngineContext.ScriptBuilder.CurrentEngine = this;

                //toggle running flag to allow for tab selection
                ScriptEngineContext.ScriptBuilder.IsScriptRunning = false;
                ((frmScriptBuilder)ScriptEngineContext.ScriptBuilder).OpenOpenBotsFile(ScriptEngineContext.FilePath, true);
                ScriptEngineContext.ScriptBuilder.IsScriptRunning = true;
            }

            EngineInstance.ReportProgressEvent    += Engine_ReportProgress;
            EngineInstance.ScriptFinishedEvent    += Engine_ScriptFinishedEvent;
            EngineInstance.LineNumberChangedEvent += EngineInstance_LineNumberChangedEvent;
            EngineInstance.AutomationEngineContext.ScriptEngine = this;
            EngineInstance.IsServerExecution = ServerExecution;

            if (JsonData == null)
            {
                EngineInstance.ExecuteScriptAsync();
            }
            else
            {
                EngineInstance.ExecuteScriptJson();
            }
        }
Exemplo n.º 9
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);
        }
Exemplo n.º 10
0
        private async Task GetCurrentDepencies()
        {
            List <string> nugetDirectoryList = Directory.GetDirectories(_packagesPath).ToList();

            _projectDependencies.Clear();
            foreach (var pair in _projectDependenciesDict)
            {
                var dependency = (await NugetPackageManager.GetPackageMetadata(pair.Key, _packagesPath, _includePrerelease))
                                 .Where(x => x.Identity.Version.ToString() == pair.Value).FirstOrDefault();
                if (dependency != null && nugetDirectoryList.Where(x => x.EndsWith($"{pair.Key}.{pair.Value}")).FirstOrDefault() != null)
                {
                    _projectDependencies.Add(dependency);
                }
            }
        }
Exemplo n.º 11
0
        private async void txtSampleSearch_KeyDown(object sender, KeyEventArgs e)
        {
            lblError.Text = "";
            var searchResults = new List <IPackageSearchMetadata>();

            if (e.KeyCode == Keys.Enter)
            {
                try
                {
                    if (lblPackageCategory.Text == "Project Dependencies")
                    {
                        await GetCurrentDepencies();

                        searchResults.AddRange(_projectDependencies.Where(x => x.Title.ToLower().Contains(txtSampleSearch.Text.ToLower())));
                    }
                    else if (lblPackageCategory.Text == "All Packages")
                    {
                        foreach (DataRow row in _packageSourceDT.Rows)
                        {
                            if (row[0].ToString() == "True")
                            {
                                try
                                {
                                    searchResults.AddRange(await NugetPackageManager.SearchPackages(txtSampleSearch.Text, row[2].ToString(), _includePrerelease));
                                }
                                catch (Exception ex)
                                {
                                    lblError.Text = "Error: " + ex.Message;
                                }
                            }
                        }
                    }
                    else
                    {
                        var sourceURL = _packageSourceDT.AsEnumerable().Where(r => r.Field <string>("Enabled") == "True" && r.Field <string>("Package Name") == lblPackageCategory.Text)
                                        .Select(r => r.Field <string>("Package Source")).FirstOrDefault();
                        searchResults.AddRange(await NugetPackageManager.SearchPackages(txtSampleSearch.Text, sourceURL, _includePrerelease));
                    }
                }
                catch (Exception ex)
                {
                    lblError.Text = "Error: " + ex.Message;
                }

                PopulateListBox(searchResults);
                e.Handled = true;
            }
        }
        private async void frmGalleryProject_LoadAsync(object sender, EventArgs e)
        {
            pnlProjectVersion.Hide();
            pnlProjectDetails.Hide();
            uiBtnOpen.Enabled = false;
            try
            {
                _searchresults = await NugetPackageManager.SearchPackages("", _galleryAutomationsSourceUrl, true);

                PopulateListBox(_searchresults);
            }
            catch (Exception ex)
            {
                //not connected to internet
                lblError.Text = "Error: " + ex.Message;
            }
        }
Exemplo n.º 13
0
        private async void frmGalleryProject_LoadAsync(object sender, EventArgs e)
        {
            PopulatetvPackageFeeds();
            pnlProjectVersion.Hide();
            pnlProjectDetails.Hide();

            _currentCommandsVersion = Regex.Matches(Application.ProductVersion, @"\d+\.\d+\.\d+")[0].ToString();

            //TODO: Will be implemented in future versions
            //check if command dependencies include any that don't match the current app version
            //var outdatedPackage = _projectDependenciesDict.Where(x => x.Key.StartsWith("OpenBots") && x.Value != _currentCommandsVersion).FirstOrDefault().Key;
            //if (!string.IsNullOrEmpty(outdatedPackage))
            //    btnSyncCommandsAndStudio.Visible = true;
            //else
            //    btnSyncCommandsAndStudio.Visible = false;

            try
            {
                foreach (DataRow row in _packageSourceDT.Rows)
                {
                    if (row[0].ToString() == "True")
                    {
                        try
                        {
                            _allResults.AddRange(await NugetPackageManager.SearchPackages("", row[2].ToString(), _includePrerelease));
                        }
                        catch (Exception ex)
                        {
                            //invalid source
                            lblError.Text = "Error: " + ex.Message;
                        }
                    }
                }

                await GetCurrentDepencies();

                PopulateListBox(_projectDependencies);
            }
            catch (Exception ex)
            {
                //not connected to internet
                lblError.Text = "Error: " + ex.Message;
            }
        }
Exemplo n.º 14
0
        private async Task DownloadAndOpenPackage(string packageId, string version)
        {
            try
            {
                tpbLoadingSpinner.Visible = true;
                string packageName = $"{packageId}.{version}";
                Cursor.Current = Cursors.WaitCursor;
                lblError.Text  = $"Installing {packageName}";

                await NugetPackageManager.InstallPackage(packageId, version, _projectDependenciesDict);

                lblError.Text = string.Empty;
            }
            catch (Exception ex)
            {
                tpbLoadingSpinner.Visible = false;
                lblError.Text             = "Error: " + ex.Message;
            }
        }
        private async void tvProjectFeeds_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            lblError.Text = "";
            try
            {
                if (tvProjectFeeds.SelectedNode != null)
                {
                    lbxGalleryProjects.Clear();
                    lbxGalleryProjects.Visible = false;
                    tpbLoadingSpinner.Visible  = true;

                    if (tvProjectFeeds.SelectedNode.Name == "Automations")
                    {
                        lblGalleryProjects.Text = "Gallery Automations";
                        var sourceResults = await NugetPackageManager.SearchPackages("", _galleryAutomationsSourceUrl, false);

                        PopulateListBox(sourceResults);
                    }
                    else if (tvProjectFeeds.SelectedNode.Name == "Samples")
                    {
                        lblGalleryProjects.Text = "Gallery Samples";
                        var sourceResults = await NugetPackageManager.SearchPackages("", _gallerySamplesSourceUrl, false);

                        PopulateListBox(sourceResults);
                    }
                    else if (tvProjectFeeds.SelectedNode.Name == "Templates")
                    {
                        lblGalleryProjects.Text = "Gallery Templates";
                        var sourceResults = await NugetPackageManager.SearchPackages("", _galleryTemplatesSourceUrl, false);

                        PopulateListBox(sourceResults);
                    }
                }
            }
            catch (Exception)
            {
                tpbLoadingSpinner.Visible = false;
            }
        }
Exemplo n.º 16
0
        private void SetAgentEnvironment()
        {
            MessageDialog messageDialog = new MessageDialog(
                "Environment Setup",
                "Please wait while the environment is being set up for the Agent.",
                false);

            try
            {
                messageDialog.Topmost = true;
                messageDialog.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                messageDialog.Show();

                // Set Environment Variable Path
                SetEnvironmentVariable();

                // Create Settings File
                CreateSettingsFile();

                // Install Default Packages for the First Time
                NugetPackageManager.SetupFirstTimeUserEnvironment(Environment.UserDomainName, Environment.UserName, SystemForms.Application.ProductVersion);

                messageDialog.CloseManually = true;
                messageDialog.Close();
            }
            catch (Exception ex)
            {
                messageDialog.CloseManually = true;
                messageDialog.Close();

                ShowErrorDialog("An error occurred while setting up environment for the Agent.",
                                "",
                                ex.Message,
                                Application.Current.MainWindow);

                ShutDownApplication();
            }
        }
Exemplo n.º 17
0
        private async void frmScriptBuilder_LoadAsync(object sender, EventArgs e)
        {
            //set controls double buffered
            foreach (Control control in Controls)
            {
                typeof(Control).InvokeMember("DoubleBuffered",
                                             BindingFlags.SetProperty | BindingFlags.Instance | BindingFlags.NonPublic,
                                             null, control, new object[] { true });
            }

            //get app settings
            _appSettings    = new ApplicationSettings().GetOrCreateApplicationSettings();
            _slimBarHeight  = tlpControls.RowStyles[0].Height;
            _thickBarHeight = tlpControls.RowStyles[1].Height;

            LoadActionBarPreference();

            //get scripts folder
            var rpaScriptsFolder = Folders.GetFolder(FolderType.ScriptsFolder, false);

            if (!Directory.Exists(rpaScriptsFolder))
            {
                var             rootFolder = Folders.GetFolder(FolderType.RootFolder);
                frmFolderDialog userDialog = new frmFolderDialog("Would you like to create a folder to save your scripts in now? " +
                                                                 "A script folder is required to save scripts generated by this application. " +
                                                                 $"The new script folder path would be '{Path.Combine(rootFolder, "OB Scripts")}'.",
                                                                 "Unable to locate OB Scripts Folder!", rootFolder);

                userDialog.ShowDialog();
                userDialog.Dispose();
            }

            //get latest files for recent files list on load
            GenerateRecentProjects();

            //set listview column size
            frmScriptBuilder_SizeChanged(null, null);
            Refresh();

            if (Debugger.IsAttached)
            {
                //set this value to 'true' to display the 'Install Default' button, and 'false' to hide it
                installDefaultToolStripMenuItem.Visible = true;
            }
            else //if OpenBots Studio is running in release mode
            {
                _isFirstTimeSetupComplete = false;
                try
                {
                    //scan whether the current user account has unpacked default commands in their local appdata
                    await NugetPackageManager.SetupFirstTimeUserEnvironment();
                }
                catch (Exception ex)
                {
                    //packages missing from Program Files
                    MessageBox.Show($"{ex.Message}\n\nFirst time user environment setup failed.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                _isFirstTimeSetupComplete = true;
            }

            var defaultTypesBinding = new BindingSource(_typeContext.DefaultTypes, null);

            variableType.DataSource    = defaultTypesBinding;
            variableType.DisplayMember = "Key";
            variableType.ValueMember   = "Value";

            argumentType.DataSource    = defaultTypesBinding;
            argumentType.DisplayMember = "Key";
            argumentType.ValueMember   = "Value";

            var importedNameSpacesBinding = new BindingSource(_scriptContext.ImportedNamespaces, null);

            lbxImportedNamespaces.DataSource    = importedNameSpacesBinding;
            lbxImportedNamespaces.DisplayMember = "Key";

            var allNameSpacesBinding = new BindingSource(_allNamespaces, null);

            cbxAllNamespaces.DataSource    = allNameSpacesBinding;
            cbxAllNamespaces.DisplayMember = "Key";

            if (_studioFormShownEarly)
            {
                _studioFormShownEarly = false;
                Show();
                frmScriptBuilder_Shown(null, null);
            }
        }
        private void OpenProject(string projectPath)
        {
            tvProject.Nodes.Clear();

            DialogResult result = CheckForUnsavedScripts();

            if (result == DialogResult.Cancel)
            {
                return;
            }

            try
            {
                string configPath = Path.Combine(projectPath, "project.obconfig");

                //open project
                Project project      = Project.OpenProject(configPath);
                string  mainFileName = project.Main;

                string mainFilePath = Directory.GetFiles(projectPath, mainFileName, SearchOption.AllDirectories).FirstOrDefault();
                if (mainFilePath == null)
                {
                    throw new Exception("Main script not found");
                }

                var assemblyList = NugetPackageManager.LoadPackageAssemblies(configPath);
                _builder   = AppDomainSetupManager.LoadBuilder(assemblyList, _typeContext.GroupedTypes);
                AContainer = _builder.Build();

                _mainFileName     = mainFileName;
                ScriptProject     = project;
                ScriptProjectPath = projectPath;
                uiScriptTabControl.TabPages.Clear();

                //open Main
                OpenOpenBotsFile(mainFilePath);

                //show success dialog
                Notify("Project has been opened successfully!", Color.White);
            }
            catch (Exception ex)
            {
                //show fail dialog
                Notify("An Error Occured: " + ex.Message, Color.Red);
            }


            DirectoryInfo projectDirectoryInfo = new DirectoryInfo(ScriptProjectPath);
            TreeNode      projectNode          = new TreeNode(projectDirectoryInfo.Name);

            projectNode.Text = projectDirectoryInfo.Name;
            projectNode.Tag  = projectDirectoryInfo.FullName;
            projectNode.Nodes.Add("Empty");
            projectNode.ContextMenuStrip = cmsProjectMainFolderActions;
            tvProject.Nodes.Add(projectNode);
            projectNode.Expand();
            LoadCommands(this);

            //save to recent projects
            if (_appSettings.ClientSettings.RecentProjects == null)
            {
                _appSettings.ClientSettings.RecentProjects = new List <string>();
            }

            if (_appSettings.ClientSettings.RecentProjects.Contains(ScriptProjectPath))
            {
                _appSettings.ClientSettings.RecentProjects.Remove(ScriptProjectPath);
            }

            _appSettings.ClientSettings.RecentProjects.Insert(0, ScriptProjectPath);

            if (_appSettings.ClientSettings.RecentProjects.Count > 10)
            {
                _appSettings.ClientSettings.RecentProjects.RemoveAt(10);
            }

            _appSettings.Save(_appSettings);
        }
        public DialogResult AddProject()
        {
            tvProject.Nodes.Clear();
            var projectBuilder = new frmProjectBuilder();

            projectBuilder.ShowDialog();

            //close OpenBots if add project form is closed at startup
            if (projectBuilder.DialogResult == DialogResult.Cancel && ScriptProject == null)
            {
                Application.Exit();
                return(DialogResult.Abort);
            }

            //create new project
            else if (projectBuilder.Action == frmProjectBuilder.ProjectAction.CreateProject)
            {
                DialogResult result = CheckForUnsavedScripts();
                if (result == DialogResult.Cancel)
                {
                    return(DialogResult.Cancel);
                }

                uiScriptTabControl.TabPages.Clear();
                ScriptProjectPath = projectBuilder.NewProjectPath;

                //create new project
                ScriptProject = new Project(projectBuilder.NewProjectName, projectBuilder.NewProjectType);
                string configPath = Path.Combine(ScriptProjectPath, "project.obconfig");

                //create config file
                File.WriteAllText(configPath, JsonConvert.SerializeObject(ScriptProject));

                NotifySync("Loading package assemblies...", Color.White);

                var assemblyList = NugetPackageManager.LoadPackageAssemblies(configPath);
                _builder   = AppDomainSetupManager.LoadBuilder(assemblyList, _typeContext.GroupedTypes);
                AContainer = _builder.Build();

                string mainScriptPath = Path.Combine(ScriptProjectPath, ScriptProjectPath, ScriptProject.Main);
                string mainScriptName = Path.GetFileNameWithoutExtension(mainScriptPath);

                switch (ScriptProject.ProjectType)
                {
                case ProjectType.OpenBots:
                    CreateOpenBotsProject(mainScriptName, mainScriptPath);
                    break;

                case ProjectType.Python:
                case ProjectType.TagUI:
                case ProjectType.CSScript:
                    CreateTextEditorProject(mainScriptName, mainScriptPath);
                    break;
                }

                //show success dialog
                Notify("Project has been created successfully!", Color.White);
            }

            //open existing OpenBots project
            else if (projectBuilder.Action == frmProjectBuilder.ProjectAction.OpenProject)
            {
                DialogResult result = CheckForUnsavedScripts();
                if (result == DialogResult.Cancel)
                {
                    return(DialogResult.Cancel);
                }

                try
                {
                    //open project
                    string  existingConfigPath = projectBuilder.ExistingConfigPath;
                    Project project            = Project.OpenProject(existingConfigPath);

                    if (existingConfigPath.EndsWith(".config"))
                    {
                        existingConfigPath = existingConfigPath.Replace(".config", ".obconfig");
                    }

                    string mainFileName = project.Main;

                    string mainFilePath = Directory.GetFiles(projectBuilder.ExistingProjectPath, mainFileName, SearchOption.AllDirectories).FirstOrDefault();
                    if (mainFilePath == null)
                    {
                        throw new Exception("Main script not found");
                    }

                    NotifySync("Loading package assemblies...", Color.White);

                    var assemblyList = NugetPackageManager.LoadPackageAssemblies(existingConfigPath);
                    _builder   = AppDomainSetupManager.LoadBuilder(assemblyList, _typeContext.GroupedTypes);
                    AContainer = _builder.Build();

                    ScriptProject     = project;
                    _mainFileName     = mainFileName;
                    ScriptProjectPath = projectBuilder.ExistingProjectPath;
                    uiScriptTabControl.TabPages.Clear();

                    //open Main
                    switch (ScriptProject.ProjectType)
                    {
                    case ProjectType.OpenBots:
                        OpenOpenBotsFile(mainFilePath);
                        break;

                    case ProjectType.Python:
                    case ProjectType.TagUI:
                    case ProjectType.CSScript:
                        OpenTextEditorFile(mainFilePath, ScriptProject.ProjectType);
                        break;
                    }

                    //show success dialog
                    Notify("Project has been opened successfully!", Color.White);
                }
                catch (Exception ex)
                {
                    projectBuilder.Dispose();

                    //show fail dialog
                    Notify("An Error Occured: " + ex.Message, Color.Red);

                    //try adding project again
                    AddProject();
                    return(DialogResult.None);
                }
            }

            projectBuilder.Dispose();

            DirectoryInfo projectDirectoryInfo = new DirectoryInfo(ScriptProjectPath);
            TreeNode      projectNode          = new TreeNode(projectDirectoryInfo.Name);

            projectNode.Text = projectDirectoryInfo.Name;
            projectNode.Tag  = projectDirectoryInfo.FullName;
            projectNode.Nodes.Add("Empty");
            projectNode.ContextMenuStrip = cmsProjectMainFolderActions;
            tvProject.Nodes.Add(projectNode);
            projectNode.Expand();
            LoadCommands(this);

            //save to recent projects
            if (_appSettings.ClientSettings.RecentProjects == null)
            {
                _appSettings.ClientSettings.RecentProjects = new List <string>();
            }

            if (_appSettings.ClientSettings.RecentProjects.Contains(ScriptProjectPath))
            {
                _appSettings.ClientSettings.RecentProjects.Remove(ScriptProjectPath);
            }

            _appSettings.ClientSettings.RecentProjects.Insert(0, ScriptProjectPath);

            if (_appSettings.ClientSettings.RecentProjects.Count > 10)
            {
                _appSettings.ClientSettings.RecentProjects.RemoveAt(10);
            }

            _appSettings.Save(_appSettings);

            return(DialogResult.OK);
        }
Exemplo n.º 20
0
        private async void tvPackageFeeds_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            lblError.Text = "";
            try
            {
                if (tvPackageFeeds.SelectedNode != null)
                {
                    lbxNugetPackages.Clear();
                    lbxNugetPackages.Visible  = false;
                    tpbLoadingSpinner.Visible = true;

                    if (tvPackageFeeds.SelectedNode.Name == "Settings")
                    {
                        var addPackageSource = new frmAddPackageSource(_packageSourceDT);
                        addPackageSource.ShowDialog();
                        if (addPackageSource.DialogResult == DialogResult.OK)
                        {
                            _packageSourceDT = addPackageSource.PackageSourceDT;
                            PopulatetvPackageFeeds();
                            _settings.Save();
                        }

                        addPackageSource.Dispose();
                        tpbLoadingSpinner.Visible = false;
                    }
                    else if (tvPackageFeeds.SelectedNode.Name == "ProjectDependencies")
                    {
                        lblPackageCategory.Text  = "Project Dependencies";
                        pbxPackageCategory.Image = Resources.OpenBots_icon;
                        await GetCurrentDepencies();

                        PopulateListBox(_projectDependencies);
                    }
                    else if (tvPackageFeeds.SelectedNode.Name == "AllPackages")
                    {
                        lblPackageCategory.Text  = "All Packages";
                        pbxPackageCategory.Image = Resources.OpenBots_icon;
                        PopulateListBox(_allResults);
                    }
                    else if (tvPackageFeeds.SelectedNode.Name == "Gallery")
                    {
                        lblPackageCategory.Text  = "Gallery";
                        pbxPackageCategory.Image = Resources.OpenBots_gallery_icon;
                        var sourceResults = await NugetPackageManager.SearchPackages("", tvPackageFeeds.SelectedNode.ToolTipText, _includePrerelease);

                        PopulateListBox(sourceResults);
                    }
                    else
                    {
                        lblPackageCategory.Text  = tvPackageFeeds.SelectedNode.Text;
                        pbxPackageCategory.Image = Resources.nuget_icon;
                        var sourceResults = await NugetPackageManager.SearchPackages("", tvPackageFeeds.SelectedNode.ToolTipText, _includePrerelease);

                        PopulateListBox(sourceResults);
                    }
                }
            }
            catch (Exception)
            {
                lblPackageCategory.Text   = "Source Not Found";
                tpbLoadingSpinner.Visible = false;
            }
        }
Exemplo n.º 21
0
        private async void lbxNugetPackages_ItemClick(object sender, int index)
        {
            lblError.Text = "";
            try
            {
                string projectId = lbxNugetPackages.ClickedItem.Id;
                List <IPackageSearchMetadata> metadata = new List <IPackageSearchMetadata>();

                if (lblPackageCategory.Text == "Project Dependencies")
                {
                    metadata.AddRange(await NugetPackageManager.GetPackageMetadata(projectId, _packagesPath, _includePrerelease));
                }
                else if (lblPackageCategory.Text == "All Packages")
                {
                    foreach (DataRow row in _packageSourceDT.Rows)
                    {
                        if (row[0].ToString() == "True")
                        {
                            metadata.AddRange(await NugetPackageManager.GetPackageMetadata(projectId, row[2].ToString(), _includePrerelease));
                        }
                    }
                }
                else
                {
                    var sourceURL = _packageSourceDT.AsEnumerable().Where(r => r.Field <string>("Enabled") == "True" && r.Field <string>("Package Name") == lblPackageCategory.Text)
                                    .Select(r => r.Field <string>("Package Source")).FirstOrDefault();
                    metadata.AddRange(await NugetPackageManager.GetPackageMetadata(projectId, sourceURL, _includePrerelease));
                }

                string latestVersion = metadata.LastOrDefault().Identity.Version.ToString();

                _projectVersions.Clear();

                if (lblPackageCategory.Text == "Project Dependencies")
                {
                    _projectVersions.AddRange(await NugetPackageManager.GetPackageVersions(projectId, _packagesPath, _includePrerelease));
                }
                else if (lblPackageCategory.Text == "All Packages")
                {
                    foreach (DataRow row in _packageSourceDT.Rows)
                    {
                        if (row[0].ToString() == "True")
                        {
                            _projectVersions.AddRange(await NugetPackageManager.GetPackageVersions(projectId, row[2].ToString(), _includePrerelease));
                        }
                    }
                }
                else
                {
                    var sourceURL = _packageSourceDT.AsEnumerable().Where(r => r.Field <string>("Enabled") == "True" && r.Field <string>("Package Name") == lblPackageCategory.Text)
                                    .Select(r => r.Field <string>("Package Source")).FirstOrDefault();
                    _projectVersions.AddRange(await NugetPackageManager.GetPackageVersions(projectId, sourceURL, _includePrerelease));
                }

                List <string> versionList = _projectVersions.Select(x => x.ToString()).ToList();
                versionList.Reverse();

                cbxVersion.Items.Clear();
                foreach (var version in versionList)
                {
                    cbxVersion.Items.Add(version);
                }

                _selectedPackageMetaData = metadata;

                var installedPackage = _projectDependencies.Where(x => x.Identity.Id == projectId).FirstOrDefault();

                if (installedPackage != null)
                {
                    _isInstalled      = true;
                    _installedVersion = installedPackage.Identity.Version.ToString();
                    PopulateProjectDetails(_installedVersion);
                    cbxVersion.SelectedItem = _installedVersion;
                }
                else
                {
                    _isInstalled      = false;
                    _installedVersion = "";
                    PopulateProjectDetails(latestVersion);
                    cbxVersion.SelectedIndex = 0;
                }

                pnlProjectVersion.Show();
                pnlProjectDetails.Show();
            }
            catch (Exception)
            {
                pnlProjectVersion.Hide();
                pnlProjectDetails.Hide();
            }
        }
Exemplo n.º 22
0
        private void frmProcessingStatus_Load(object sender, EventArgs e)
        {
            //get engine settings
            EngineContext.EngineSettings = new ApplicationSettings().GetOrCreateApplicationSettings().EngineSettings;

            //add hooks for hot key cancellation
            GlobalHook.HookStopped += new EventHandler(OnHookStopped);
            GlobalHook.StartEngineCancellationHook(EngineContext.EngineSettings.CancellationKey);
            GlobalHook.KeyDownEvent += GlobalHook_KeyDownEvent;

            if (_isParentScheduledTask)
            {
                List <string> assemblyList = NugetPackageManager.LoadPackageAssemblies(_configPath, true);
                Dictionary <string, List <Type> > groupedTypes = new Dictionary <string, List <Type> >();
                Dictionary <string, List <AssemblyReference> > allNamespaces = new Dictionary <string, List <AssemblyReference> >();
                var builder = AppDomainSetupManager.LoadBuilder(assemblyList, groupedTypes, allNamespaces, ScriptDefaultNamespaces.DefaultNamespaces);// EngineContext.ImportedNamespaces);
                EngineContext.Container = builder.Build();
            }

            //move engine form to bottom right and bring to front
            if (EngineContext.EngineSettings.ShowDebugWindow || EngineContext.IsDebugMode)
            {
                BringToFront();
                MoveFormToBottomRight(this);
            }
            else
            {
                MoveFormToBottomRight(this);
            }

            if (!EngineContext.IsDebugMode && !EngineContext.EngineSettings.ShowDebugWindow)
            {
                FormsHelper.HideForm(this);
            }

            //if listbox should be shown
            if (EngineContext.EngineSettings.ShowAdvancedDebugOutput || EngineContext.IsDebugMode)
            {
                lstSteppingCommands.Show();
                lblMainLogo.Show();
                pbBotIcon.Hide();
                lblAction.Hide();
            }
            else
            {
                lstSteppingCommands.Hide();
                lblMainLogo.Hide();
                pbBotIcon.Show();
                lblAction.Show();
            }

            //start running
            EngineInstance = new AutomationEngineInstance(EngineContext);

            if (IsNewTaskSteppedInto)
            {
                EngineInstance.PauseScript();
                uiBtnPause.Image       = Resources.engine_resume;
                uiBtnPause.DisplayText = "Resume";
                uiBtnStepOver.Visible  = true;
                uiBtnStepInto.Visible  = true;

                EngineContext.ScriptBuilder.CurrentEngine = this;

                //toggle running flag to allow for tab selection
                EngineContext.ScriptBuilder.IsScriptRunning = false;
                ((frmScriptBuilder)EngineContext.ScriptBuilder).OpenOpenBotsFile(EngineContext.FilePath, true);
                EngineContext.ScriptBuilder.IsScriptRunning = true;
            }

            EngineInstance.ReportProgressEvent       += Engine_ReportProgress;
            EngineInstance.ScriptFinishedEvent       += Engine_ScriptFinishedEvent;
            EngineInstance.LineNumberChangedEvent    += EngineInstance_LineNumberChangedEvent;
            EngineInstance.EngineContext.ScriptEngine = this;

            EngineInstance.ExecuteScriptAsync();
        }
Exemplo n.º 23
0
        private async void frmScriptBuilder_LoadAsync(object sender, EventArgs e)
        {
            if (Debugger.IsAttached)
            {
                //set this value to 'true' to display the 'Install Default' button, and 'false' to hide it
                installDefaultToolStripMenuItem.Visible = true;
            }
            else //if OpenBots Studio is running in release mode
            {
                try
                {
                    //scan whether the current user account has unpacked default commands in their local appdata
                    await NugetPackageManager.SetupFirstTimeUserEnvironment();
                }
                catch (Exception ex)
                {
                    //packages missing from Program Files
                    MessageBox.Show($"{ex.Message}\n\nFirst time user environment setup failed.", "Error");
                }
            }

            var defaultTypesBinding = new BindingSource(_typeContext.DefaultTypes, null);

            VariableType.DataSource    = defaultTypesBinding;
            VariableType.DisplayMember = "Key";
            VariableType.ValueMember   = "Value";

            ArgumentType.DataSource    = defaultTypesBinding;
            ArgumentType.DisplayMember = "Key";
            ArgumentType.ValueMember   = "Value";

            //set controls double buffered
            foreach (Control control in Controls)
            {
                typeof(Control).InvokeMember("DoubleBuffered",
                                             BindingFlags.SetProperty | BindingFlags.Instance | BindingFlags.NonPublic,
                                             null, control, new object[] { true });
            }

            //get app settings
            _appSettings = new ApplicationSettings();
            _appSettings = _appSettings.GetOrCreateApplicationSettings();

            _slimBarHeight  = tlpControls.RowStyles[0].Height;
            _thickBarHeight = tlpControls.RowStyles[1].Height;

            LoadActionBarPreference();

            //get scripts folder
            var rpaScriptsFolder = Folders.GetFolder(FolderType.ScriptsFolder);

            if (!Directory.Exists(rpaScriptsFolder))
            {
                frmDialog userDialog = new frmDialog("Would you like to create a folder to save your scripts in now? " +
                                                     "A script folder is required to save scripts generated with this application. " +
                                                     "The new script folder path would be '" + rpaScriptsFolder + "'.", "Unable to locate Script Folder!",
                                                     DialogType.YesNo, 0);

                if (userDialog.ShowDialog() == DialogResult.OK)
                {
                    Directory.CreateDirectory(rpaScriptsFolder);
                }

                userDialog.Dispose();
            }

            //get latest files for recent files list on load
            GenerateRecentProjects();

            //no height for status bar
            HideNotificationRow();

            //set listview column size
            frmScriptBuilder_SizeChanged(null, null);
            Refresh();
        }
Exemplo n.º 24
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";
        }