public void Process(GetContentEditorWarningsArgs args)
        {
            Assert.ArgumentNotNull(args, "args");

            foreach (var libraryItem in ModuleManager.GetFeatureRoots(IntegrationPoint))
            {
                if (!libraryItem.HasChildren)
                {
                    return;
                }

                foreach (var scriptItem in libraryItem.Children.ToList())
                {
                    using (var session = ScriptSessionManager.NewSession(ApplicationNames.Default, true))
                    {
                        session.SetVariable("pipelineArgs", args);

                        try
                        {
                            session.SetItemLocationContext(args.Item);
                            session.ExecuteScriptPart(scriptItem, false);
                        }
                        catch (Exception ex)
                        {
                            PowerShellLog.Error($"Error while invoking script '{scriptItem?.Paths.Path}' in Content Editor Warning pipeline.", 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 == null || !scriptItem.IsPowerShellScript() ||
                string.IsNullOrWhiteSpace(scriptItem[Templates.Script.Fields.ScriptBody]) &&
                !RulesUtils.EvaluateRules(scriptItem[Templates.Script.Fields.EnableRule], item))
            {
                return(new[] { scriptItem ?? item });
            }

            using (var session = ScriptSessionManager.NewSession(ApplicationNames.Default, false))
            {
                if (item != null)
                {
                    session.SetItemLocationContext(item);
                }

                return(session.ExecuteScriptPart(scriptItem, false).Where(i => i is Item).Cast <Item>());
            }
        }
Beispiel #3
0
        public void Process(GetPageEditorNotificationsArgs args)
        {
            Assert.ArgumentNotNull(args, "args");

            foreach (var libraryItem in ModuleManager.GetFeatureRoots(IntegrationPoint))
            {
                if (!libraryItem.HasChildren)
                {
                    return;
                }

                foreach (var scriptItem in libraryItem.Children.ToList())
                {
                    using (var session = ScriptSessionManager.NewSession(ApplicationNames.Default, true))
                    {
                        session.SetVariable("pipelineArgs", args);

                        try
                        {
                            session.SetItemLocationContext(args.ContextItem);
                            session.ExecuteScriptPart(scriptItem, false);
                        }
                        catch (Exception ex)
                        {
                            LogUtils.Error(ex.Message, this);
                        }
                    }
                }
            }
        }
Beispiel #4
0
        protected void Process(TPipelineArgs args)
        {
            Assert.ArgumentNotNull(args, "args");

            foreach (var libraryItem in ModuleManager.GetFeatureRoots(IntegrationPoint))
            {
                if (!libraryItem.HasChildren)
                {
                    return;
                }

                foreach (var scriptItem in libraryItem.Children.ToList())
                {
                    if (!scriptItem.IsPowerShellScript() || string.IsNullOrWhiteSpace(scriptItem[Templates.Script.Fields.ScriptBody]))
                    {
                        continue;
                    }

                    using (var session = ScriptSessionManager.NewSession(ApplicationNames.Default, true))
                    {
                        session.SetVariable("pipelineArgs", args);

                        try
                        {
                            session.ExecuteScriptPart(scriptItem, false);
                        }
                        catch (Exception ex)
                        {
                            PowerShellLog.Error(
                                $"Error while executing script in {GetType().FullName} pipeline processor.", ex);
                        }
                    }
                }
            }
        }
        public NameValue[] ExecuteScript(string userName, string password, string script, string returnVariables)
        {
            if (!WebServiceSettings.ServiceEnabledRemoting)
            {
                return(new NameValue[0]);
            }
            Login(userName, password);
            using (var scriptSession = ScriptSessionManager.NewSession(ApplicationNames.RemoteAutomation, false))
            {
                scriptSession.ExecuteScriptPart(script);

                var result = new List <NameValue>();

                if (scriptSession.Output.Count > 0)
                {
                    result.Add(new NameValue
                    {
                        Name  = "output",
                        Value =
                            scriptSession.Output.Select(p => p.Terminated ? p.Text + "\n" : p.Text).Aggregate(
                                (current, next) => current + next)
                    });
                }
                result.AddRange(
                    returnVariables.Split('|').Select(variable => new NameValue
                {
                    Name  = variable,
                    Value = (scriptSession.GetVariable(variable) ?? string.Empty).ToString()
                }));
                return(result.ToArray());
            }
        }
Beispiel #6
0
        public void Process(GetPageEditorNotificationsArgs args)
        {
            Assert.ArgumentNotNull(args, "args");

            Func <Item, bool> filter = si => si.IsPowerShellScript() &&
                                       !string.IsNullOrWhiteSpace(si[Templates.Script.Fields.ScriptBody]) &&
                                       RulesUtils.EvaluateRules(si[Templates.Script.Fields.EnableRule], args.ContextItem);

            foreach (var libraryItem in ModuleManager.GetFeatureRoots(IntegrationPoint))
            {
                var applicableScriptItems = libraryItem?.Children?.Where(filter).ToArray();
                if (applicableScriptItems == null || !applicableScriptItems.Any())
                {
                    return;
                }

                foreach (var scriptItem in applicableScriptItems)
                {
                    using (var session = ScriptSessionManager.NewSession(ApplicationNames.Default, true))
                    {
                        session.SetVariable("pipelineArgs", args);

                        try
                        {
                            session.SetItemLocationContext(args.ContextItem);
                            session.ExecuteScriptPart(scriptItem, false);
                        }
                        catch (Exception ex)
                        {
                            PowerShellLog.Error($"Error while invoking script '{scriptItem?.Paths.Path}' in Page Editor Notification pipeline.", ex);
                        }
                    }
                }
            }
        }
Beispiel #7
0
        protected void Process(TPipelineArgs args)
        {
            Assert.ArgumentNotNull(args, "args");

            foreach (var libraryItem in ModuleManager.GetFeatureRoots(IntegrationPoint))
            {
                if (!libraryItem.HasChildren)
                {
                    return;
                }

                foreach (var scriptItem in libraryItem.Children.ToList())
                {
                    using (var session = ScriptSessionManager.NewSession(ApplicationNames.Default, true))
                    {
                        var script = (scriptItem.Fields[ScriptItemFieldNames.Script] != null)
                            ? scriptItem.Fields[ScriptItemFieldNames.Script].Value
                            : String.Empty;
                        session.SetVariable("pipelineArgs", args);

                        try
                        {
                            session.SetExecutedScript(scriptItem);
                            session.ExecuteScriptPart(script, false);
                        }
                        catch (Exception ex)
                        {
                            PowerShellLog.Error($"Error while executing script in {GetType().FullName} pipeline processor.", ex)
                            ;
                        }
                    }
                }
            }
        }
        private void ExportResults(Message message)
        {
            var scriptDb   = Database.GetDatabase(message.Arguments["scriptDb"]);
            var scriptItem = scriptDb.GetItem(message.Arguments["scriptID"]);
            var session    = ScriptSessionManager.NewSession(ApplicationNames.Default, true);

            ExecuteScriptJob(scriptItem, session, message, true);
        }
Beispiel #9
0
 public void Update(Item[] items, CommandItem command, ScheduleItem schedule)
 {
     using (var session = ScriptSessionManager.NewSession(ApplicationNames.Default, true))
     {
         foreach (var item in items)
         {
             ProcessTaskItem(item, session);
         }
     }
 }
Beispiel #10
0
 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);
         }
     }
 }
        private ScriptSession GetSession(Boolean onlyBuild)
        {
            var session = ScriptSessionManager.GetSession(CurrentSessionId, ApplicationNames.Console, true);

            if (session.IsNull())
            {
                session = ScriptSessionManager.NewSession(ApplicationNames.Console, true);
            }
            CurrentSessionId = session.Key;
            //var session = new ScriptSession("IDE", false, HttpContext.Current.Request.Url.Host, onlyBuild);
            session.Initialize();
            return(session);
        }
Beispiel #12
0
        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);
        }
        public void OnEvent(object sender, EventArgs args)
        {
            Item item      = null;
            var  eventName = EventArgToEventName(args);

            if (args is SitecoreEventArgs)
            {
                var scevent = (SitecoreEventArgs)args;
                item = scevent.Parameters[0] as Item;
            }

            if (String.IsNullOrEmpty(eventName))
            {
                return;
            }

            Func <Item, bool> filter = si => si.IsPowerShellScript() &&
                                       !string.IsNullOrWhiteSpace(si[Templates.Script.Fields.ScriptBody]) &&
                                       RulesUtils.EvaluateRules(si[Templates.Script.Fields.EnableRule], item);

            foreach (var root in ModuleManager.GetFeatureRoots(IntegrationPoints.EventHandlersFeature))
            {
                if (!RulesUtils.EvaluateRules(root?[Templates.ScriptLibrary.Fields.EnableRule], item))
                {
                    continue;
                }

                var libraryItem = root?.Paths.GetSubItem(eventName);

                var applicableScriptItems = libraryItem?.Children?.Where(filter).ToArray();
                if (applicableScriptItems == null || !applicableScriptItems.Any())
                {
                    return;
                }

                using (var session = ScriptSessionManager.NewSession(ApplicationNames.Default, true))
                {
                    session.SetVariable("eventArgs", args);

                    if (item != null)
                    {
                        session.SetItemLocationContext(item);
                    }

                    foreach (var scriptItem in applicableScriptItems)
                    {
                        session.ExecuteScriptPart(scriptItem, true);
                    }
                }
            }
        }
        public void OnEvent(object sender, EventArgs args)
        {
            Item item      = null;
            var  eventName = EventArgToEventName(args);

            if (args is SitecoreEventArgs)
            {
                var scevent = (SitecoreEventArgs)args;
                item = scevent.Parameters[0] as Item;
            }

            if (String.IsNullOrEmpty(eventName))
            {
                return;
            }

            foreach (var root in ModuleManager.GetFeatureRoots(IntegrationPoints.EventHandlersFeature))
            {
                var libraryItem = root.Paths.GetSubItem(eventName);

                if (libraryItem == null)
                {
                    return;
                }

                using (var session = ScriptSessionManager.NewSession(ApplicationNames.Default, true))
                {
                    foreach (Item scriptItem in libraryItem.Children)
                    {
                        if (!scriptItem.IsPowerShellScript())
                        {
                            continue;
                        }
                        if (item != null)
                        {
                            session.SetItemLocationContext(item);
                        }
                        session.SetExecutedScript(scriptItem);
                        session.SetVariable("eventArgs", args);
                        var script = scriptItem[Templates.Script.Fields.ScriptBody];
                        if (!String.IsNullOrEmpty(script))
                        {
                            session.ExecuteScriptPart(script);
                        }
                    }
                }
            }
        }
Beispiel #15
0
 public void Update(Item[] items, CommandItem command, ScheduleItem schedule)
 {
     using (var session = ScriptSessionManager.NewSession(ApplicationNames.Default, true))
     {
         foreach (var item in items)
         {
             var script = item[ScriptItemFieldNames.Script];
             if (!String.IsNullOrEmpty(script))
             {
                 session.SetExecutedScript(item);
                 session.SetItemLocationContext(item);
                 session.ExecuteScriptPart(script);
             }
         }
     }
 }
Beispiel #16
0
        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>());
            }
        }
Beispiel #17
0
        public void Update(Item[] items, CommandItem command, ScheduleItem schedule)
        {
            using (var session = ScriptSessionManager.NewSession(ApplicationNames.Default, true))
            {
                foreach (var scriptItem in items.Where(si => si.IsPowerShellScript() && !string.IsNullOrWhiteSpace(si[Templates.Script.Fields.ScriptBody])))
                {
                    if (!RulesUtils.EvaluateRules(scriptItem[Templates.Script.Fields.EnableRule], scriptItem))
                    {
                        continue;
                    }

                    session.SetItemLocationContext(scriptItem);
                    session.ExecuteScriptPart(scriptItem, true);
                }
            }
        }
        /// <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
                });
            }
        }
Beispiel #19
0
        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();
                }
            }
        }
Beispiel #20
0
        public NameValue[] ExecuteScript(string userName, string password, string script, string returnVariables)
        {
            if (!WebServiceSettings.IsEnabled(WebServiceSettings.ServiceRemoting))
            {
                return(new NameValue[0]);
            }

            if (!Login(userName, password))
            {
                return(new[]
                {
                    new NameValue()
                    {
                        Name = "login failed", Value = "login failed"
                    }
                });
            }

            PowerShellLog.Info($"Script executed through remoting by user: '******' in disposable session.");

            using (var scriptSession = ScriptSessionManager.NewSession(ApplicationNames.RemoteAutomation, false))
            {
                scriptSession.ExecuteScriptPart(script);

                var result = new List <NameValue>();

                if (scriptSession.Output.Count > 0)
                {
                    result.Add(new NameValue
                    {
                        Name  = "output",
                        Value =
                            scriptSession.Output.Select(p => p.Terminated ? p.Text + "\n" : p.Text).Aggregate(
                                (current, next) => current + next)
                    });
                }
                result.AddRange(
                    returnVariables.Split('|').Select(variable => new NameValue
                {
                    Name  = variable,
                    Value = (scriptSession.GetVariable(variable) ?? string.Empty).ToString()
                }));
                return(result.ToArray());
            }
        }
Beispiel #21
0
        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);
            }
        }
Beispiel #22
0
        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>());
            }
        }
Beispiel #23
0
        protected void RunPlugin(ClientPipelineArgs args)
        {
            var scriptSession = ScriptSessionManager.NewSession(ApplicationNames.ISE, true);
            var scriptDb      = args.Parameters["scriptDb"];
            var scriptItem    = args.Parameters["scriptId"];
            var script        = Factory.GetDatabase(scriptDb).GetItem(scriptItem);

            if (!script.IsPowerShellScript())
            {
                return;
            }

            scriptSession.SetVariable("scriptText", Editor.Value);
            scriptSession.SetVariable("selectionText", SelectionText.Value.Trim());
            scriptSession.SetVariable("scriptItem", ScriptItem);
            scriptSession.Interactive = true;
            JobExecuteScript(args, script[Templates.Script.Fields.ScriptBody], scriptSession, true, false);
        }
Beispiel #24
0
        protected virtual void JobExecuteScript(ClientPipelineArgs args, string scriptToExecute, bool debug)
        {
            if (!RequestSessionElevationEx(args, ApplicationNames.ISE, SessionElevationManager.ExecuteAction))
            {
                return;
            }

            Debugging = debug;
            var sessionName = CurrentSessionId;

            if (string.Equals(sessionName, StringTokens.PersistentSessionId, StringComparison.OrdinalIgnoreCase))
            {
                var script = ScriptItem;
                sessionName = script != null ? script[Templates.Script.Fields.PersistentSessionId] : string.Empty;
            }

            var autoDispose   = string.IsNullOrEmpty(sessionName);
            var scriptSession = autoDispose
                ? ScriptSessionManager.NewSession(ApplicationNames.ISE, true)
                : ScriptSessionManager.GetSession(sessionName, ApplicationNames.ISE, true);

            if (debug)
            {
                scriptSession.DebugFile = FileUtil.MapPath(Settings.TempFolderPath) + "\\" +
                                          Path.GetFileNameWithoutExtension(Path.GetTempFileName()) +
                                          ".ps1";
                File.WriteAllText(scriptSession.DebugFile, scriptToExecute);
                if (!string.IsNullOrEmpty(Breakpoints.Value))
                {
                    var strBrPoints = (Breakpoints.Value ?? string.Empty).Split(',');
                    var bPoints     = strBrPoints.Select(int.Parse);
                    scriptSession.SetBreakpoints(bPoints);
                }
                scriptToExecute = scriptSession.DebugFile;
            }
            if (UseContext)
            {
                scriptSession.SetItemLocationContext(ContextItem);
            }

            scriptSession.Interactive = true;

            JobExecuteScript(args, scriptToExecute, scriptSession, autoDispose, debug);
        }
Beispiel #25
0
        private void Run(Item speScript, NameValueCollection parameters)
        {
            var script = speScript.Fields[FieldIDs.Script].Value ?? string.Empty;

            if (!string.IsNullOrEmpty(script))
            {
                Log.Info(string.Format("Sitecron: Powershell.ExecuteScript: Running Script: {0} {1}", speScript.Name, speScript.ID.ToString()), this);

                if (speScript.IsPowerShellScript())
                {
                    //reset session for each script otherwise the position of the items and env vars set by the previous script will be inherited by the subsequent scripts
                    using (var session = ScriptSessionManager.NewSession(ApplicationNames.Default, true))
                    {
                        //here we are passing the param collection to the script
                        var paramItems = parameters.AllKeys.SelectMany(parameters.GetValues, (k, v) => new { Key = k, Value = v });
                        foreach (var p in paramItems)
                        {
                            if (String.IsNullOrEmpty(p.Key))
                            {
                                continue;
                            }
                            if (String.IsNullOrEmpty(p.Value))
                            {
                                continue;
                            }

                            if (session.GetVariable(p.Key) == null)
                            {
                                session.SetVariable(p.Key, p.Value);
                            }
                        }

                        session.SetExecutedScript(speScript);
                        //session.SetItemLocationContext(speScript); //not needed anymore?
                        session.ExecuteScriptPart(script);
                    }
                }
            }
        }
        //This is where the PowerShell script is run. Its from SPE code.
        private void Run(Item speScript, NameValueCollection parameters, IJobExecutionContext context)
        {
            var script = speScript.Fields[SitecronConstants.PowerShellFieldIds.ScriptBody].Value ?? string.Empty;

            if (!string.IsNullOrEmpty(script))
            {
                Log.Info(string.Format("SiteCron: Powershell.ExecuteScript: Running Script: {0} {1}", speScript.Name, speScript.ID.ToString()), this);

                if (speScript.IsPowerShellScript())
                {
                    //reset session for each script otherwise the position of the items and env vars set by the previous script will be inherited by the subsequent scripts
                    using (var session = ScriptSessionManager.NewSession(ApplicationNames.Default, true))
                    {
                        //here we are passing the param collection to the script
                        var paramItems = parameters.AllKeys.SelectMany(parameters.GetValues, (k, v) => new { Key = k, Value = v });
                        foreach (var p in paramItems)
                        {
                            if (String.IsNullOrEmpty(p.Key))
                            {
                                continue;
                            }
                            if (String.IsNullOrEmpty(p.Value))
                            {
                                continue;
                            }

                            if (session.GetVariable(p.Key) == null)
                            {
                                session.SetVariable(p.Key, p.Value);
                            }
                        }

                        session.SetExecutedScript(speScript);
                        session.ExecuteScriptPart(script);
                        context.JobDetail.JobDataMap.Put(SitecronConstants.ParamNames.SitecronJobLogData, session.GetVariable(SitecronConstants.ParamNames.PSSitecronExecutionLog)); //get the PowerShell session variable to use for the Execution Report
                    }
                }
            }
        }
        public void OnEvent(object sender, EventArgs args)
        {
            var eventArgs = args as SitecoreEventArgs;

            if (eventArgs == null)
            {
                return;
            }
            var item      = eventArgs.Parameters[0] as Item;
            var eventName = eventArgs.EventName.Replace(':', '/');

            foreach (var root in ModuleManager.GetFeatureRoots(IntegrationPoints.EventHandlersFeature))
            {
                var libraryItem = root.Paths.GetSubItem(eventName);

                if (libraryItem == null)
                {
                    return;
                }
                using (var session = ScriptSessionManager.NewSession(ApplicationNames.Default, true))
                {
                    foreach (Item scriptItem in libraryItem.Children)
                    {
                        if (item != null)
                        {
                            session.SetItemLocationContext(item);
                        }
                        session.SetExecutedScript(scriptItem);
                        session.SetVariable("eventArgs", eventArgs);
                        var script = scriptItem[ScriptItemFieldNames.Script];
                        if (!String.IsNullOrEmpty(script))
                        {
                            session.ExecuteScriptPart(script);
                        }
                    }
                }
            }
        }
Beispiel #28
0
        protected virtual void ClientExecute(ClientPipelineArgs args)
        {
            using (var scriptSession = ScriptSessionManager.NewSession(ApplicationNames.IseConsole, 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();
                }
            }
        }
Beispiel #29
0
        protected void Execute(object sender, EventArgs e)
        {
            var script = this.Query.Text;

            if (string.IsNullOrEmpty(script))
            {
                this.ShowError("The PowerShell script is empty");
                return;
            }
            try
            {
                using (var session = ScriptSessionManager.NewSession(ApplicationNames.Default, false))
                {
                    session.ExecuteScriptPart(script, true);
                    Output.InnerHtml = $"<pre ID='ScriptResultCode'>{session.Output.ToHtml(false)}</pre>";
                }
            }
            catch (Exception ex)
            {
                this.ShowError(ex.Message);
                Log.Error("An error occured when using PowerShell page.", ex, this);
            }
        }
        private static void ProcessScript(HttpContext context, Item scriptItem, Dictionary <string, Stream> streams)
        {
            if (!scriptItem.IsPowerShellScript() || scriptItem?.Fields[Templates.Script.Fields.ScriptBody] == null)
            {
                HttpContext.Current.Response.StatusCode = 404;
                return;
            }

            using (var session = ScriptSessionManager.NewSession(ApplicationNames.Default, true))
            {
                var script = scriptItem[Templates.Script.Fields.ScriptBody];

                if (Context.Database != null)
                {
                    var item = Context.Database.GetRootItem();
                    if (item != null)
                    {
                        session.SetItemLocationContext(item);
                    }
                }
                session.SetExecutedScript(scriptItem);

                context.Response.ContentType = "text/plain";

                var scriptArguments = new Hashtable();

                foreach (var param in HttpContext.Current.Request.QueryString.AllKeys)
                {
                    var paramValue = HttpContext.Current.Request.QueryString[param];
                    if (string.IsNullOrEmpty(param))
                    {
                        continue;
                    }
                    if (string.IsNullOrEmpty(paramValue))
                    {
                        continue;
                    }

                    scriptArguments[param] = paramValue;
                }

                foreach (var param in HttpContext.Current.Request.Params.AllKeys)
                {
                    var paramValue = HttpContext.Current.Request.Params[param];
                    if (string.IsNullOrEmpty(param))
                    {
                        continue;
                    }
                    if (string.IsNullOrEmpty(paramValue))
                    {
                        continue;
                    }

                    if (session.GetVariable(param) == null)
                    {
                        session.SetVariable(param, paramValue);
                    }
                }

                session.SetVariable("requestStreams", streams);

                session.SetVariable("scriptArguments", scriptArguments);

                session.ExecuteScriptPart(script, true);

                context.Response.Write(session.Output.ToString());

                if (session.Output.HasErrors)
                {
                    context.Response.StatusCode        = 424;
                    context.Response.StatusDescription = "Method Failure";
                }
            }
        }