public byte[] DownloadFile(string userName, string password, string filePath, string database, string language)
        {
            if (!WebServiceSettings.ServiceEnabledRemoting)
            {
                return(new byte[0]);
            }

            try
            {
                if (!Login(userName, password))
                {
                    return(Encoding.ASCII.GetBytes("login failed"));
                }

                var dirName = (Path.GetDirectoryName(filePath) ?? string.Empty).Replace('\\', '/');
                if (!dirName.StartsWith(Constants.MediaLibraryPath))
                {
                    dirName = Constants.MediaLibraryPath + (dirName.StartsWith("/") ? dirName : "/" + dirName);
                }
                var itemname = dirName + "/" + Path.GetFileNameWithoutExtension(filePath);
                var db       = Factory.GetDatabase(database);
                var item     = (MediaItem)db.GetItem(itemname);
                using (var stream = item.GetMediaStream())
                {
                    var result = new byte[stream.Length];
                    stream.Read(result, 0, (int)stream.Length);
                    return(result);
                }
            }
            catch (Exception ex)
            {
                PowerShellLog.Error("Error during uploading file using PowerShell web service", ex);
                return(new byte[0]);
            }
        }
Beispiel #2
0
        private static void UpdateCache()
        {
            var functionCache = new List <FunctionCacheEntry>();
            var roots         = ModuleManager.GetFeatureRoots(IntegrationPoints.FunctionsFeature);

            foreach (var root in roots)
            {
                try
                {
                    // One does not simply Select... as modules can have more than Query.MaxItems
                    // We have to traverse the tree.
                    IEnumerable <Item> results = GetAllScriptChildren(root);
                    functionCache.AddRange(results.Select(p =>
                                                          new FunctionCacheEntry()
                    {
                        Name     = p.Name,
                        Library  = GetLibraryName(p.Parent, string.Empty),
                        Database = p.Database.Name,
                        Module   = GetModuleName(p.Parent),
                        ScriptID = p.ID
                    }));
                }
                catch (Exception ex)
                {
                    PowerShellLog.Error("Error while querying for items", ex);
                }
            }

            FunctionCache = functionCache;
            libraries     = null;
            functions     = null;
            modules       = null;
        }
Beispiel #3
0
        public static void DropSessionTokenElevation(string appName)
        {
            var token = GetToken(appName);

            HttpContext.Current.Session.Remove(string.Format(SessionCacheToken, token?.Name));
            PowerShellLog.Warn($"Session state elevation dropped for '{appName}' by user: {Sitecore.Context.User?.Name}");
        }
Beispiel #4
0
        public static void ElevateSessionToken(string appName)
        {
            var token = GetToken(appName);

            PowerShellLog.Warn($"Session state elevated for '{appName}' by user: {Sitecore.Context.User?.Name}");
            HttpContext.Current.Session[string.Format(SessionCacheToken, token?.Name)] = DateTime.Now + token.Expiration;
        }
        internal List <object> ExecuteScriptPart(string script, bool stringOutput, bool internalScript,
                                                 bool marshalResults)
        {
            if (string.IsNullOrWhiteSpace(script) || State == RunspaceAvailability.Busy)
            {
                return(null);
            }

            if (Runspace.DefaultRunspace == null)
            {
                Runspace.DefaultRunspace = host.Runspace;
            }

            PowerShellLog.Info($"Executing a script in ScriptSession '{Key}'.");
            PowerShellLog.Debug(script);

            // Create a pipeline, and populate it with the script given in the
            // edit box of the form.
            return(SpeTimer.Measure($"script execution in ScriptSession '{Key}'", () =>
            {
                try
                {
                    using (powerShell = NewPowerShell())
                    {
                        powerShell.Commands.AddScript(script);
                        return ExecuteCommand(stringOutput, marshalResults);
                    }
                }
                finally
                {
                    powerShell = null;
                }
            }));
        }
        static SpeSitecorePowerShellSnapIn()
        {
            var commandsToIncludes = Factory.GetConfigNodes("powershell/commandlets/add");

            foreach (XmlElement commandToInclude in commandsToIncludes)
            {
                var commandTypeDef = commandToInclude.Attributes["type"].Value.Split(',');
                var cmdletType     = commandTypeDef[0];
                var cmdletAssembly = commandTypeDef[1];
                var wildcard       = GetWildcardPattern(cmdletType);
                try
                {
                    var assembly = Assembly.Load(cmdletAssembly);
                    GetCommandletsFromAssembly(assembly, wildcard);
                }
                catch (ReflectionTypeLoadException typeLoadException)
                {
                    var loaderExceptions = typeLoadException.LoaderExceptions;
                    var message          = loaderExceptions.Aggregate(string.Empty, (current, exc) => current + exc.Message);
                    PowerShellLog.Error($"Error while loading commands from assembly {cmdletAssembly} list: {message}",
                                        typeLoadException);
                }
                catch (Exception ex)
                {
                    PowerShellLog.Error($"Error while loading commands from assembly {cmdletAssembly} list: {ex.Message}",
                                        ex);
                }
            }
        }
        private static List <AuthorizationEntry> GetServiceAuthorizationInfo(string serviceName)
        {
            if (authorizationEntries.ContainsKey(serviceName))
            {
                return(authorizationEntries[serviceName]);
            }

            var authEntryList = new List <AuthorizationEntry>();

            authorizationEntries.Add(serviceName, authEntryList);

            var servicesNode =
                Factory.GetConfigNode($"powershell/services/{serviceName}/authorization");

            if (servicesNode != null)
            {
                foreach (XmlNode node in servicesNode.ChildNodes)
                {
                    AuthorizationEntry entry;
                    if (node.Name.Is("#comment"))
                    {
                        continue;
                    }
                    if (AuthorizationEntry.TryParse(node, out entry))
                    {
                        authEntryList.Add(entry);
                    }
                    else
                    {
                        PowerShellLog.Error($"Invalid permission entry for service '{serviceName}'");
                    }
                }
            }
            return(authEntryList);
        }
Beispiel #8
0
        private bool Login(string userName, string password)
        {
            if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password))
            {
                PowerShellLog.Info($"User '{userName}' calling the Remoting Automation service.");

                if (!userName.Contains("\\"))
                {
                    userName = "******" + userName;
                }

                if (!ServiceAuthorizationManager.IsUserAuthorized(WebServiceSettings.ServiceRemoting, userName))
                {
                    PowerShellLog.Error($"User `{userName}` tried to access the service but was not permitted to do so.");
                    return(false);
                }

                var loggedIn = AuthenticationManager.Login(userName, password, false);
                if (!loggedIn)
                {
                    PowerShellLog.Error($"User '{userName}' was not recognized or provided wrong password.");
                }
                else
                {
                    PowerShellLog.Info($"User '{userName}' successfully logged in to the Remoting Automation service.");
                }
                return(loggedIn);
            }
            PowerShellLog.Info($"Unsuccessfuly login with empty username or password. Username: '******'.");
            return(false);
        }
        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)
                }));
            }
        }
Beispiel #10
0
        protected override Collection <PSDriveInfo> InitializeDefaultDrives()
        {
            var result = new Collection <PSDriveInfo>();
            var i      = 0;

            foreach (var database in Factory.GetDatabases().Where(db => !db.ReadOnly))
            {
                i++;
                var dbName = database?.Name ?? $"sitecore{i}";
                try
                {
                    var drive = new PSDriveInfo(dbName,
                                                providerInfo,
                                                dbName + ":",
                                                $"Sitecore '{dbName}' database.",
                                                PSCredential.Empty);
                    result.Add(drive);
                }
                catch (Exception ex)
                {
                    PowerShellLog.Error($"Error while adding PowerShell drive for database {dbName}", ex);
                }
            }
            return(result);
        }
Beispiel #11
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)
                            ;
                        }
                    }
                }
            }
        }
Beispiel #12
0
 protected override void OnOK(object sender, EventArgs args)
 {
     Assert.ArgumentNotNull(sender, "sender");
     Assert.ArgumentNotNull(args, "args");
     if (!string.IsNullOrEmpty(ItemUri))
     {
         var item = Factory.GetDatabase(ItemDb).GetItem(new DataUri(ItemUri));
         if (MediaManager.HasMediaContent(item))
         {
             var str = item.Uri.ToUrlString(string.Empty);
             str.Append("field", "Blob");
             Files.Download(str.ToString());
             PowerShellLog.Audit("Download file: {0}", str.ToString());
         }
         else
         {
             SheerResponse.Alert("There is no file attached.");
         }
     }
     else if (!string.IsNullOrEmpty(FileName))
     {
         SheerResponse.Download(FileName);
         Hidden.Value = "downloaded";
     }
     Hidden.Value = "downloaded";
     Context.ClientPage.ClientResponse.SetDialogValue(Hidden.Value);
     //base.OnCancel(sender, args);
 }
        private void WriteToLog(string message, LogLevel level)
        {
            if (!IsOutputLoggingEnabled)
            {
                return;
            }

            switch (level)
            {
            case LogLevel.Debug:
                PowerShellLog.Debug(message);
                break;

            case LogLevel.Error:
                PowerShellLog.Error(message);
                break;

            case LogLevel.Info:
            case LogLevel.Verbose:
                PowerShellLog.Info(message);
                break;

            case LogLevel.Warning:
                PowerShellLog.Warn(message);
                break;
            }
        }
        private static bool CheckServiceAuthentication(HttpContext context, string apiVersion, string serviceName, bool isAuthenticated)
        {
            var skipAuthentication = false;

            switch (apiVersion)
            {
            case "1":
            case "2":
                skipAuthentication = true;
                break;

            default:
                if (!isAuthenticated)
                {
                    const string disabledMessage =
                        "The request could not be completed because the service requires authentication.";

                    context.Response.StatusCode        = 401;
                    context.Response.StatusDescription = disabledMessage;
                    context.Response.SuppressFormsAuthenticationRedirect = true;
                    PowerShellLog.Error($"Attempt to call the {serviceName} service failed as - user not logged in, authentication failed, or no credentials provided.");
                }

                break;
            }

            return(skipAuthentication || isAuthenticated);
        }
Beispiel #15
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 object GetAutoCompletionPrefix(string guid, string command)
        {
            if (!IsLoggedInUserAuthorized ||
                !SessionElevationManager.IsSessionTokenElevated(ApplicationNames.ISE))
            {
                return(string.Empty);
            }

            PowerShellLog.Info($"Auto completion requested in session '{guid}' by user: '******'");

            var serializer = new JavaScriptSerializer();
            var session    = GetScriptSession(guid);

            try
            {
                var result = serializer.Serialize(CommandCompletion.GetPrefix(session, command));
                return(result);
            }
            finally
            {
                if (string.IsNullOrEmpty(guid))
                {
                    ScriptSessionManager.RemoveSession(session);
                }
            }
        }
 private void BuildCache(IEnumerable <Item> roots)
 {
     foreach (var root in roots)
     {
         var path     = PathUtilities.PreparePathForQuery(root.Paths.Path);
         var rootPath = root.Paths.Path;
         var query    = $"{path}//*[@@TemplateId=\"{Templates.Script.Id}\"]";
         try
         {
             var results = root.Database.SelectItems(query);
             foreach (var result in results)
             {
                 var scriptPath = result.Paths.Path.Substring(rootPath.Length);
                 var dbName     = result.Database.Name;
                 if (!apiScripts.ContainsKey(dbName))
                 {
                     apiScripts.Add(dbName, new SortedDictionary <string, ApiScript>(StringComparer.OrdinalIgnoreCase));
                 }
                 apiScripts[dbName].Add(scriptPath, new ApiScript
                 {
                     Database = result.Database.Name,
                     Id       = result.ID,
                     Path     = scriptPath
                 });
             }
         }
         catch (Exception ex)
         {
             PowerShellLog.Error("Error while querying for items", ex);
         }
     }
 }
        private static void UpdateCache()
        {
            var localFunctions = new List <string>();
            var roots          = ModuleManager.GetFeatureRoots(IntegrationPoints.FunctionsFeature);

            modules =
                (from module in ModuleManager.Modules where module.Enabled select module.Name).ToList()
                .ConvertAll(WrapNameWithSpacesInQuotes)
                .ToArray();

            libraries = (from root in roots
                         from Item library in root.GetChildren()
                         where library.IsPowerShellLibrary()
                         select library.Name).ToList().ConvertAll(WrapNameWithSpacesInQuotes).ToArray();

            foreach (var root in roots)
            {
                var path  = PathUtilities.PreparePathForQuery(root.Paths.Path);
                var query = string.Format(
                    "{0}//*[@@TemplateId=\"{{DD22F1B3-BD87-4DB2-9E7D-F7A496888D43}}\"]",
                    path);
                try
                {
                    var results = root.Database.SelectItems(query);
                    localFunctions.AddRange(
                        results.ToList().ConvertAll(p => WrapNameWithSpacesInQuotes(p.Name)));
                }
                catch (Exception ex)
                {
                    PowerShellLog.Error("Error while querying for items", ex);
                }
            }
            functions = localFunctions.ToArray();
        }
Beispiel #19
0
        protected override void OnLoad(EventArgs e)
        {
            if (!SecurityHelper.CanRunApplication("PowerShell/PowerShell Console") ||
                ServiceAuthorizationManager.TerminateUnauthorizedRequest(WebServiceSettings.ServiceClient,
                                                                         Context.User?.Name))
            {
                PowerShellLog.Error($"User {Context.User?.Name} attempt to access PowerShell Console - denied.");
                return;
            }
            base.OnLoad(e);

            UpdateWarning();

            Settings = ApplicationSettings.GetInstance(ApplicationNames.Context, false);
            HttpContext.Current.Response.AddHeader("X-UA-Compatible", "IE=edge");
            var settings = ApplicationSettings.GetInstance(ApplicationNames.Console, false);

            if (!Context.ClientPage.IsEvent)
            {
                Options.Text = @"<script type='text/javascript'>" +
                               @"$ise(function() { cognifide.powershell.setOptions({ initialPoll: " +
                               WebServiceSettings.InitialPollMillis + @", maxPoll: " +
                               WebServiceSettings.MaxmimumPollMillis + @", fontSize: " +
                               settings.FontSize + $", fontFamily: '{settings.FontFamilyStyle}' }});}});</script>" +
                               @"<style>#terminal {" +
                               $"color: {OutputLine.ProcessHtmlColor(settings.ForegroundColor)};" +
                               $"background-color: {OutputLine.ProcessHtmlColor(settings.BackgroundColor)};" +
                               $"font-family: inherit;" + "}</style>";
            }
            SheerResponse.SetDialogValue("ok");
        }
        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);
                        }
                    }
                }
            }
        }
Beispiel #21
0
        private void LogString(string message)
        {
            switch (Log)
            {
            case LogNotificationLevel.Debug:
                PowerShellLog.Debug(message);
                break;

            case LogNotificationLevel.Error:
                PowerShellLog.Error(message);
                break;

            case LogNotificationLevel.Fatal:
                PowerShellLog.Fatal(message);
                break;

            case LogNotificationLevel.Warning:
                PowerShellLog.Warn(message);
                break;

            default:
                PowerShellLog.Info(message);
                break;
            }

            WriteVerbose(message);
        }
Beispiel #22
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);
                        }
                    }
                }
            }
        }
        // We override the GetIconDescriptor so a script can be called in it's place.
        protected override GutterIconDescriptor GetIconDescriptor(Item item)
        {
            return(SpeTimer.Measure("gutter script execution", true, () =>
            {
                // The scriptId parameter is configured when we create a new gutter
                // here /sitecore/content/Applications/Content Editor/Gutters
                if (!Parameters.ContainsKey("scriptId"))
                {
                    return null;
                }

                var scriptId = new ID(Parameters["scriptId"]);
                var scriptDb = string.IsNullOrEmpty(Parameters["scriptDb"])
                    ? ApplicationSettings.ScriptLibraryDb
                    : Parameters["scriptId"];

                var db = Factory.GetDatabase(scriptDb);
                var scriptItem = db.GetItem(scriptId);

                // If a script is configured but does not exist or is of a wrong template then do nothing.
                if (scriptItem == null || !scriptItem.IsPowerShellScript() ||
                    string.IsNullOrWhiteSpace(scriptItem[Templates.Script.Fields.ScriptBody]) ||
                    !RulesUtils.EvaluateRules(scriptItem[Templates.Script.Fields.EnableRule], item))
                {
                    return null;
                }

                var featureRoot = ModuleManager.GetItemModule(scriptItem)?
                                  .GetFeatureRoot(IntegrationPoints.ContentEditorGuttersFeature);
                if (!RulesUtils.EvaluateRules(featureRoot?[Templates.ScriptLibrary.Fields.EnableRule], item))
                {
                    return null;
                }

                try
                {
                    // Create a new session for running the script.
                    var session = ScriptSessionManager.GetSession(scriptItem[Templates.Script.Fields.PersistentSessionId],
                                                                  IntegrationPoints.ContentEditorGuttersFeature);

                    // We will need the item variable in the script.
                    session.SetItemLocationContext(item);

                    // Any objects written to the pipeline in the script will be returned.
                    var output = session.ExecuteScriptPart(scriptItem, false);
                    foreach (var result in output)
                    {
                        if (result.GetType() == typeof(GutterIconDescriptor))
                        {
                            return (GutterIconDescriptor)result;
                        }
                    }
                }
                catch (Exception ex)
                {
                    PowerShellLog.Error($"Error while invoking script '{scriptItem?.Paths.Path}' for rendering in Content Editor gutter.", ex);
                }
                return null;
            }));
        }
        // Methods
        protected override bool Execute(T ruleContext)
        {
            Assert.ArgumentNotNull(ruleContext, "ruleContext");

            var    measuredLength = MeasuredLengths[MeasuredLength];
            string lengthStr;

            if (measuredLength == Measured.Script)
            {
                lengthStr = ruleContext.Parameters["scriptLength"].ToString();
            }
            else
            {
                lengthStr = ruleContext.Parameters["selectionLength"].ToString();
            }

            if (string.IsNullOrEmpty(lengthStr))
            {
                return(false);
            }

            int length;

            if (!int.TryParse(lengthStr, out length))
            {
                PowerShellLog.Debug("Invalid script length: " + MeasuredLength);
                return(false);
            }

            int desiredLength;

            if (!int.TryParse(DesiredLength, out desiredLength))
            {
                PowerShellLog.Debug("Wrong script length definition: " + DesiredLength);
                return(false);
            }

            switch (GetOperator())
            {
            case ConditionOperator.Equal:
                return(length == desiredLength);

            case ConditionOperator.GreaterThanOrEqual:
                return(length >= desiredLength);

            case ConditionOperator.GreaterThan:
                return(length > desiredLength);

            case ConditionOperator.LessThanOrEqual:
                return(length <= desiredLength);

            case ConditionOperator.LessThan:
                return(length < desiredLength);

            case ConditionOperator.NotEqual:
                return(length >= desiredLength);
            }
            return(false);
        }
        // We override the GetIconDescriptor so a script can be called in it's place.
        protected override GutterIconDescriptor GetIconDescriptor(Item item)
        {
            return(SpeTimer.Measure("gutter script execution", () =>
            {
                // The scriptId parameter is configured when we create a new gutter
                // here /sitecore/content/Applications/Content Editor/Gutters
                if (!Parameters.ContainsKey("scriptId"))
                {
                    return null;
                }

                var scriptId = new ID(Parameters["scriptId"]);
                var scriptDb = string.IsNullOrEmpty(Parameters["scriptDb"])
                    ? ApplicationSettings.ScriptLibraryDb
                    : Parameters["scriptId"];

                var db = Factory.GetDatabase(scriptDb);
                var scriptItem = db.GetItem(scriptId);

                // If a script is configured but does not exist then return.
                if (scriptItem == null)
                {
                    return null;
                }

                try
                {
                    // Create a new session for running the script.
                    var session = ScriptSessionManager.GetSession(scriptItem[ScriptItemFieldNames.PersistentSessionId],
                                                                  IntegrationPoints.ContentEditorGuttersFeature);

                    var script = (scriptItem.Fields[ScriptItemFieldNames.Script] != null)
                        ? scriptItem.Fields[ScriptItemFieldNames.Script].Value
                        : string.Empty;

                    // We will need the item variable in the script.
                    session.SetItemLocationContext(item);

                    //let the session know which script is being executed
                    session.SetExecutedScript(scriptItem);

                    // Any objects written to the pipeline in the script will be returned.
                    var output = session.ExecuteScriptPart(script, false);
                    foreach (var result in output)
                    {
                        if (result.GetType() == typeof(GutterIconDescriptor))
                        {
                            return (GutterIconDescriptor)result;
                        }
                    }
                }
                catch (Exception ex)
                {
                    PowerShellLog.Error($"Error while invoking script '{scriptItem?.Paths.Path}' for rendering in Content Editor gutter.", ex);
                }
                return null;
            }));
        }
        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();
            }
        }
Beispiel #27
0
        /// <summary>
        ///     Not implemented by this example class. The call fails with
        ///     a NotImplementedException exception.
        /// </summary>
        public override void EnterNestedPrompt()
        {
            NestedLevel++;
            UiNestedLevel++;
            var resultSig = Guid.NewGuid().ToString();

            var str = new UrlString(UIUtil.GetUri("control:PowerShellConsole"));

            str.Add("sid", resultSig);
            str.Add("fc", privateData.ForegroundColor.ToString());
            str.Add("bc", privateData.BackgroundColor.ToString());
            str.Add("id", SessionKey);
            str.Add("suspend", "true");

            var currentNesting = NestedLevel;
            var jobManager     = TypeResolver.ResolveFromCache <IJobManager>();
            var job            = jobManager.GetContextJob();

            job.MessageQueue.PutMessage(
                new ShowSuspendDialogMessage(SessionKey, str.ToString(), "900", "600", new Hashtable())
            {
                ReceiveResults = true,
            });

            var scriptSession = ScriptSessionManager.GetSession(SessionKey);

            while (currentNesting <= UiNestedLevel)
            {
                if (currentNesting == UiNestedLevel)
                {
                    if (scriptSession.ImmediateCommand is string commandString)
                    {
                        scriptSession.ImmediateCommand = null;
                        PowerShellLog.Info($"Executing a command in ScriptSession '{SessionKey}'.");
                        PowerShellLog.Debug(commandString);
                        try
                        {
                            var result =
                                scriptSession.InvokeInNewPowerShell(commandString, ScriptSession.OutTarget.OutHost);
                        }
                        catch (Exception ex)
                        {
                            PowerShellLog.Error("Error while executing Debugging command.", ex);
                            UI.WriteErrorLine(ScriptSession.GetExceptionString(ex));
                        }
                    }
                    else
                    {
                        Thread.Sleep(20);
                    }
                }
            }
            job.MessageQueue.GetResult();

            ScriptSessionManager.GetSession(SessionKey).InvokeInNewPowerShell("exit", ScriptSession.OutTarget.OutHost);
        }
        private static bool CheckServiceEnabled(HttpContext context, string apiVersion, string httpMethod)
        {
            bool isEnabled;

            switch (apiVersion)
            {
            case "1":
                isEnabled = WebServiceSettings.IsEnabled(WebServiceSettings.ServiceRestfulv1);
                break;

            case "2":
                isEnabled = WebServiceSettings.IsEnabled(WebServiceSettings.ServiceRestfulv2);
                break;

            case "file":
                isEnabled = (WebServiceSettings.IsEnabled(WebServiceSettings.ServiceFileUpload) &&
                             httpMethod.Is("POST")) ||
                            (WebServiceSettings.IsEnabled(WebServiceSettings.ServiceFileDownload) &&
                             httpMethod.Is("GET"));
                break;

            case "media":
                isEnabled = ((WebServiceSettings.IsEnabled(WebServiceSettings.ServiceMediaUpload) &&
                              httpMethod.Is("POST")) ||
                             (WebServiceSettings.IsEnabled(WebServiceSettings.ServiceMediaDownload) &&
                              httpMethod.Is("GET")));
                break;

            case "handle":
                isEnabled = WebServiceSettings.IsEnabled(WebServiceSettings.ServiceHandleDownload);
                break;

            case "script":
                isEnabled = WebServiceSettings.IsEnabled(WebServiceSettings.ServiceRemoting);
                break;

            default:
                isEnabled = false;
                break;
            }

            if (isEnabled)
            {
                return(true);
            }

            const string disabledMessage = "The request could not be completed because the service is disabled.";

            context.Response.StatusCode        = 403;
            context.Response.StatusDescription = disabledMessage;
            PowerShellLog.Error($"Attempt to call the {apiVersion} service failed as it is not enabled.");

            return(false);
        }
Beispiel #29
0
 public void SetExecutedScript(Item scriptItem)
 {
     if (scriptItem != null)
     {
         var scriptPath = scriptItem.GetProviderPath();
         PowerShellLog.Info($"Script item set to {scriptPath} in ScriptSession {Key}.");
         SetVariable("SitecoreScriptRoot", scriptItem.Parent.GetProviderPath());
         SetVariable("SitecoreCommandPath", scriptPath);
         SetVariable("PSScript", scriptItem);
     }
 }
        protected virtual void WriteError(Exception exception, ErrorIds errorIds, ErrorCategory errorCategory, object targetObject, bool throwTerminatingError = false)
        {
            var record = new ErrorRecord(exception, errorIds.ToString(), errorCategory, targetObject);

            PowerShellLog.Error($"'{errorIds}' (Category: {errorCategory}) error encountered on object. ", exception);
            if (throwTerminatingError)
            {
                ThrowTerminatingError(record);
            }
            WriteError(record);
        }