public JobHistoryViewModel(RunbookViewModel runbookViewModel) { _runbook = (RunbookModelProxy)runbookViewModel.Model; Owner = _runbook.Context.Service; Jobs = new ObservableCollection<JobModelProxy>(); //AsyncExecution.Run(ThreadPriority.Normal, () => Task.Run(() => { IList<JobModelProxy> draftJobs = null; IList<JobModelProxy> publishedJobs = null; try { if (_runbook.DraftRunbookVersionID.HasValue) draftJobs = Owner.GetJobs(_runbook.DraftRunbookVersionID.Value); if (_runbook.PublishedRunbookVersionID.HasValue) publishedJobs = Owner.GetJobs(_runbook.PublishedRunbookVersionID.Value); } catch (ApplicationException ex) { GlobalExceptionHandler.Show(ex); } Execute.OnUIThread(() => { if (draftJobs != null) { foreach (var job in draftJobs) { job.BoundRunbookViewModel = runbookViewModel; job.RunbookType = RunbookType.Draft; Jobs.Add(job); } } if (publishedJobs != null) { foreach (var job in publishedJobs) { job.BoundRunbookViewModel = runbookViewModel; job.RunbookType = RunbookType.Published; Jobs.Add(job); } } Jobs = Jobs.OrderBy(j => j.StartTime).ToObservableCollection(); }); }); }
public Guid? StartRunbook(RunbookModelProxy runbookProxy, List<NameValuePair> parameters) { Logger.DebugFormat("StartRunbook(runbook = {0}, ...)", runbookProxy.RunbookName); if (!(runbookProxy.Model is SMA.Runbook)) return null; var context = GetConnection(); var runbook = (SMA.Runbook)runbookProxy.Model; try { runbookProxy.IsTestRun = false; return runbook.StartRunbook(context, parameters); } catch (DataServiceQueryException ex) { /*var xml = default(string); if (ex.InnerException != null) xml = ex.InnerException.Message; else xml = ex.Message; Logger.Error("Error when trying to start the runbook.", ex); XmlExceptionHandler.Show(xml);*/ throw new ApplicationException("Error when starting the runbook. Please refer to the output for more information.", ex); } }
static SnippetElement CreateElementForValue(RunbookModelProxy runbook, Dictionary<string, SnippetReplaceableTextElement> replaceableElements, string val, int offset, string snippetText) { SnippetReplaceableTextElement srte; int equalsSign = val.IndexOf('='); if (equalsSign > 0) { string name = val.Substring(0, equalsSign); if (replaceableElements.TryGetValue(name, out srte)) { if (srte.Text == null) srte.Text = val.Substring(equalsSign + 1); return srte; } } if (replaceableElements.TryGetValue(val, out srte)) return new SnippetBoundElement { TargetElement = srte }; string result = GetValue(runbook, val); if (result != null) return new SnippetTextElement { Text = result }; else return new SnippetReplaceableTextElement { Text = val }; // ${unknown} -> replaceable element }
public Snippet CreateAvalonEditSnippet(RunbookModelProxy runbook) { return CreateAvalonEditSnippet(runbook, this.Text); }
public async Task<OperationStatus> SaveRunbookContentAsync(RunbookModelProxy runbook, string runbookContent, RunbookType runbookType) { var longRunningOp = default(LongRunningOperationResultResponse); var runbookUpdate = new RunbookDraftUpdateParameters(); runbookUpdate.Stream = runbookContent; runbookUpdate.Name = runbook.RunbookName; longRunningOp = await _client.RunbookDraft.UpdateAsync(_connectionData.AzureRMGroupName, _connectionData.AzureAutomationAccount, runbookUpdate); if (runbookType == RunbookType.Published) { await CheckIn(runbook); } if (longRunningOp.Status == Microsoft.Azure.OperationStatus.Failed) return OperationStatus.Failed; else if (longRunningOp.Status == Microsoft.Azure.OperationStatus.InProgress) return OperationStatus.InProgress; else if (longRunningOp.Status == Microsoft.Azure.OperationStatus.Succeeded) return OperationStatus.Succeeded; return OperationStatus.Failed; }
public async Task<bool> CheckIn(RunbookModelProxy runbook) { RunbookDraftPublishParameters publishParams = new RunbookDraftPublishParameters { Name = runbook.RunbookName, PublishedBy = "Automation Studio, by: " + System.Security.Principal.WindowsIdentity.GetCurrent().Name }; CancellationTokenSource cts = new CancellationTokenSource(); cts.CancelAfter(TIMEOUT_MS); LongRunningOperationResultResponse resultResponse = await _client.RunbookDraft.PublishAsync(_connectionData.AzureRMGroupName, _connectionData.AzureAutomationAccount, publishParams, cts.Token); // Move the draft to published runbook.PublishedRunbookVersionID = runbook.DraftRunbookVersionID; runbook.DraftRunbookVersionID = null; return true; }
private JobModelProxy GetDraftJobDetails(RunbookModelProxy runbook) { var job = _client.TestJobs.Get(_connectionData.AzureRMGroupName, _connectionData.AzureAutomationAccount, runbook.RunbookName); if (job.StatusCode != System.Net.HttpStatusCode.OK) return null; var jobModel = new JobModelProxy(new Vendor.Azure.Job { JobID = Guid.NewGuid(), Id = string.Empty, WarningCount = 0, ErrorCount = 0, JobException = job.TestJob.Exception, CreationTime = job.TestJob.CreationTime.DateTime, EndTime = (job.TestJob.EndTime != null ? job.TestJob.EndTime.DateTime : default(DateTime?)), JobStatus = job.TestJob.Status, JobStatusDeteails = job.TestJob.StatusDetails, LastModifiedTime = job.TestJob.LastModifiedTime.DateTime, StartTime = (job.TestJob.StartTime != null ? job.TestJob.StartTime.DateTime : default(DateTime?)) }, Context); var jobStreamParameters = new JobStreamListParameters(); jobStreamParameters.StreamType = "Any"; var streams = default(JobStreamListResponse); do { if (streams != null) streams = _client.JobStreams.ListNext(streams.NextLink); else streams = _client.JobStreams.ListTestJobStreams(_connectionData.AzureRMGroupName, _connectionData.AzureAutomationAccount, runbook.RunbookName, jobStreamParameters); if (streams.StatusCode != System.Net.HttpStatusCode.OK) return jobModel; var output = streams.JobStreams.Select(s => new JobOutput { JobID = jobModel.JobID, RunbookVersionID = runbook.DraftRunbookVersionID.Value, StreamText = s.Properties.Summary, StreamTime = s.Properties.Time.DateTime, StreamTypeName = s.Properties.StreamType }).ToList(); foreach (var o in output) jobModel.Result.Add(o); } while (streams.NextLink != null); return jobModel; }
public string GetBackendUrl(RunbookType runbookType, RunbookModelProxy runbook) { // Azure RM, apart from Classic, only requires the runbook name when fetching the content. // That's why we only return runbook name here. return runbookType + "|" + runbook.RunbookName; }
public async Task<OperationResult> SaveRunbookAsync(RunbookModelProxy runbook, string runbookContent) { if (runbook.RunbookID == Guid.Empty) { // New runbook that doesn't exist in Azure Automation yet var json = new Dictionary<string, object>(); var properties = new Dictionary<string, object>(); properties.Add("runbookType", "Script"); properties.Add("logProgress", false); properties.Add("logVerbose", false); var draft = new Dictionary<string, object>(); draft.Add("inEdit", true); draft.Add("creationTime", DateTime.Now); draft.Add("lastModifiedTime", DateTime.Now); properties.Add("draft", draft); json.Add("properties", properties); var cryptoProvider = new SHA256CryptoServiceProvider(); var encoding = System.Text.Encoding.UTF8; var rbBytes = encoding.GetBytes(runbookContent); var resultHash = cryptoProvider.ComputeHash(rbBytes); var resultHashB64 = Convert.ToBase64String(resultHash); var runbookData = await SendRequestAsync("runbooks/" + runbook.RunbookName.ToUrlSafeString(), HttpMethod.Put, JsonConvert.SerializeObject(json), "application/json").ConfigureAwait(false); if (runbookData.Length > 0) { runbook.RunbookID = Guid.NewGuid(); } } // Update the runbook await SaveRunbookContentAsync(runbook, runbookContent, RunbookType.Draft); return new OperationResult { Status = OperationStatus.Succeeded, HttpStatusCode = HttpStatusCode.OK }; }
public async Task<bool> CheckIn(RunbookModelProxy runbook) { var invocationId = string.Empty; if (TracingAdapter.IsEnabled) { invocationId = TracingAdapter.NextInvocationId.ToString(); TracingAdapter.Enter(invocationId, this, "CheckIn", new Dictionary<string, object>() { { "runbook", runbook } }); } // Publish the draft runbook await SendRequestAsync("runbooks/" + runbook.RunbookName.ToUrlSafeString() + "/draft/publish", HttpMethod.Post, "").ConfigureAwait(false); // Move the draft to published runbook.PublishedRunbookVersionID = runbook.DraftRunbookVersionID; runbook.DraftRunbookVersionID = null; if (TracingAdapter.IsEnabled) { TracingAdapter.Exit(invocationId, null); } return true; }
/// <summary> /// Check in a drafted runbook and make it the published one. /// </summary> /// <param name="runbook"></param> /// <returns></returns> public async Task<bool> CheckIn(RunbookModelProxy runbook) { Logger.DebugFormat("CheckIn(runbook = {0})", runbook.RunbookName); return await Task.Run(delegate () { var context = GetConnection(); try { context.AttachTo("Runbooks", runbook.Model); } catch (InvalidOperationException) { /* already attached */ } if (!runbook.DraftRunbookVersionID.HasValue || runbook.DraftRunbookVersionID == Guid.Empty) { //MessageBox.Show("The runbook's already checked in.", "Information", MessageBoxButton.OK, MessageBoxImage.Information); return true; } var publishedGuid = Guid.Empty; try { //runbook.PublishedRunbookVersionID = ((Runbook)runbook.Model).Publish(context); publishedGuid = ((Runbook)runbook.Model).Publish(context); } catch (DataServiceQueryException ex) { /*var xml = default(string); if (ex.InnerException != null) xml = ex.InnerException.Message; else xml = ex.Message; Logger.Error("Error when publishing the runbook.", ex); XmlExceptionHandler.Show(xml); return false;*/ throw new ApplicationException("Error when publishing the runbook. Please refer to the output for more information.", ex); } runbook.PublishedRunbookVersionID = publishedGuid; return true; }); }
/// <summary> /// Retrieve information about a specific job from SMA /// </summary> /// <param name="jobId">ID to retrieve information about</param> /// <returns>Proxy object or null</returns> public JobModelProxy GetJobDetails(RunbookModelProxy runbook) { Logger.DebugFormat("GetJobDetails(runbook = {0})", runbook.RunbookName); return GetJobDetails(runbook.JobID); }
public async Task<OperationStatus> SaveRunbookContentAsync(RunbookModelProxy runbook, string runbookContent, RunbookType runbookType) { var context = GetConnection(); var ms = new MemoryStream(); var bytes = Encoding.UTF8.GetBytes(runbookContent); ms.Write(bytes, 0, bytes.Length); ms.Seek(0, SeekOrigin.Begin); var baseStream = (Stream)ms; var entity = (from rv in context.RunbookVersions where (Guid?)rv.RunbookVersionID == (runbook.Model as SMA.Runbook).DraftRunbookVersionID select rv).FirstOrDefault<RunbookVersion>(); try { context.AttachTo("Runbooks", runbook.Model as SMA.Runbook); } catch (InvalidOperationException) { } context.SetSaveStream(entity, baseStream, true, "application/octet-stream", string.Empty); context.SaveChanges(); if (runbookType == RunbookType.Published) { await CheckIn(runbook); } return OperationStatus.Succeeded; }
public Task<OperationResult> SaveRunbookAsync(RunbookModelProxy runbook, string runbookContent) { var context = GetConnection(); Logger.DebugFormat("SaveSmaRunbook(...)"); var rawRunbook = runbook.Model as SMA.Runbook; if (rawRunbook == null || rawRunbook.RunbookID == Guid.Empty) { Logger.DebugFormat("Runbook does not exist yet, generate a new ID and set it as draft."); // This is a new runbook var runbookVersion = new RunbookVersion { TenantID = new Guid("00000000-0000-0000-0000-000000000000"), IsDraft = true }; context.AddToRunbookVersions(runbookVersion); var ms = new MemoryStream(); var bytes = Encoding.UTF8.GetBytes(runbookContent); ms.Write(bytes, 0, bytes.Length); ms.Seek(0, SeekOrigin.Begin); var baseStream = (Stream)ms; context.SetSaveStream(runbookVersion, baseStream, true, "application/octet-stream", string.Empty); EntityDescriptor ed = null; try { ChangeOperationResponse cor = (ChangeOperationResponse)context.SaveChanges().FirstOrDefault<OperationResponse>(); if (cor != null) { ed = (cor.Descriptor as EntityDescriptor); } } catch (Exception e) { Logger.Error("Unable to verify the saved runbook.", e); //throw new PersistenceException("Sorry, we were unable to save your runbook. Please refer to the log for more information."); throw new ApplicationException("Error when saving the runbook. Please refer to the output for more information.", e); } if (ed != null && ed.EditLink != null) { MergeOption mergeOption = context.MergeOption; context.MergeOption = MergeOption.OverwriteChanges; try { context.Execute<RunbookVersion>(ed.EditLink).Count<RunbookVersion>(); } catch (Exception e) { Logger.Error("Unable to save the runbook.", e); throw new ApplicationException("Error when saving the runbook. Please refer to the output for more information.", e); //throw new PersistenceException("There was an error when saving the runbook. Please try again later."); } finally { context.MergeOption = mergeOption; } } var savedRunbook = context.Runbooks.Where(x => x.RunbookID == runbookVersion.RunbookID).FirstOrDefault(); if (savedRunbook == null) { //throw new PersistenceException("Unable to retrieve the saved runbook, something went wrong when trying to save the object. Please try again."); throw new ApplicationException("Error when saving the object."); } //instance.Model = new RunbookModelProxy(savedRunbook, _backendContext); //runbook = savedRunbook; rawRunbook = savedRunbook; runbook.Model = rawRunbook; } try { context.AttachTo("Runbooks", rawRunbook); } catch (InvalidOperationException) { /* already attached */ } try { if (rawRunbook.DraftRunbookVersionID.HasValue) { AsyncHelper.RunSync(() => SaveRunbookContentAsync(runbook, runbookContent, RunbookType.Draft)); } var smaRunbook = context.Runbooks.Where(r => r.RunbookID.Equals(runbook.RunbookID)).FirstOrDefault(); smaRunbook.Tags = runbook.Tags; smaRunbook.Description = rawRunbook.Description; if (rawRunbook.DraftRunbookVersionID.HasValue) smaRunbook.DraftRunbookVersionID = rawRunbook.DraftRunbookVersionID; if (rawRunbook.PublishedRunbookVersionID.HasValue) smaRunbook.PublishedRunbookVersionID = rawRunbook.PublishedRunbookVersionID; context.UpdateObject(smaRunbook); context.SaveChanges(); //instance.UnsavedChanges = false; } catch (Exception e) { Logger.Error("Error when saving the runbook.", e); //throw new PersistenceException("Unable to save the changes, error: " + e.Message); throw new ApplicationException("Error when saving the runbook. Please refer to the output for more information.", e); } return new Task<OperationResult>(() => { return new OperationResult { HttpStatusCode = HttpStatusCode.OK, Status = OperationStatus.Succeeded, RequestUrl = string.Empty }; }); }
public string GetBackendUrl(RunbookType runbookType, RunbookModelProxy runbook) { Logger.DebugFormat("GetBackendUrl(runbookType = {0}, runbook = {1})", runbookType, runbook.RunbookName); switch (runbookType) { case RunbookType.Draft: return _connectionData.SmaConnectionUrl + "/Runbooks(guid'" + runbook.RunbookID + "')/DraftRunbookVersion/$value"; case RunbookType.Published: return _connectionData.SmaConnectionUrl + "/Runbooks(guid'" + runbook.RunbookID + "')/PublishedRunbookVersion/$value"; } return string.Empty; }
public Guid? TestRunbook(RunbookModelProxy runbookProxy, List<NameValuePair> parameters) { var jobGuid = Guid.NewGuid(); var runbook = _client.Runbooks.Get(_connectionData.AzureRMGroupName, _connectionData.AzureAutomationAccount, runbookProxy.RunbookName); if (runbook.StatusCode == System.Net.HttpStatusCode.NotFound) return null; var jobParameters = new TestJobCreateParameters(); jobParameters.RunbookName = runbookProxy.RunbookName; foreach (var param in parameters) jobParameters.Parameters.Add(param.Name, param.Value); var response = _client.TestJobs.Create(_connectionData.AzureRMGroupName, _connectionData.AzureAutomationAccount, jobParameters); if ((int)response.StatusCode > 299) { _output.AppendLine("Unable to start the job, please verify your connectivity and parameters and try again."); return null; } _testJobCache.Add(jobGuid, response.TestJob); runbookProxy.IsTestRun = true; return jobGuid; }
public async Task<bool> CheckRunningJobs(RunbookModelProxy runbook, bool checkDraft) { try { if (checkDraft) { // Test job var response = await _client.TestJobs.GetAsync(_connectionData.AzureRMGroupName, _connectionData.AzureAutomationAccount, runbook.RunbookName); if (response.StatusCode == System.Net.HttpStatusCode.OK) { if (_completionStatusList.Contains(response.TestJob.Status)) return false; } } else { var response = await _client.Jobs.GetAsync(_connectionData.AzureRMGroupName, _connectionData.AzureAutomationAccount, runbook.JobID); if (response.StatusCode == System.Net.HttpStatusCode.OK) { if (_completionStatusList.Contains(response.Job.Properties.Status)) return false; } } } catch (CloudException) { return false; } return true; }
public async Task<OperationStatus> SaveRunbookContentAsync(RunbookModelProxy runbook, string runbookContent, RunbookType runbookType) { var result = await SendRequestAsync("runbooks/" + runbook.RunbookName.ToUrlSafeString() + "/draft/content", HttpMethod.Put, runbookContent, "text/powershell").ConfigureAwait(false); if (runbookType == RunbookType.Published) { await CheckIn(runbook); } return OperationStatus.Succeeded; }
public JobModelProxy GetJobDetails(RunbookModelProxy runbook) { if (runbook.IsTestRun) return GetDraftJobDetails(runbook); if (runbook.JobID != Guid.Empty) return GetPublishedJobDetails(runbook.JobID); return new JobModelProxy(new Vendor.Azure.Job(), Context); }
public Guid? StartRunbook(RunbookModelProxy runbookProxy, List<SMA.NameValuePair> parameters) { var jobGuid = Guid.NewGuid(); var runbook = new Dictionary<string, string>(); runbook.Add("name", runbookProxy.RunbookName); var jobParameters = new Dictionary<string, string>(); foreach (var parameter in parameters) { jobParameters.Add(parameter.Name, parameter.Value); } var job = new Dictionary<string, Dictionary<string, object>>(); job.Add("properties", new Dictionary<string, object> { { "runbook", runbook } }); job["properties"].Add("parameters", jobParameters); var json = JsonConvert.SerializeObject(job); runbookProxy.IsTestRun = false; try { SendRequest("jobs/" + jobGuid, HttpMethod.Put, json, "application/json"); } catch (WebException ex) { //if (ex.Status == WebExceptionStatus.ProtocolError && (ex.Response as HttpWebResponse).StatusCode == HttpStatusCode.BadRequest) // MessageBox.Show("A job is already running, please wait for that to complete and then try again.", "Error", MessageBoxButton.OK, MessageBoxImage.Error); //else // MessageBox.Show("An unknown error occurred when trying to start the runbook: " + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error); throw new ApplicationException("An error occurred when starting the runbook, please refer to the output.", ex); } return jobGuid; }
public async Task ResumeExecution(RunbookModelProxy runbook, bool isDraft = false) { if (!_jobCache.ContainsKey(runbook.JobID) && !_testJobCache.ContainsKey(runbook.JobID)) return; if (isDraft) { // Test job await _client.TestJobs.ResumeAsync(_connectionData.AzureRMGroupName, _connectionData.AzureAutomationAccount, runbook.RunbookName); } else { await _client.Jobs.ResumeAsync(_connectionData.AzureRMGroupName, _connectionData.AzureAutomationAccount, runbook.JobID); } }
public Guid? TestRunbook(RunbookModelProxy runbookProxy, List<SMA.NameValuePair> parameters) { var jobGuid = Guid.NewGuid(); // Not used in this case, which is a bit confusing :( var runbook = new Dictionary<string, string>(); runbook.Add("name", runbookProxy.RunbookName); var jobParameters = new Dictionary<string, string>(); foreach (var parameter in parameters) { jobParameters.Add(parameter.Name, parameter.Value); } var job = new Dictionary<string, Dictionary<string, object>>(); job.Add("properties", new Dictionary<string, object> { { "parameters", jobParameters } }); var json = JsonConvert.SerializeObject(job); runbookProxy.IsTestRun = true; // Try to start the runbook job try { var result = SendRequest("runbooks/" + runbookProxy.RunbookName.ToUrlSafeString() + "/draft/testJob", HttpMethod.Put, json, "application/json"); } catch (WebException ex) { throw new ApplicationException("An error occurred when testing the runbook, please refer to the output.", ex); } return jobGuid; }
public async Task<OperationResult> SaveRunbookAsync(RunbookModelProxy runbook, string runbookContent) { var runbookCreated = false; var response = default(RunbookCreateOrUpdateResponse); //if (runbook.RunbookID == Guid.Empty) //{ //runbookNeedsCreation = true; // This is a new runbook! var draft = new RunbookDraft(); draft.InEdit = true; draft.CreationTime = DateTimeOffset.Now; draft.LastModifiedTime = DateTimeOffset.Now; var details = new RunbookCreateOrUpdateDraftParameters(); details.Name = runbook.RunbookName; details.Location = _connectionData.AzureRMLocation; details.Tags.Add(AutoStudioTagName, runbook.Tags != null ? runbook.Tags : string.Empty); details.Properties = new RunbookCreateOrUpdateDraftProperties(); details.Properties.RunbookType = "Script"; details.Properties.Description = "Runbook created with Automation Studio."; details.Properties.Draft = draft; response = await _client.Runbooks.CreateOrUpdateWithDraftAsync(_connectionData.AzureRMGroupName, _connectionData.AzureAutomationAccount, details); if (response.StatusCode == System.Net.HttpStatusCode.InternalServerError) runbookCreated = false; else runbookCreated = true; // Need to set the draft runbook ID to notify the system that this runbook is in draft mode runbook.DraftRunbookVersionID = Guid.NewGuid(); //} if (!runbookCreated /*&& runbookNeedsCreation*/) { return new OperationResult { ErrorCode = response.StatusCode.ToString(), ErrorMessage = "Unable to save the runbook", HttpStatusCode = response.StatusCode, Status = OperationStatus.Failed }; } // Now we need to commit the draft var status = await SaveRunbookContentAsync(runbook, runbookContent, RunbookType.Draft); // Make sure that we add the runbook to our Env Explorer if (runbook.RunbookID == Guid.Empty) { Context.Start(); } return new OperationResult { HttpStatusCode = System.Net.HttpStatusCode.OK, Status = status, RequestUrl = string.Empty }; }
public string GetBackendUrl(RunbookType runbookType, RunbookModelProxy runbook) { switch (runbookType) { case RunbookType.Draft: return AzureBaseUrl + String.Format(AzureResourceUrl, _connectionData.AzureSubscriptionId, _connectionData.AzureAutomationAccount, "runbooks/" + runbook.RunbookName + "/draft/content"); case RunbookType.Published: return AzureBaseUrl + String.Format(AzureResourceUrl, _connectionData.AzureSubscriptionId, _connectionData.AzureAutomationAccount, "runbooks/" + runbook.RunbookName + "/content"); } return string.Empty; }
public async Task StopExecution(RunbookModelProxy runbook, bool isDraft = false) { if (isDraft) await SendRequestAsync("runbooks/" + runbook.RunbookName.ToUrlSafeString() + "/draft/testJob/stop", HttpMethod.Post, "", "0").ConfigureAwait(false); else await SendRequestAsync("jobs/" + runbook.JobID + "/stop", HttpMethod.Post, "", "0").ConfigureAwait(false); }
public async Task<bool> CheckRunningJobs(RunbookModelProxy runbook, bool checkDraft) { var result = string.Empty; if (checkDraft) { result = await SendRequestAsync("runbooks/" + runbook.RunbookName.ToUrlSafeString() + "/draft/testJob", HttpMethod.Get).ConfigureAwait(false); } else if (runbook.JobID != Guid.Empty) { result = await SendRequestAsync("jobs/" + runbook.JobID, HttpMethod.Get).ConfigureAwait(false); } if (result.Length > 0) { dynamic jobRaw = JObject.Parse(result); var status = jobRaw.status.ToString(); if (_completionStatusList.Contains(status)) return false; } else return false; return true; }
public static Snippet CreateAvalonEditSnippet(RunbookModelProxy runbook, string snippetText) { if (snippetText == null) throw new ArgumentNullException("text"); var replaceableElements = new Dictionary<string, SnippetReplaceableTextElement>(StringComparer.OrdinalIgnoreCase); foreach (Match m in pattern.Matches(snippetText)) { string val = m.Groups[1].Value; int equalsSign = val.IndexOf('='); if (equalsSign > 0) { string name = val.Substring(0, equalsSign); replaceableElements[name] = new SnippetReplaceableTextElement(); } } Snippet snippet = new Snippet(); int pos = 0; foreach (Match m in pattern.Matches(snippetText)) { if (pos < m.Index) { snippet.Elements.Add(new SnippetTextElement { Text = snippetText.Substring(pos, m.Index - pos) }); pos = m.Index; } snippet.Elements.Add(CreateElementForValue(runbook, replaceableElements, m.Groups[1].Value, m.Index, snippetText)); pos = m.Index + m.Length; } if (pos < snippetText.Length) { snippet.Elements.Add(new SnippetTextElement { Text = snippetText.Substring(pos) }); } if (!snippet.Elements.Any(e => e is SnippetCaretElement)) { var obj = snippet.Elements.FirstOrDefault(e2 => e2 is SnippetSelectionElement); int index = snippet.Elements.IndexOf(obj); if (index > -1) snippet.Elements.Insert(index + 1, new SnippetCaretElement()); } return snippet; }
private JobModelProxy GetDraftJobDetails(RunbookModelProxy runbook) { var result = SendRequest("runbooks/" + runbook.RunbookName.ToUrlSafeString() + "/draft/testJob", HttpMethod.Get); if (result.Length < 1) return null; dynamic jsonJob = JObject.Parse(result); var job = new Job(); job.JobID = Guid.NewGuid(); job.CreationTime = (DateTime)jsonJob.creationTime; job.LastModifiedTime = (DateTime)jsonJob.lastModifiedTime; job.JobStatus = jsonJob.status; job.StartTime = jsonJob.startTime != null ? (DateTime?)jsonJob.startTime : null; job.EndTime = jsonJob.endTime != null ? (DateTime?)jsonJob.endTime : null; job.JobException = jsonJob.exception; var jobModelProxy = new JobModelProxy(job, Context); foreach (var param in jsonJob.parameters) { //jobModelProxy.Parameters.Add(param) } var output = string.Empty; try { output = SendRequest("runbooks/" + runbook.RunbookName.ToUrlSafeString() + "/draft/testJob/streams", HttpMethod.Get); jobModelProxy = ParseJobStreams(jobModelProxy, output); } catch (WebException) { // The job haven't been started yet, ignore this. } return jobModelProxy; }
static string GetValue(RunbookModelProxy runbook, string propertyName) { if (runbook == null) return null; var property = runbook.GetType().GetProperty(propertyName); if (property != null) { return property.GetValue(runbook).ToString(); } return null; }
/// <summary> /// Stops execution of a runbook /// </summary> /// <param name="jobId">ID of the job to stop</param> public Task StopExecution(RunbookModelProxy runbook, bool isDraft = false) { Logger.DebugFormat("StopExecution(jobId = {0})", runbook.JobID); var context = GetConnection(); var job = context.Jobs.Where(j => j.JobID == runbook.JobID).FirstOrDefault(); if (job == null) return TaskUtility.Completed; try { job.Stop(context); } catch (DataServiceQueryException ex) { throw new ApplicationException("Error when stoping the runbook. Please refer to the output for more information.", ex); } return TaskUtility.Completed; }