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 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 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(); }
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(); } }
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); }
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(); }
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"; }
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); }
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); }