public object ExecuteCommand(string guid, string command, string stringFormat) { var serializer = new JavaScriptSerializer(); var output = new StringBuilder(); if (!IsLoggedInUserAuthorized || !SessionElevationManager.IsSessionTokenElevated(ApplicationNames.Console)) { return(serializer.Serialize( new { status = StatusElevationRequired, result = "You need to be authenticated, elevated and have sufficient privileges to use the PowerShell console. Please (re)login to Sitecore.", prompt = "PS >", background = OutputLine.ProcessHtmlColor(ConsoleColor.DarkBlue) })); } PowerShellLog.Info($"Arbitrary script execution in Console session '{guid}' by user: '******'"); var session = GetScriptSession(guid); session.Interactive = true; session.SetItemContextFromLocation(); try { var handle = ID.NewID.ToString(); var jobOptions = new JobOptions(GetJobId(guid, handle), "PowerShell", "shell", this, nameof(RunJob), new object[] { session, command }) { AfterLife = new TimeSpan(0, 0, 20), ContextUser = Sitecore.Context.User, EnableSecurity = true, ClientLanguage = Sitecore.Context.ContentLanguage }; JobManager.Start(jobOptions); Thread.Sleep(WebServiceSettings.CommandWaitMillis); return(PollCommandOutput(guid, handle, stringFormat)); } catch (Exception ex) { return (serializer.Serialize( new Result { status = StatusError, result = output + ScriptSession.GetExceptionString(ex, ScriptSession.ExceptionStringFormat.Console) + "\r\n" + "\r\n[[;#f00;#000]Uh oh, looks like the command you ran is invalid or something else went wrong. Is it something we should know about?]\r\n" + "[[;#f00;#000]Please submit a support ticket here https://git.io/spe with error details, screenshots, and anything else that might help.]\r\n\r\n" + "[[;#f00;#000]We also have a user guide here http://doc.sitecorepowershell.com/.]\r\n\r\n", prompt = $"PS {session.CurrentLocation}>", background = OutputLine.ProcessHtmlColor(session.PrivateData.BackgroundColor), color = OutputLine.ProcessHtmlColor(session.PrivateData.ForegroundColor) })); } }
protected override void ProcessSession(ScriptSession session) { if (State != RunspaceAvailability.None && State != session.State) { return; } if (SessionType != null && SessionType.Length > 0) { if (patterns == null) { patterns = new List <WildcardPattern>(SessionType.Length); foreach (var type in SessionType) { patterns.Add(GetWildcardPattern(type)); } } if (!patterns.Any(pattern => pattern.IsMatch(session.ApplianceType))) { return; } } WriteObject(session); }
protected override void ProcessSession(ScriptSession session) { if (session.State == RunspaceAvailability.Busy) { WriteError(typeof(CmdletInvocationException), $"The script session with Id '{session.ID}' cannot execute the script because it is Busy. Use Stop-ScriptSession or wait for the operation to complete.", ErrorIds.ScriptSessionBusy, ErrorCategory.ResourceBusy, session.ID); return; } session.AutoDispose = AutoDispose; session.SetItemLocationContext(ContextItem); if (ArgumentList != null) { foreach (string argument in ArgumentList.Keys) { session.SetVariable(argument, ArgumentList[argument]); } } var handle = string.IsNullOrEmpty(JobName) ? ID.NewID.ToString() : JobName; var jobOptions = new JobOptions(GetJobId(session.ID, handle), "PowerShell", "shell", this, nameof(RunJob), new object[] { session, scriptBlock.ToString() }) { AfterLife = new TimeSpan(0, 0, 1), ContextUser = Identity ?? Context.User, EnableSecurity = !DisableSecurity, ClientLanguage = Context.ContentLanguage }; if (Interactive) { var appParams = new Hashtable(); if (scriptItem != null) { appParams.Add("scriptId", scriptItem.ID.ToString()); appParams.Add("scriptDb", scriptItem.Database.Name); } else { session.JobScript = scriptBlock.ToString(); session.JobOptions = jobOptions; } appParams.Add("cfs", "1"); appParams.Add("sessionKey", session.Key); var message = new ShowApplicationMessage("PowerShell/PowerShell Runner", "PowerShell", "", "500", "360", false, appParams) { Title = " " }; PutMessage(message); } else { Sitecore.Jobs.JobManager.Start(jobOptions); } WriteObject(session); }
protected virtual void JobExecuteScript(ClientPipelineArgs args, string scriptToExecute, ScriptSession scriptSession, bool autoDispose, bool debug) { ScriptRunning = true; UpdateRibbon(); PowerShellLog.Info($"Arbitrary script execution in ISE by user: '******'"); scriptSession.SetExecutedScript(ScriptItem); var parameters = new object[] { scriptSession, scriptToExecute }; var progressBoxRunner = new ScriptRunner(ExecuteInternal, scriptSession, scriptToExecute, autoDispose); var rnd = new Random(); Context.ClientPage.ClientResponse.SetInnerHtml( "ScriptResult", string.Format( "<div id='PleaseWait'>" + "<img src='../../../../../sitecore modules/PowerShell/Assets/working.gif' alt='" + Texts.PowerShellIse_JobExecuteScript_Working + "' />" + "<div>" + Texts.PowerShellIse_JobExecuteScript_Please_wait___0_ + "</div>" + "</div>" + "<pre ID='ScriptResultCode'></pre>", ExecutionMessages.PleaseWaitMessages[ rnd.Next(ExecutionMessages.PleaseWaitMessages.Length - 1)])); Context.ClientPage.ClientResponse.Eval("if(cognifide.powershell.preventCloseWhenRunning){cognifide.powershell.preventCloseWhenRunning(true);}"); scriptSession.Debugging = debug; Monitor.Start($"{DefaultSessionName}", "ISE", progressBoxRunner.Run, LanguageManager.IsValidLanguageName(CurrentLanguage) ? LanguageManager.GetLanguage(CurrentLanguage) : Context.Language, User.Exists(CurrentUser) ? User.FromName(CurrentUser, true) : Context.User); Monitor.SessionID = scriptSession.ID; SheerResponse.Eval("cognifide.powershell.restoreResults();"); var settings = ApplicationSettings.GetInstance(ApplicationNames.ISE); if (settings.SaveLastScript) { settings.Load(); settings.LastScript = Editor.Value; settings.Save(); } }
public void Run() { try { Method(Session, Script); if (Context.Job == null) { return; } Context.Job.Status.Result = new RunnerOutput { Exception = null, Output = Session.Output.GetHtmlUpdate(), HasErrors = Session.Output.HasErrors, CloseRunner = Session.CloseRunner }; JobContext.PostMessage("psr:updateresults"); JobContext.Flush(); } catch (ThreadAbortException taex) { LogUtils.Error("Script was aborted", taex, this); if (!Environment.HasShutdownStarted) { Thread.ResetAbort(); } } catch (Exception exc) { LogUtils.Error(ScriptSession.GetExceptionString(exc), exc); if (Context.Job != null) { Context.Job.Status.Result = new RunnerOutput { Exception = exc, Output = Session.Output.GetHtmlUpdate(), HasErrors = true, CloseRunner = Session.CloseRunner }; JobContext.PostMessage("psr:updateresults"); JobContext.Flush(); } } finally { Session.CloseRunner = false; Session.Output.Clear(); if (AutoDispose) { Session.Dispose(); } } }
public CodeRunner(ScriptRunnerMethod method, ScriptSession session, String script) { Assert.ArgumentNotNull(script, nameof(script)); Assert.ArgumentNotNull(method, nameof(method)); Assert.ArgumentNotNull(session, nameof(session)); this.Session = session; this.Script = script; this.Method = method; }
public object ExecuteCommand(string guid, string command, string stringFormat) { if (!WebServiceSettings.ServiceEnabledClient) { return(string.Empty); } var serializer = new JavaScriptSerializer(); var output = new StringBuilder(); if (!HttpContext.Current.Request.IsAuthenticated && !command.StartsWith("login-user", StringComparison.OrdinalIgnoreCase)) { return(serializer.Serialize( new { result = "You need to be authenticated to use the PowerShell console. Please login to Sitecore first.", prompt = "PS >", background = OutputLine.ProcessHtmlColor(ConsoleColor.DarkBlue) })); } var session = GetScriptSession(guid); session.Interactive = true; try { var handle = ID.NewID.ToString(); var jobOptions = new JobOptions(GetJobId(guid, handle), "PowerShell", "shell", this, "RunJob", new object[] { session, command }) { AfterLife = new TimeSpan(0, 0, 20), ContextUser = Sitecore.Context.User, EnableSecurity = true, ClientLanguage = Sitecore.Context.ContentLanguage }; JobManager.Start(jobOptions); Thread.Sleep(WebServiceSettings.CommandWaitMillis); return(PollCommandOutput(guid, handle, stringFormat)); } catch (Exception ex) { return (serializer.Serialize( new Result { status = StatusError, result = output + ScriptSession.GetExceptionString(ex, ScriptSession.ExceptionStringFormat.Console) + "\r\n" + "\r\n[[;#f00;#000]Uh oh, looks like the command you ran is invalid or something else went wrong. Is it something we should know about?]\r\n" + "[[;#f00;#000]Please submit a support ticket here https://git.io/spe with error details, screenshots, and anything else that might help.]\r\n\r\n" + "[[;#f00;#000]We also have a user guide here http://sitecorepowershell.gitbooks.io/sitecore-powershell-extensions/.]\r\n\r\n", prompt = $"PS {session.CurrentLocation}>", background = OutputLine.ProcessHtmlColor(session.PrivateData.BackgroundColor), color = OutputLine.ProcessHtmlColor(session.PrivateData.ForegroundColor) })); } }
public ScriptRunner(ScriptRunnerMethod method, ScriptSession session, string script, bool autoDispose) { Assert.ArgumentNotNull(method, "method"); Assert.ArgumentNotNull(session, "session"); Assert.ArgumentNotNull(script, "script"); Method = method; Session = session; Script = script; AutoDispose = autoDispose; }
public void Invoke() { using (ScriptSession scriptSession = ScriptSessionManager.NewSession("Default", true)) { Item speScriptItem = Sitecore.Context.Database.GetItem("/path-or-id/to-spe-item"); string script = speScriptItem["Script"]; if (!string.IsNullOrEmpty(script)) { scriptSession.ExecuteScriptPart(script); } } }
protected void RunPlugin(ClientPipelineArgs args) { ScriptSession scriptSession = ScriptSessionManager.NewSession(ApplicationNames.IseConsole, true); string scriptDb = args.Parameters["scriptDb"]; string scriptItem = args.Parameters["scriptId"]; Item script = Factory.GetDatabase(scriptDb).GetItem(scriptItem); scriptSession.SetVariable("scriptText", Editor.Value); scriptSession.SetVariable("selectionText", SelectionText.Value.Trim()); scriptSession.SetVariable("scriptItem", ScriptItem); scriptSession.Interactive = true; JobExecuteScript(args, script[ScriptItemFieldNames.Script], scriptSession, true, false); }
/// <summary> /// Delete session on server. /// </summary> /// <param name="pythonSession">Session to delete</param> private void EndPythonSession(HttpClient httpClient, ScriptSession pythonSession) { // uri Uri requestUri = new Uri($"{httpClient.BaseAddress}{ScriptPath}/{pythonSession.Id}"); // request try { httpClient.Delete(requestUri, ScriptHostResult.ParseEndSessionResult); } catch (EmptyHttpResponseException) { // response of delete should be empty, so catch this } }
public ActionResult <ScriptSession> Get() { return(Execute(() => { ScriptSession pythonSession = SessionService.CreateSession(); ExpireSessionTimer sessionTimer = new ExpireSessionTimer(pythonSession, SettingsProvider.SessionLifetime); Sessions.Add(pythonSession.Id, sessionTimer); sessionTimer.Start(); Log.Information($"Request new session DONE. Created session with ID '{pythonSession.Id}' and expire date '{pythonSession.ExpireDate.ToLongTimeString()}'"); return Ok(pythonSession); })); }
protected void RunJob(ScriptSession session, string command) { if (!IsLoggedInUserAuthorized) { return; } try { if (!string.IsNullOrEmpty(command)) { if (session.IsRunning) { session.TryInvokeInRunningSession(command); } else { session.ExecuteScriptPart(command); } } } catch (Exception ex) { var jobManager = TypeResolver.ResolveFromCache <IJobManager>(); var job = jobManager.GetContextJob(); if (job != null) { job.StatusFailed = true; var exceptionMessage = ScriptSession.GetExceptionString(ex); if (job.Options.WriteToLog) { PowerShellLog.Error("Error while executing PowerShell Extensions script.", ex); } job.AddStatusMessage(exceptionMessage); job.AddStatusMessage( "Uh oh, looks like the command you ran is invalid or something else went wrong. Is it something we should know about?"); job.AddStatusMessage( "Please submit a support ticket here https://git.io/spe with error details, screenshots, and anything else that might help."); job.AddStatusMessage( "We also have a user guide here https://doc.sitecorepowershell.com/."); } else { PowerShellLog.Error("Script execution failed. Could not find command job.", ex); } } }
protected static IEnumerable <Item> RunEnumeration(string scriptSource, Item item) { Assert.ArgumentNotNull(scriptSource, "scriptSource"); Assert.ArgumentNotNull(item, "item"); scriptSource = scriptSource.Replace("script:", "").Trim(); var scriptItem = item.Database.GetItem(scriptSource); using (var session = ScriptSessionManager.NewSession(ApplicationNames.Default, true)) { var script = (scriptItem.Fields[ScriptItemFieldNames.Script] != null) ? scriptItem.Fields[ScriptItemFieldNames.Script].Value : string.Empty; script = string.Format("{0}\n{1}", ScriptSession.GetDataContextSwitch(item), script); return(session.ExecuteScriptPart(script, false).Cast <Item>()); } }
/// <summary> /// Creates a new instance of session timer. /// </summary> /// <param name="pythonSession">Python session to terminate</param> /// <param name="interval">Interval when session should be end</param> public ExpireSessionTimer(ScriptSession pythonSession, double interval) : base(interval) { #region validation if (pythonSession == null) { throw new ArgumentNullException(nameof(pythonSession)); } #endregion this.ParametersDirectory = pythonSession.ParametersDirectory; this.ResultsDirectory = pythonSession.ResultDirectory; this.Elapsed += ExpireSessionTimerElapsed; }
/// <summary> /// Runs the healthcheck. /// </summary> public override void RunHealthcheck() { this.LastCheckTime = DateTime.UtcNow; var invokeScript = $"ExecuteHealthcheck -componentId {this.InnerItem.ID.ToString()} -params {GetParamsFromNameValue(this.Parameters)}"; try { using (ScriptSession scriptSession = ScriptSessionManager.NewSession("Default", true)) { string script = this.ScriptItem["Script"]; script += Environment.NewLine + invokeScript; if (!string.IsNullOrEmpty(script)) { var output = scriptSession.ExecuteScriptPart(script, false); if (output.Count > 0) { Hashtable result = (Hashtable)output[0]; this.Status = (HealthcheckStatus)Enum.Parse(typeof(HealthcheckStatus), result["Status"].ToString()); if (this.Status != HealthcheckStatus.Healthy) { this.ErrorList.Entries.Add(new ErrorEntry { Created = DateTime.UtcNow, Reason = result["Reason"].ToString() }); } else { this.HealthyMessage = result["HealthyMessage"].ToString(); } } } } } catch (Exception ex) { this.Status = HealthcheckStatus.Error; this.ErrorList.Entries.Add(new ErrorEntry { Created = DateTime.UtcNow, Reason = ex.Message, Exception = ex }); } }
private static void ProcessTaskItem(Item item, ScriptSession session) { var featureRoot = ModuleManager.GetItemModule(item)? .GetFeatureRoot(IntegrationPoints.TasksFeature); if (!RulesUtils.EvaluateRules(featureRoot?[Templates.ScriptLibrary.Fields.EnableRule], item)) { return; } var queue = new Queue <Item>(); queue.Enqueue(item); Item currentItem; while (queue.Count > 0 && (currentItem = queue.Dequeue()) != null) { if (currentItem.IsPowerShellScript()) { if (string.IsNullOrWhiteSpace(currentItem[Templates.Script.Fields.ScriptBody])) { continue; } if (!RulesUtils.EvaluateRules(currentItem[Templates.Script.Fields.EnableRule], currentItem)) { continue; } session.SetItemLocationContext(currentItem); session.ExecuteScriptPart(currentItem, true); } else if (currentItem.IsPowerShellLibrary() && currentItem.HasChildren) { if (!RulesUtils.EvaluateRules(currentItem[Templates.ScriptLibrary.Fields.EnableRule], currentItem)) { continue; } var children = currentItem.Children.ToArray(); foreach (var child in children) { queue.Enqueue(child); } } } }
protected override void ProcessSession(ScriptSession session) { if (!ShouldProcess(session.ID, "Remove existing script session")) { return; } if (session.State == RunspaceAvailability.Busy) { WriteError(typeof(CmdletInvocationException), $"The script session with Id '{session.ID}' cannot be unloaded because it is in the Busy state. Use Stop-ScriptSession or wait for the operation to complete.", ErrorIds.ScriptSessionBusy, ErrorCategory.ResourceBusy, session.ID); return; } ScriptSessionManager.RemoveSession(session); }
protected virtual void ClientExecute(ClientPipelineArgs args) { args.Parameters["message"] = "ise:run"; if (!RequestSessionElevationEx(args, ApplicationNames.ISE, SessionElevationManager.ExecuteAction)) { return; } PowerShellLog.Info($"Arbitrary script execution in ISE by user: '******'"); using (var scriptSession = ScriptSessionManager.NewSession(ApplicationNames.ISE, true)) { var settings = scriptSession.Settings; try { if (UseContext) { scriptSession.SetItemLocationContext(ContextItem); } scriptSession.SetExecutedScript(ScriptItem); scriptSession.ExecuteScriptPart(Editor.Value); if (scriptSession.Output != null) { Context.ClientPage.ClientResponse.SetInnerHtml("Result", scriptSession.Output.ToHtml()); } } catch (Exception exc) { var result = string.Empty; if (scriptSession.Output != null) { result += scriptSession.Output.ToHtml(); } result += string.Format("<pre style='background:red;'>{0}</pre>", ScriptSession.GetExceptionString(exc, ScriptSession.ExceptionStringFormat.Html)); Context.ClientPage.ClientResponse.SetInnerHtml("Result", result); } if (settings.SaveLastScript) { settings.Load(); settings.LastScript = Editor.Value; settings.Save(); } } }
public ScriptSession CreateSession() { string sessionId = GuidService.GenerateGuid(); string parametersDirectory = ParametersFileContainer.CreatePath(sessionId); string resultDirectory = ResultFileContainer.CreatePath(sessionId); ScriptSession pythonSession = new ScriptSession() { Id = sessionId, ExpireDate = DateTimeService.GetNow().AddMilliseconds(SettingsProvider.SessionLifetime).ToUniversalTime(), ParametersDirectory = parametersDirectory, ResultDirectory = resultDirectory }; return(pythonSession); }
protected void ExecuteInternal(ScriptSession scriptSession, string script) { try { scriptSession.ExecuteScriptPart(script); } finally { if (!string.IsNullOrEmpty(scriptSession.DebugFile)) { File.Delete(scriptSession.DebugFile); scriptSession.DebugFile = string.Empty; } scriptSession.Debugging = false; scriptSession.ExecuteScriptPart("Get-PSBreakpoint | Remove-PSBreakpoint"); } }
protected virtual void JobExecuteScript(ClientPipelineArgs args, string scriptToExecute, ScriptSession scriptSession, bool autoDispose, bool debug) { ScriptRunning = true; UpdateRibbon(); scriptSession.SetExecutedScript(ScriptItem); var parameters = new object[] { scriptSession, scriptToExecute }; var progressBoxRunner = new ScriptRunner(ExecuteInternal, scriptSession, scriptToExecute, autoDispose); var rnd = new Random(); Context.ClientPage.ClientResponse.SetInnerHtml( "ScriptResult", string.Format( "<div id='PleaseWait'>" + "<img src='../../../../../sitecore modules/PowerShell/Assets/working.gif' alt='Working' />" + "<div>Please wait, {0}</div>" + "</div>" + "<pre ID='ScriptResultCode'></pre>", ExecutionMessages.PleaseWaitMessages[ rnd.Next(ExecutionMessages.PleaseWaitMessages.Length - 1)])); Context.ClientPage.ClientResponse.Eval("if(cognifide.powershell.preventCloseWhenRunning){cognifide.powershell.preventCloseWhenRunning(true);}"); scriptSession.Debugging = debug; Monitor.Start("ScriptExecution", "UI", progressBoxRunner.Run); Monitor.SessionID = scriptSession.ID; SheerResponse.Eval("cognifide.powershell.restoreResults();"); var settings = ApplicationSettings.GetInstance(ApplicationNames.IseConsole); if (settings.SaveLastScript) { settings.Load(); settings.LastScript = Editor.Value; settings.Save(); } }
private void MonitorOnJobFinished(object sender, EventArgs e) { var args = e as SessionCompletedEventArgs; var result = args?.RunnerOutput; if (!result.IsNull() && result.Exception.IsNull()) { SheerResponse.SetInnerHtml("ScriptResult", result.Output); } if (result?.Exception != null) { //TODO: Implement get exection string through script session var error = ScriptSession.GetExceptionString(result.Exception); SheerResponse.SetInnerHtml("ScriptResult", error); } ScriptRunning = false; UpdateRibbon(); }
private void ExecuteScriptJob(Item scriptItem, ScriptSession scriptSession, Message message, bool autoDispose) { var script = (scriptItem.Fields[ScriptItemFieldNames.Script] != null) ? scriptItem.Fields[ScriptItemFieldNames.Script].Value : string.Empty; SetVariables(scriptSession, message); scriptSession.SetExecutedScript(scriptItem); scriptSession.Interactive = true; ScriptSessionId = scriptSession.ID; var progressBoxRunner = new ScriptRunner(ExecuteInternal, scriptSession, script, autoDispose); Monitor.Start("ScriptExecution", "UI", progressBoxRunner.Run); LvProgressOverlay.Visible = false; Monitor.SessionID = scriptSession.ID; }
public void Run(PublishContext publishContext) { Item scriptItem = Factory.GetDatabase("master").GetItem(publishNotificationScriptID); try { using (ScriptSession scriptSession = ScriptSessionManager.NewSession(ApplicationNames.Default, true)) { scriptSession.SetVariable("publishContext", publishContext); scriptSession.ExecuteScriptPart(scriptItem, true); PowerShellLog.Info($"Job ended: Send Teams Notification"); } } catch (Exception ex) { PowerShellLog.Error($"Error while invoking {scriptItem.Paths.FullPath} script from Send Teams Notification job", ex); } }
protected static IEnumerable <Item> RunEnumeration(string scriptSource, Item item) { Assert.ArgumentNotNull(scriptSource, "scriptSource"); scriptSource = scriptSource.Replace("script:", "").Trim(); var database = item?.Database ?? Sitecore.Context.ContentDatabase ?? Sitecore.Context.Database; var scriptItem = ID.IsID(scriptSource) ? database.GetItem(ID.Parse(scriptSource)) : database.GetItem(scriptSource); if (!scriptItem.IsPowerShellScript()) { return(new[] { scriptItem ?? item }); } using (var session = ScriptSessionManager.NewSession(ApplicationNames.Default, true)) { var script = scriptItem[Templates.Script.Fields.ScriptBody] ?? string.Empty; script = $"{ScriptSession.GetDataContextSwitch(item)}\n{script}"; return(session.ExecuteScriptPart(script, false).Where(i => i is Item).Cast <Item>()); } }
private void SetVariables(ScriptSession session, Message message) { //visible objects in string form for export var export = ListViewer.FilteredItems.Select(p => { var psobj = new PSObject(); foreach (var property in p.Display) { psobj.Properties.Add(new PSNoteProperty(property.Key, property.Value)); } return(psobj); }).ToList(); //selected original objects var results = ListViewer.SelectedItems.Select(p => { var id = Int32.Parse(p.Value); return(ListViewer.Data.Data.Where(d => d.Id == id).Select(d => d.Original).First()); }).ToList(); session.SetVariable("filteredData", ListViewer.FilteredItems.Select(p => p.Original).ToList()); session.SetVariable("resultSet", results); session.SetVariable("selectedData", results); session.SetVariable("exportData", export); session.SetVariable("allData", ListViewer.Data.Data.Select(p => p.Original).ToList()); session.SetVariable("allDataInternal", ListViewer.Data.Data); session.SetVariable("actionData", ListViewer.Data.ActionData); session.SetVariable("title", ListViewer.Data.Title); session.SetVariable("infoTitle", ListViewer.Data.InfoTitle); session.SetVariable("infoDescription", ListViewer.Data.InfoDescription); session.SetVariable("formatProperty", ListViewer.Data.Property.Cast <object>().ToArray()); session.SetVariable("formatPropertyStr", ListViewer.Data.FormatProperty); session.SetVariable("exportProperty", ListViewer.Data.ExportProperty); if (message != null) { foreach (var key in message.Arguments.AllKeys) { session.SetVariable(key, message.Arguments[key]); } } }
protected void RunJob(ScriptSession session, string command) { if (!WebServiceSettings.ServiceEnabledClient || !Sitecore.Context.IsLoggedIn) { return; } try { if (!string.IsNullOrEmpty(command)) { if (session.IsRunning) { session.TryInvokeInRunningSession(command); } else { session.ExecuteScriptPart(command); } } } catch (Exception ex) { var job = Sitecore.Context.Job; if (job != null) { job.Status.Failed = true; var exceptionMessage = ScriptSession.GetExceptionString(ex); if (job.Options.WriteToLog) { LogUtils.Error(exceptionMessage, this); } job.Status.Messages.Add(exceptionMessage); job.Status.Messages.Add("Uh oh, looks like the command you ran is invalid or something else went wrong. Is it something we should know about?"); job.Status.Messages.Add("Please submit a support ticket here https://git.io/spe with error details, screenshots, and anything else that might help."); job.Status.Messages.Add("We also have a user guide here http://sitecorepowershell.gitbooks.io/sitecore-powershell-extensions/."); } else { LogUtils.Error("Script execution failed. Could not find command job.", ex, this); } } }
private void ExecuteScriptJob(Item scriptItem, ScriptSession scriptSession, Message message, bool autoDispose) { if (!scriptItem.IsPowerShellScript()) { SessionElevationErrors.OperationFailedWrongDataTemplate(); return; } var script = scriptItem[Templates.Script.Fields.ScriptBody] ?? string.Empty; SetVariables(scriptSession, message); scriptSession.SetExecutedScript(scriptItem); scriptSession.Interactive = true; ScriptSessionId = scriptSession.ID; var progressBoxRunner = new ScriptRunner(ExecuteInternal, scriptSession, script, autoDispose); Monitor.Start($"SPE - \"{ListViewer?.Data?.Title}\" - \"{scriptItem?.Name}\"", "UI", progressBoxRunner.Run); LvProgressOverlay.Visible = false; Monitor.SessionID = scriptSession.ID; }
private void MonitorOnJobFinished(object sender, EventArgs eventArgs) { var args = eventArgs as SessionCompleteEventArgs; var result = args.RunnerOutput; if (result != null) { PrintSessionUpdate(result.Output); } if (result?.Exception != null) { var error = ScriptSession.GetExceptionString(result.Exception, ScriptSession.ExceptionStringFormat.Html); PrintSessionUpdate($"<pre style='background:red;'>{error}</pre>"); } SheerResponse.SetInnerHtml("PleaseWait", ""); ProgressOverlay.Visible = false; ScriptRunning = false; UpdateRibbon(); SheerResponse.Eval("cognifide.powershell.scriptExecutionEnded()"); }
/// <summary> /// Save the session under a new file name. /// /// A new session object will be created from this new saved file (and returned by this method) /// and added to the project. The original session wil not be saved. /// </summary> /// <param name="theCurrentSession"></param> /// <returns>The new created session object, null if save as a new session has been cancelled or failed.</returns> public Session SaveSessionAs(Session theCurrentSession) { Session theNewSession = null; SaveFileDialog theSaveFileDialog = new SaveFileDialog(); theSaveFileDialog.AddExtension = true; theSaveFileDialog.DefaultExt = ".ses"; theSaveFileDialog.OverwritePrompt = false; theSaveFileDialog.Filter = "All session files (*.ses)|*.ses"; DialogResult theDialogResult = theSaveFileDialog.ShowDialog(); // User has specified a file name and has pressed the OK button. if (theDialogResult == DialogResult.OK) { if (File.Exists(theSaveFileDialog.FileName)) { MessageBox.Show(string.Format("File name \"{0}\" already exists.\nOperation cancelled", theSaveFileDialog.FileName)); } else { // Save the current session to a new file. string theCurrentSessionFullFileName = theCurrentSession.SessionFileName; theCurrentSession.SessionFileName = theSaveFileDialog.FileName; theCurrentSession.Save(); Session.SessionType sessionType = theCurrentSession.sessionType ; // Create a new session object from this new saved file and replace the current session. switch(sessionType) { case Session.SessionType.ST_MEDIA: theNewSession = new MediaSession(theSaveFileDialog.FileName); LoadSession(); break; case Session.SessionType.ST_SCRIPT: theNewSession = new ScriptSession(theSaveFileDialog.FileName); LoadSession(); break; case Session.SessionType.ST_EMULATOR: theNewSession = new EmulatorSession(theSaveFileDialog.FileName); LoadSession(); break; case Session.SessionType.ST_UNKNOWN: break; } // Create a new session object from this new saved file and replace the current session. if (theNewSession != null) { int theCurrentIndex = GetLoadedSessionsIndex(theCurrentSession); parentProject.Sessions[theCurrentIndex] = theNewSession; parentProject.HasProjectChanged = true; } } } return(theNewSession); }