Esempio n. 1
1
 public static IEnumerable<string> GetHelp(ScriptSession session, string command)
 {
     Collection<PSParseError> errors;
     var tokens = PSParser.Tokenize(command, out errors);
     var lastPsToken = tokens.LastOrDefault(t => t.Type == PSTokenType.Command);
     if (lastPsToken != null)
     {
         session.Output.Clear();
         var lastToken = lastPsToken.Content;
         session.SetVariable("helpFor", lastToken);
         var platformmodule = ModuleManager.GetModule("Platform");
         var scriptItem = Database.GetDatabase(platformmodule.Database)
             .GetItem(platformmodule.Path + "/Internal/Context Help/Command Help");
         if (scriptItem == null)
         {
             scriptItem = Factory.GetDatabase(ApplicationSettings.ScriptLibraryDb)
                 .GetItem(ApplicationSettings.ScriptLibraryPath + "Internal/Context Help/Command Help");
         }
         session.ExecuteScriptPart(scriptItem[ScriptItemFieldNames.Script], true, true);
         var sb = new StringBuilder("<div id=\"HelpClose\">X</div>");
         if (session.Output.Count == 0 || session.Output[0].LineType == OutputLineType.Error)
         {
             return new[]
             {
                 "<div class='ps-help-command-name'>&nbsp;</div><div class='ps-help-header' align='center'>No Command in line or help information found</div><div class='ps-help-parameter' align='center'>Cannot provide help in this context.</div>"
             };
         }
         session.Output.ForEach(l => sb.Append(l.Text));
         session.Output.Clear();
         var result = new[] {sb.ToString()};
         return result;
     }
     return new[] {"No Command in line found - cannot provide help in this context."};
 }
Esempio n. 2
0
        public static string GetPrefix(ScriptSession session, string command)
        {
            string lastToken;

            TruncatedCommand(session, command, out lastToken);
            return(string.IsNullOrEmpty(lastToken) ? string.Empty : lastToken);
        }
Esempio n. 3
0
        public static ScriptSession GetSession(string persistentId, string applianceType, bool personalizedSettings)
        {
            // sessions with no persistent ID, are just created new every time
            var autoDispose = string.IsNullOrEmpty(persistentId);
            if (autoDispose)
            {
                persistentId = Guid.NewGuid().ToString();
            }

            var sessionKey = GetSessionKey(persistentId);
            lock (sessions)
            {
                if (SessionExists(persistentId))
                {
                    return HttpRuntime.Cache[sessionKey] as ScriptSession;
                }

                var session = new ScriptSession(applianceType, personalizedSettings)
                {
                    ID = persistentId,
                    AutoDispose = autoDispose
                };
                var expiration = Sitecore.Configuration.Settings.GetIntSetting(expirationSetting, 30);
                HttpRuntime.Cache.Add(sessionKey, session, null, Cache.NoAbsoluteExpiration,
                    new TimeSpan(0, expiration, 0), CacheItemPriority.Normal, CacheItemRemoved);
                sessions.Add(sessionKey);
                session.ID = persistentId;
                session.Key = sessionKey;
                session.Initialize();
                return session;
            }
        }
Esempio n. 4
0
        public static IEnumerable<string> FindMatches2(ScriptSession session, string command, bool aceResponse)
        {
            string lastToken;
            var truncatedCommand = TruncatedCommand2(command, out lastToken);

            var teCmd = new Command("TabExpansion");
            teCmd.Parameters.Add("line", command);
            teCmd.Parameters.Add("lastWord", lastToken);
            var teResult = session.ExecuteCommand(teCmd, false, true).Cast<string>();

            var result = new List<string>();
            WrapResults(truncatedCommand, teResult, result, aceResponse);

            var splitPathResult =
                (session.ExecuteScriptPart(string.Format("Split-Path \"{0}*\" -IsAbsolute", lastToken), false, true)
                    .FirstOrDefault());
            var isAbsolute = splitPathResult != null && (bool) splitPathResult;

            if (isAbsolute)
            {
                var commandLine = string.Format("Resolve-Path \"{0}*\"", lastToken);
                var psResults = session.ExecuteScriptPart(commandLine, false, true);
                var rpResult = psResults.Cast<PathInfo>().Select(p => p.Path);
                WrapResults(truncatedCommand, rpResult, result, aceResponse);
            }
            else
            {
                var commandLine = string.Format("Resolve-Path \"{0}*\" -Relative", lastToken);
                var rpResult = session.ExecuteScriptPart(commandLine, false, true).Cast<string>();
                WrapResults(truncatedCommand, rpResult, result, aceResponse);
            }

            return result;
        }
        protected override void ProcessSession(ScriptSession session)
        {
            if (!ShouldProcess(session.ID, "Receive results from existing script session")) return;

            if (session.State == RunspaceAvailability.Busy)
            {
                WriteError(typeof (CmdletInvocationException),
                    $"The script session with Id '{session.ID}' cannot be received because it is in the Busy state. Use Stop-ScriptSession or wait for the operation to complete.",
                    ErrorIds.ScriptSessionBusy,
                    ErrorCategory.ResourceBusy, session.ID);
                return;
            }

            if (HostOutput)
            {
                WriteObject(session.Output.ToString());
            }
            else
            {
                WriteObject(session.JobResultsStore);
            }

            if (KeepResult) return;
            session.JobResultsStore = null;

            if (KeepSession) return;
            ScriptSessionManager.RemoveSession(session);
        }
Esempio n. 6
0
        public static IEnumerable <string> GetHelp(ScriptSession session, string command)
        {
            Collection <PSParseError> errors;
            var tokens      = PSParser.Tokenize(command, out errors);
            var lastPsToken = tokens.LastOrDefault(t => t.Type == PSTokenType.Command);

            if (lastPsToken != null)
            {
                session.Output.Clear();
                var lastToken = lastPsToken.Content;
                session.SetVariable("helpFor", lastToken);
                var platformmodule = ModuleManager.GetModule("Platform");
                var scriptItem     = Database.GetDatabase(platformmodule.Database)
                                     .GetItem(platformmodule.Path + "/Internal/Context Help/Command Help");
                if (scriptItem == null)
                {
                    scriptItem = Factory.GetDatabase(ApplicationSettings.ScriptLibraryDb)
                                 .GetItem(ApplicationSettings.ScriptLibraryPath + "Internal/Context Help/Command Help");
                }
                session.ExecuteScriptPart(scriptItem[ScriptItemFieldNames.Script], true, true);
                var sb = new StringBuilder("<div id=\"HelpClose\">X</div>");
                if (session.Output.Count == 0 || session.Output[0].LineType == OutputLineType.Error)
                {
                    return(new[]
                    {
                        "<div class='ps-help-command-name'>&nbsp;</div><div class='ps-help-header' align='center'>No Command in line or help information found</div><div class='ps-help-parameter' align='center'>Cannot provide help in this context.</div>"
                    });
                }
                session.Output.ForEach(l => sb.Append(l.Text));
                session.Output.Clear();
                var result = new[] { sb.ToString() };
                return(result);
            }
            return(new[] { "No Command in line found - cannot provide help in this context." });
        }
Esempio n. 7
0
 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;
 }
Esempio n. 8
0
 public static IEnumerable<string> FindMatches(ScriptSession session, string command, bool aceResponse)
 {
     switch (ScriptSession.PsVersion.Major)
     {
         case (1):
         case (2):
             return FindMatches2(session, command, aceResponse);
         default:
             return FindMatches3(session, command, aceResponse);
     }
 }
Esempio n. 9
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;

            JobContext.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);
                    }
                }
            }
            JobContext.MessageQueue.GetResult();

            ScriptSessionManager.GetSession(SessionKey).InvokeInNewPowerShell("exit", ScriptSession.OutTarget.OutHost);
        }
Esempio n. 10
0
        public static IEnumerable <string> FindMatches(ScriptSession session, string command, bool aceResponse)
        {
            switch (ScriptSession.PsVersion.Major)
            {
            case (1):
            case (2):
                return(FindMatches2(session, command, aceResponse));

            default:
                return(FindMatches3(session, command, aceResponse));
            }
        }
Esempio n. 11
0
        public static IEnumerable<string> FindMatches3(ScriptSession session, string command, bool aceResponse)
        {
            string lastToken;
            var truncatedCommand = TruncatedCommand3(session, command, out lastToken);
            Hashtable options = null;//session.GetVariable("options") as Hashtable;
            Hashtable completers = null;
            if (options == null)
            {
                options = new Hashtable(1);
            }

            if (options.ContainsKey("CustomArgumentCompleters"))
            {
                completers = options["CustomArgumentCompleters"] as Hashtable;
            }
            if (completers == null)
            {
                completers = new Hashtable(CognifideSitecorePowerShellSnapIn.Completers.Count);
                options.Add("CustomArgumentCompleters", completers);
            }

            foreach (var completer in CognifideSitecorePowerShellSnapIn.Completers)
            {
                if (!completers.ContainsKey(completer.Key))
                {
                    completers.Add(completer.Key,
                        session.GetScriptBlock(
                            "param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter) \r\n " +
                            completer.Value +
                             " | ForEach-Object { New-Object System.Management.Automation.CompletionResult $_, $_, 'ParameterValue', $_ }"
                         ));
                }
            }
            session.SetVariable("options",options);

            const string TabExpansionHelper =
                @"function ScPsTabExpansionHelper( [string] $inputScript, [int]$cursorColumn ){ TabExpansion2 $inputScript $cursorColumn -Options $options |% { $_.CompletionMatches } |% { ""$($_.ResultType)|$($_.CompletionText)"" } }";
            session.ExecuteScriptPart(TabExpansionHelper);

            var teCmd = new Command("ScPsTabExpansionHelper");
            teCmd.Parameters.Add("inputScript", command);
            teCmd.Parameters.Add("cursorColumn", command.Length);
            teCmd.Parameters.Add("options", options);

            var teResult = session.ExecuteCommand(teCmd, false, true).Cast<string>().ToArray();
            var result = new List<string>();

            WrapResults3(truncatedCommand, teResult, result, aceResponse);
            return result;
        }
Esempio n. 12
0
        public static IEnumerable<string> FindMatches3(ScriptSession session, string command, bool aceResponse)
        {
            string lastToken;
            var truncatedCommand = TruncatedCommand3(session, command, out lastToken);
            Hashtable completers = null;
            var options = new Hashtable(1);

            if (options.ContainsKey("CustomArgumentCompleters"))
            {
                completers = options["CustomArgumentCompleters"] as Hashtable;
            }
            if (completers == null)
            {
                completers = new Hashtable(CognifideSitecorePowerShellSnapIn.Completers.Count);
                options.Add("CustomArgumentCompleters", completers);
            }

            foreach (var miscCompleter in MiscAutocompleteSets.Completers)
            {
                AddCompleter(session, completers, miscCompleter);
            }
            foreach (var completer in CognifideSitecorePowerShellSnapIn.Completers)
            {
                AddCompleter(session, completers, completer);
            }

            const string TabExpansionHelper =
                @"function ScPsTabExpansionHelper( [string] $inputScript, [int]$cursorColumn , $options){ TabExpansion2 $inputScript $cursorColumn -Options $options |% { $_.CompletionMatches } |% { ""$($_.ResultType)|$($_.CompletionText)"" } }";

            session.TryInvokeInRunningSession(TabExpansionHelper);

            var teCmd = new Command("ScPsTabExpansionHelper");
            teCmd.Parameters.Add("inputScript", command);
            teCmd.Parameters.Add("cursorColumn", command.Length);
            teCmd.Parameters.Add("options", options);

            string[] teResult = new string[0];

            List<object> results;
            if (session.TryInvokeInRunningSession(teCmd, out results, true))
            {
                teResult = results.Cast<string>().ToArray();
            }
            var result = new List<string>();

            WrapResults3(truncatedCommand, teResult, result, aceResponse);
            return result;
        }
Esempio n. 13
0
        private static void TruncatedCommand(ScriptSession session, string command, out string lastToken)
        {
            {
                switch (ScriptSession.PsVersion.Major)
                {
                case (1):
                case (2):
                    TruncatedCommand2(command, out lastToken);
                    break;

                default:
                    TruncatedCommand3(session, command, out lastToken);
                    break;
                }
            }
        }
Esempio n. 14
0
        public static IEnumerable<string> FindMatches(ScriptSession session, string command, bool aceResponse)
        {
            if (_powerShellVersionMajor == 0)
            {
                _powerShellVersionMajor =
                    (int) session.ExecuteScriptPart("$PSVersionTable.PSVersion.Major", false, true)[0];
            }

            switch (_powerShellVersionMajor)
            {
                case (1):
                case (2):
                    return FindMatches2(session, command, aceResponse);
                default:
                    return FindMatches3(session, command, aceResponse);
            }
        }
 private static string TruncatedCommand(ScriptSession session, string command, out string lastToken)
 {
     if (session.TryInvokeInRunningSession(ReplacementIndexHelper))
     {
         var teCmd = new Command("ScPsReplacementIndex");
         teCmd.Parameters.Add("inputScript", command);
         teCmd.Parameters.Add("cursorColumn", command.Length);
         List <object> psResult;
         if (session.TryInvokeInRunningSession(teCmd, out psResult))
         {
             var teResult = psResult.Cast <int>().FirstOrDefault();
             lastToken = command.Substring(teResult);
             return(command.Substring(0, teResult));
         }
     }
     lastToken = string.Empty;
     return(string.Empty);
 }
Esempio n. 16
0
        protected override void ProcessSession(ScriptSession session)
        {
            if (session.State != RunspaceAvailability.Busy) { return; }

            if (!ShouldProcess(session.ID, "Abort running script session")) return;

            if (session.ID != CurrentSessionId)
            {
                session.Abort();
            }
            else
            {
                WriteError(typeof (CmdletInvocationException), $"The current script session with Id '{session.ID}' cannot be stopped.",
                    ErrorIds.ScriptSessionCannotBeStopped, ErrorCategory.ResourceBusy,session.ID ?? string.Empty);
            }

            WriteObject(session);
        }
Esempio n. 17
0
        public static IEnumerable <string> FindMatches2(ScriptSession session, string command, bool aceResponse)
        {
            string lastToken;
            var    truncatedCommand = TruncatedCommand2(command, out lastToken);

            var teCmd = new Command("TabExpansion");

            teCmd.Parameters.Add("line", command);
            teCmd.Parameters.Add("lastWord", lastToken);
            var teResult = session.ExecuteCommand(teCmd, false, true).Cast <string>();

            var result = new List <string>();

            WrapResults(truncatedCommand, teResult, result, aceResponse);

            List <object> psResults;

            if (!session.TryInvokeInRunningSession($"Split-Path \"{lastToken}*\" -IsAbsolute", out psResults))
            {
                return(result);
            }
            var splitPathResult = psResults.FirstOrDefault();
            var isAbsolute      = splitPathResult != null && (bool)splitPathResult;

            if (isAbsolute)
            {
                if (session.TryInvokeInRunningSession($"Resolve-Path \"{lastToken}*\"", out psResults))
                {
                    var rpResult = psResults.Cast <PathInfo>().Select(p => p.Path);
                    WrapResults(truncatedCommand, rpResult, result, aceResponse);
                }
            }
            else
            {
                var commandLine = $"Resolve-Path \"{lastToken}*\" -Relative";
                if (session.TryInvokeInRunningSession(commandLine, out psResults))
                {
                    var rpResult = psResults.Cast <string>();
                    WrapResults(truncatedCommand, rpResult, result, aceResponse);
                }
            }

            return(result);
        }
Esempio n. 18
0
        public static IEnumerable<string> FindMatches2(ScriptSession session, string command, bool aceResponse)
        {
            string lastToken;
            var truncatedCommand = TruncatedCommand2(command, out lastToken);

            var teCmd = new Command("TabExpansion");
            teCmd.Parameters.Add("line", command);
            teCmd.Parameters.Add("lastWord", lastToken);
            var teResult = session.ExecuteCommand(teCmd, false, true).Cast<string>();

            var result = new List<string>();
            WrapResults(truncatedCommand, teResult, result, aceResponse);

            List<object> psResults;
            if (!session.TryInvokeInRunningSession($"Split-Path \"{lastToken}*\" -IsAbsolute", out psResults))
            {
                return result;
            }
            var splitPathResult = psResults.FirstOrDefault();
            var isAbsolute = splitPathResult != null && (bool) splitPathResult;

            if (isAbsolute)
            {
                if (session.TryInvokeInRunningSession($"Resolve-Path \"{lastToken}*\"", out psResults))
                {
                    var rpResult = psResults.Cast<PathInfo>().Select(p => p.Path);
                    WrapResults(truncatedCommand, rpResult, result, aceResponse);
                }
            }
            else
            {
                var commandLine = $"Resolve-Path \"{lastToken}*\" -Relative";
                if (session.TryInvokeInRunningSession(commandLine, out psResults))
                {
                    var rpResult = psResults.Cast<string>();
                    WrapResults(truncatedCommand, rpResult, result, aceResponse);
                }
            }

            return result;
        }
Esempio n. 19
0
        public static ScriptSession GetSession(string persistentId, string applianceType, bool personalizedSettings)
        {
            // sessions with no persistent ID, are just created new every time
            var autoDispose = string.IsNullOrEmpty(persistentId);

            if (autoDispose)
            {
                persistentId = Guid.NewGuid().ToString();
            }

            var sessionKey = GetSessionKey(persistentId);

            lock (sessions)
            {
                if (SessionExists(persistentId))
                {
                    return(HttpRuntime.Cache[sessionKey] as ScriptSession);
                }

                var session = new ScriptSession(applianceType, personalizedSettings)
                {
                    ID = persistentId,
                };

                PowerShellLog.Debug($"New Script Session with key '{sessionKey}' created.");

                if (autoDispose)
                {
                    // this only should be set if new session has been created - do not change!
                    session.AutoDispose = true;
                }
                var expiration = Sitecore.Configuration.Settings.GetIntSetting(expirationSetting, 30);
                HttpRuntime.Cache.Add(sessionKey, session, null, Cache.NoAbsoluteExpiration,
                                      new TimeSpan(0, expiration, 0), CacheItemPriority.Normal, CacheItemRemoved);
                sessions.Add(sessionKey);
                session.ID  = persistentId;
                session.Key = sessionKey;
                session.Initialize();
                return(session);
            }
        }
Esempio n. 20
0
        private static string TruncatedCommand3(ScriptSession session, string command, out string lastToken)
        {
            const string TabExpansionHelper =
                @"function ScPsReplacementIndex( [string] $inputScript, [int]$cursorColumn ){ TabExpansion2 $inputScript $cursorColumn |% { $_.ReplacementIndex } }";

            if (session.TryInvokeInRunningSession(TabExpansionHelper))
            {
                var teCmd = new Command("ScPsReplacementIndex");
                teCmd.Parameters.Add("inputScript", command);
                teCmd.Parameters.Add("cursorColumn", command.Length);
                List <object> psResult;
                if (session.TryInvokeInRunningSession(teCmd, out psResult))
                {
                    var teResult = psResult.Cast <int>().FirstOrDefault();
                    lastToken = command.Substring(teResult);
                    return(command.Substring(0, teResult));
                }
            }
            lastToken = string.Empty;
            return(string.Empty);
        }
Esempio n. 21
0
        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, "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("appMode", "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);
        }
Esempio n. 22
0
        private static void TruncatedCommand(ScriptSession session, string command, out string lastToken)
        {
            {
                if (_powerShellVersionMajor == 0)
                {
                    _powerShellVersionMajor =
                        (int) session.ExecuteScriptPart("$PSVersionTable.PSVersion.Major", false, true)[0];
                }

                switch (_powerShellVersionMajor)
                {
                    case (2):
                        TruncatedCommand2(command, out lastToken);
                        break;
                    case (3):
                    case (4):
                        TruncatedCommand3(session, command, out lastToken);
                        break;
                    default:
                        lastToken = string.Empty;
                        break;
                }
            }
        }
Esempio n. 23
0
 private static void AddCompleter(ScriptSession session, Hashtable completers, KeyValuePair<string, string> completer)
 {
     if (!completers.ContainsKey(completer.Key))
     {
         completers.Add(completer.Key,
             session.GetScriptBlock(
                 "param($commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameter) \r\n " +
                 completer.Value +
                 " | ForEach-Object { New-Object System.Management.Automation.CompletionResult $_, $_, 'ParameterValue', $_ }"
                 ));
     }
 }
Esempio n. 24
0
 public static string GetPrefix(ScriptSession session, string command)
 {
     string lastToken;
     TruncatedCommand(session, command, out lastToken);
     return string.IsNullOrEmpty(lastToken) ? string.Empty : lastToken;
 }
Esempio n. 25
0
 private static void TruncatedCommand(ScriptSession session, string command, out string lastToken)
 {
     {
         switch (ScriptSession.PsVersion.Major)
         {
             case (1):
             case (2):
                 TruncatedCommand2(command, out lastToken);
                 break;
             default:
                 TruncatedCommand3(session, command, out lastToken);
                 break;
         }
     }
 }
Esempio n. 26
0
        public static IEnumerable <string> FindMatches3(ScriptSession session, string command, bool aceResponse)
        {
            string lastToken;
            //command = command.Trim();
            var truncatedCommand = TruncatedCommand3(session, command, out lastToken) ?? string.Empty;
            var truncatedLength  = truncatedCommand.Length;
            var options          = Completers;

            lastToken = lastToken.Trim();
            if (!string.IsNullOrEmpty(lastToken) && lastToken.Trim().StartsWith("["))
            {
                if (lastToken.IndexOf("]", StringComparison.Ordinal) < 0)
                {
                    return(CompleteTypes(lastToken, truncatedLength));
                }
                if (staticFuncRegex.IsMatch(lastToken))
                {
                    var matches    = staticFuncRegex.Matches(lastToken);
                    var className  = matches[0].Groups["class"].Value;
                    var methodName = matches[0].Groups["method"].Value;

                    const BindingFlags bindingFlags =
                        BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy;

                    // look in acceelerators first
                    if (!className.Contains('.') && TypeAccelerators.AllAccelerators.ContainsKey(className))
                    {
                        return(GetMethodSignatures(TypeAccelerators.AllAccelerators[className], methodName, bindingFlags, truncatedLength));
                    }

                    // check the loaded assemblies
                    foreach (var assembly in System.AppDomain.CurrentDomain.GetAssemblies())
                    {
                        try
                        {
                            var type = assembly
                                       .GetExportedTypes()
                                       .FirstOrDefault(
                                aType => aType.FullName.Equals(className, StringComparison.OrdinalIgnoreCase));
                            if (type != null)
                            {
                                return(GetMethodSignatures(type, methodName, bindingFlags, truncatedLength));
                            }
                        }
                        catch
                        {
                            // ignore on purpose
                        }
                    }
                }
            }

            if (!string.IsNullOrEmpty(lastToken) && (lastToken.StartsWith("$") || lastToken.StartsWith("[")))
            {
                MatchCollection matches = null;
                var             matched = false;
                if (variableFuncRegex.IsMatch(lastToken))
                {
                    matches = variableFuncRegex.Matches(lastToken);
                    matched = true;
                }
                else if (staticExpressionRegex.IsMatch(lastToken))
                {
                    matches = staticExpressionRegex.Matches(lastToken);
                    matched = true;
                }

                if (matched)
                {
                    //var matches = variableFuncRegex.Matches(lastToken);
                    var           expression = matches[0].Groups["expression"].Value;
                    var           methodName = matches[0].Groups["method"].Value;
                    Type          objectType = null;
                    List <object> objectValue;
                    try
                    {
                        if (session.TryInvokeInRunningSession(expression, out objectValue, false))
                        {
                            if (objectValue != null && objectValue.Count > 0)
                            {
                                objectType = objectValue[0].GetType();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        var varName = variableRegex.Matches(lastToken)[0].Value;
                        var message = $"Variable {varName} not found in session. Execute script first.";
                        return(new List <string> {
                            $"Signature|{message}|{truncatedLength}|{message}"
                        });
                    }
                    if (objectType != null)
                    {
                        const BindingFlags bindingFlags =
                            BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance |
                            BindingFlags.FlattenHierarchy;
                        return(GetMethodSignatures(objectType, methodName, bindingFlags, truncatedLength));
                    }
                }
            }


            session.TryInvokeInRunningSession(TabExpansionHelper);

            var teCmd = new Command("ScPsTabExpansionHelper");

            teCmd.Parameters.Add("inputScript", command);
            teCmd.Parameters.Add("cursorColumn", command.Length);
            teCmd.Parameters.Add("options", options);

            var teResult = new string[0];

            List <object> results;

            if (session.TryInvokeInRunningSession(teCmd, out results, true))
            {
                teResult = results.Cast <string>().ToArray();
            }
            var result = new List <string>();

            WrapResults3(truncatedCommand, teResult, result, aceResponse);
            return(result);
        }
Esempio n. 27
0
        protected virtual void JobExecuteScript(ClientPipelineArgs args, string scriptToExecute,
            ScriptSession scriptSession, bool autoDispose)
        {
            ScriptRunning = true;
            EnterScriptInfo.Visible = false;
            UpdateRibbon();

            scriptSession.SetExecutedScript(ScriptItem);
            var parameters = new object[]
            {
                scriptSession,
                scriptToExecute
            };

            var progressBoxRunner = new ScriptRunner(ExecuteInternal, parameters, autoDispose);

            var rnd = new Random();
            Context.ClientPage.ClientResponse.SetInnerHtml(
                "ScriptResult",
                string.Format(
                    "<div id='ResultsClose' onclick='javascript:return cognifide.powershell.closeResults();' >x</div>" +
                    "<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)]));
            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();
            }
        }
Esempio n. 28
0
        private static string TruncatedCommand3(ScriptSession session, string command, out string lastToken)
        {
            const string TabExpansionHelper =
                @"function ScPsReplacementIndex( [string] $inputScript, [int]$cursorColumn ){ TabExpansion2 $inputScript $cursorColumn |% { $_.ReplacementIndex } }";

            if (session.TryInvokeInRunningSession(TabExpansionHelper))
            {

                var teCmd = new Command("ScPsReplacementIndex");
                teCmd.Parameters.Add("inputScript", command);
                teCmd.Parameters.Add("cursorColumn", command.Length);
                List<object> psResult;
                if (session.TryInvokeInRunningSession(teCmd, out psResult))
                {
                    var teResult = psResult.Cast<int>().First();
                    lastToken = command.Substring(teResult);
                    return command.Substring(0, teResult);
                }
            }
            lastToken = string.Empty;
            return string.Empty;
        }
        protected void RunJob(ScriptSession session, string command)
        {
            if (!WebServiceSettings.ServiceEnabledClient || !Sitecore.Context.IsLoggedIn)
            {
                return;
            }
            try
            {
                if (!string.IsNullOrEmpty(command))
                {
                    if (session.IsRunning)
                    {
                        session.ImmediateCommand = command;
                        var tries = 20;
                        while (!string.IsNullOrEmpty(session.ImmediateCommand) && tries > 0)
                        {
                            Thread.Sleep(100);
                            tries--;
                        }
                    }
                    else
                    {
                        session.ExecuteScriptPart(command);
                    }
                }
            }
            catch (Exception ex)
            {
                var job = Sitecore.Context.Job;
                if (job != null)
                {
                    job.Status.Failed = true;

                    var exceptionMessage = session.GetExceptionString(ex);
                    if (job.Options.WriteToLog)
                    {
                        Log.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
                {
                    Log.Error("Script execution failed. Could not find command job.", ex, this);
                }
            }
        }
 protected void ExecuteInternal(ScriptSession scriptSession, string script)
 {
     scriptSession.ExecuteScriptPart(script);
 }
Esempio n. 31
0
        public static IEnumerable<string> FindMatches3(ScriptSession session, string command, bool aceResponse)
        {
            string lastToken;
            //command = command.Trim();
            var truncatedCommand = TruncatedCommand3(session, command, out lastToken) ?? string.Empty;
            var truncatedLength = truncatedCommand.Length;
            var options = Completers;
            lastToken = lastToken.Trim();
            if (!string.IsNullOrEmpty(lastToken) && lastToken.Trim().StartsWith("["))
            {
                if (lastToken.IndexOf("]", StringComparison.Ordinal) < 0)
                {
                    return CompleteTypes(lastToken, truncatedLength);
                }
                if (staticFuncRegex.IsMatch(lastToken))
                {
                    var matches = staticFuncRegex.Matches(lastToken);
                    var className = matches[0].Groups["class"].Value;
                    var methodName = matches[0].Groups["method"].Value;

                    const BindingFlags bindingFlags =
                        BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy;

                    // look in acceelerators first
                    if (!className.Contains('.') && TypeAccelerators.AllAccelerators.ContainsKey(className))
                    {
                        return GetMethodSignatures(TypeAccelerators.AllAccelerators[className], methodName, bindingFlags, truncatedLength);
                    }

                    // check the loaded assemblies
                    foreach (var assembly in System.AppDomain.CurrentDomain.GetAssemblies())
                    {
                        try
                        {
                            var type = assembly
                                .GetExportedTypes()
                                .FirstOrDefault(
                                    aType => aType.FullName.Equals(className, StringComparison.OrdinalIgnoreCase));
                            if (type != null)
                            {
                                return GetMethodSignatures(type, methodName, bindingFlags, truncatedLength);
                            }
                        }
                        catch
                        {
                            // ignore on purpose
                        }
                    }
                }
            }

            if (!string.IsNullOrEmpty(lastToken) && (lastToken.StartsWith("$") || lastToken.StartsWith("[")))
            {
                MatchCollection matches = null;
                var matched = false;
                if (variableFuncRegex.IsMatch(lastToken))
                {
                    matches = variableFuncRegex.Matches(lastToken);
                    matched = true;
                }
                else if (staticExpressionRegex.IsMatch(lastToken))
                {
                    matches = staticExpressionRegex.Matches(lastToken);
                    matched = true;
                }

                if (matched)
                {
                    //var matches = variableFuncRegex.Matches(lastToken);
                    var expression = matches[0].Groups["expression"].Value;
                    var methodName = matches[0].Groups["method"].Value;
                    Type objectType = null;
                    List<object> objectValue;
                    try
                    {
                        if (session.TryInvokeInRunningSession(expression, out objectValue, false))
                        {
                            if (objectValue != null && objectValue.Count > 0)
                            {
                                objectType = objectValue[0].GetType();
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        var varName = variableRegex.Matches(lastToken)[0].Value;
                        var message = $"Variable {varName} not found in session. Execute script first.";
                        return new List<string> {$"Signature|{message}|{truncatedLength}|{message}"};
                    }
                    if (objectType != null)
                    {
                        const BindingFlags bindingFlags =
                            BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance |
                            BindingFlags.FlattenHierarchy;
                        return GetMethodSignatures(objectType, methodName, bindingFlags, truncatedLength);
                    }
                }
            }


            session.TryInvokeInRunningSession(TabExpansionHelper);

            var teCmd = new Command("ScPsTabExpansionHelper");
            teCmd.Parameters.Add("inputScript", command);
            teCmd.Parameters.Add("cursorColumn", command.Length);
            teCmd.Parameters.Add("options", options);

            var teResult = new string[0];

            List<object> results;
            if (session.TryInvokeInRunningSession(teCmd, out results, true))
            {
                teResult = results.Cast<string>().ToArray();
            }
            var result = new List<string>();

            WrapResults3(truncatedCommand, teResult, result, aceResponse);
            return result;
        }
Esempio n. 32
0
 protected abstract void ProcessSession(ScriptSession session);
Esempio n. 33
0
        private static string TruncatedCommand3(ScriptSession session, string command, out string lastToken)
        {
            const string TabExpansionHelper =
                @"function ScPsReplacementIndex( [string] $inputScript, [int]$cursorColumn ){ TabExpansion2 $inputScript $cursorColumn |% { $_.ReplacementIndex } }";
            session.ExecuteScriptPart(TabExpansionHelper);

            var teCmd = new Command("ScPsReplacementIndex");
            teCmd.Parameters.Add("inputScript", command);
            teCmd.Parameters.Add("cursorColumn", command.Length);

            var teResult = session.ExecuteCommand(teCmd, false, true).Cast<int>().First();

            lastToken = command.Substring(teResult);
            return command.Substring(0, teResult);
        }
        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;
        }
        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]);
                }
            }
        }
Esempio n. 36
0
 public static void RemoveSession(ScriptSession session)
 {
     RemoveSession(session.Key);
 }
Esempio n. 37
0
        protected void RunJob(ScriptSession session, string command)
        {
            try
            {
                session.JobResultsStore = null;
                session.JobResultsStore = session.ExecuteScriptPart(command, false, false, false);

            }
            catch (Exception ex)
            {
                var job = Sitecore.Context.Job;
                if (job != null)
                {
                    job.Status.Failed = true;

                    var exceptionMessage = session.GetExceptionString(ex);
                    if (job.Options.WriteToLog)
                    {
                        Log.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
                {
                    Log.Error("Script execution failed. Could not find command job.", ex, this);
                }
            }
            finally
            {
                if (session.AutoDispose)
                {
                    session.Dispose();
                }
            }
        }
Esempio n. 38
0
        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);
        }
Esempio n. 39
0
 public static void RemoveSession(ScriptSession session)
 {
     RemoveSession(session.Key);
 }