Beispiel #1
0
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            Settings = ApplicationSettings.GetInstance(ApplicationNames.Context, false);

            if (!Context.ClientPage.IsEvent)
            {
                ItemId   = WebUtil.GetQueryString("id");
                ItemDb   = WebUtil.GetQueryString("db");
                ItemLang = WebUtil.GetQueryString("lang");
                ItemVer  = WebUtil.GetQueryString("ver");

                PageId   = WebUtil.GetQueryString("pageId");
                PageLang = WebUtil.GetQueryString("pageLang");
                PageVer  = WebUtil.GetQueryString("pageVer");

                AppMode   = WebUtil.GetQueryString("AppMode") == "1";
                HasScript = WebUtil.GetQueryString("HasScript") == "1";

                ScriptId = WebUtil.GetQueryString("scriptId");
                ScriptDb = WebUtil.GetQueryString("scriptDb");

                RenderingId = WebUtil.GetQueryString("RenderingId");

                if (!string.IsNullOrEmpty(ScriptId) && !string.IsNullOrEmpty(ScriptId))
                {
                    var scriptItem = Factory.GetDatabase(ScriptDb).GetItem(new ID(ScriptId));
                    scriptItem.Fields.ReadAll();
                    Icon.Src = scriptItem.Appearance.Icon;

                    PersistentId = string.IsNullOrEmpty(WebUtil.GetQueryString("sessionKey"))
                        ? scriptItem[ScriptItemFieldNames.PersistentSessionId]
                        : WebUtil.GetQueryString("sessionKey");

                    ScriptContent     = scriptItem[ScriptItemFieldNames.Script];
                    DialogHeader.Text = scriptItem.DisplayName;
                }
                else
                {
                    PersistentId = string.IsNullOrEmpty(WebUtil.GetQueryString("sessionKey"))
                        ? string.Empty
                        : WebUtil.GetQueryString("sessionKey");
                    ScriptContent = ScriptSessionManager.GetSession(PersistentId).JobScript;
                }

                if (Monitor != null)
                {
                    return;
                }

                Monitor = new SpeJobMonitor {
                    ID = "Monitor"
                };
                Context.ClientPage.Controls.Add(Monitor);
            }
            else
            {
                if (Monitor == null)
                {
                    Monitor = Context.ClientPage.FindControl("Monitor") as SpeJobMonitor;
                }

                if (Context.ClientPage.ClientRequest.Parameters == "pstaskmonitor:check" &&
                    PreviousProgressValue.Text != CurrentProgressValue.Text)
                {
                    var percentComplete = Int32.Parse(CurrentProgressValue.Text);
                    SheerResponse.Eval(
                        string.Format(@"updateProgress('#progressbar',{0});", percentComplete));
                    PreviousProgressValue.Text = CurrentProgressValue.Text;
                }
            }
        }
Beispiel #2
0
        protected override void ProcessRecord()
        {
            if (Interactive && !HostData.ScriptingHost.Interactive)
            {
                RecoverHttpContext();
                WriteError(typeof(CmdletInvocationException),
                           "An interactive script session cannot be started from non interactive script session.",
                           ErrorIds.OriginatingScriptSessionNotInteractive, ErrorCategory.InvalidOperation, HostData.ScriptingHost.SessionId);
                return;
            }

            var script = string.Empty;

            scriptItem = Item;

            if (Item != null)
            {
                scriptItem = Item;
                if (!IsPowerShellScriptItem(scriptItem))
                {
                    return;
                }
                script = Item[Templates.Script.Fields.ScriptBody];
            }
            else if (Path != null)
            {
                var drive = IsCurrentDriveSitecore ? CurrentDrive : ApplicationSettings.ScriptLibraryDb;

                scriptItem = PathUtilities.GetItem(Path, drive, ApplicationSettings.ScriptLibraryPath);

                if (scriptItem == null)
                {
                    WriteError(typeof(ItemNotFoundException), $"The script '{Path}' cannot be found.",
                               ErrorIds.ItemNotFound, ErrorCategory.ObjectNotFound, Path);
                    return;
                }

                if (!IsPowerShellScriptItem(scriptItem))
                {
                    return;
                }

                script = scriptItem[Templates.Script.Fields.ScriptBody];
            }

            if (!ShouldProcess(scriptItem?.GetProviderPath() ?? string.Empty, "Start new script session"))
            {
                return;
            }

            scriptBlock = ScriptBlock ?? InvokeCommand.NewScriptBlock(script);

            // sessions from IDs
            if (Id != null && Id.Length > 0)
            {
                foreach (var id in Id)
                {
                    // is id defined?
                    if (string.IsNullOrEmpty(id))
                    {
                        WriteError(typeof(ObjectNotFoundException),
                                   "The script session Id cannot be null or empty.",
                                   ErrorIds.ScriptSessionNotFound, ErrorCategory.ResourceUnavailable, Id);
                        break;
                    }

                    // is it a wildcard search for session?
                    if (id.Contains("*") || id.Contains("?"))
                    {
                        if (ScriptSessionManager.SessionExistsForAnyUserSession(id))
                        {
                            ScriptSessionManager.GetMatchingSessionsForAnyUserSession(id).ForEach(ProcessSession);
                        }
                        else
                        {
                            WriteError(typeof(ObjectNotFoundException),
                                       $"The script session with Id '{Id}' cannot be found.",
                                       ErrorIds.ScriptSessionNotFound, ErrorCategory.ResourceUnavailable, Id);
                        }
                        break;
                    }
                    // does session exist?
                    if (ScriptSessionManager.SessionExistsForAnyUserSession(id))
                    {
                        ScriptSessionManager.GetMatchingSessionsForAnyUserSession(id).ForEach(ProcessSession);
                    }
                    else // OK... fine... execute in a new persistent session!
                    {
                        ProcessSession(ScriptSessionManager.GetSession(id, ApplicationNames.BackgroundJob, false));
                    }
                }

                return;
            }

            if (Session != null)
            {
                if (Session.Length == 0)
                {
                    WriteError(typeof(ObjectNotFoundException), "Script session cannot be found.",
                               ErrorIds.ScriptSessionNotFound, ErrorCategory.ResourceUnavailable, string.Empty);
                    return;
                }
                foreach (var session in Session)
                {
                    ProcessSession(session);
                }
            }

            ProcessSession(ScriptSessionManager.GetSession(string.Empty, ApplicationNames.BackgroundJob, false));
        }
 private static ScriptSession GetScriptSession(string guid)
 {
     return(ScriptSessionManager.GetSession(guid, ApplicationNames.Console, false));
 }
        public object GetVariableValue(string guid, string variableName)
        {
            if (!IsLoggedInUserAuthorized)
            {
                return(string.Empty);
            }

            var sessionExists = ScriptSessionManager.SessionExists(guid);

            if (!sessionExists)
            {
                return("<div class='undefinedVariableType'>Session not found</div>" +
                       "<div class='variableLine'>A script needs to be executed in the session<br/>before the variable value can be inspected.</div>");
            }

            var session = ScriptSessionManager.GetSession(guid);

            try
            {
                variableName = variableName.TrimStart('$');
                var debugVariable = session.GetDebugVariable(variableName);
                if (debugVariable == null)
                {
                    return("<div class='undefinedVariableType'>undefined</div>" +
                           $"<div class='variableLine'><span class='varName'>${variableName}</span> : <span class='varValue'>$null</span></div>");
                }

                var defaultProps = new string[0];
                if (debugVariable is PSObject)
                {
                    var script =
                        $"${variableName}.PSStandardMembers.DefaultDisplayPropertySet.ReferencedPropertyNames";
                    session.Output.SilenceOutput = true;
                    try
                    {
                        if (session.TryInvokeInRunningSession(script, out List <object> results) && results != null)
                        {
                            defaultProps = session.IsRunning
                                ? (session.Output.SilencedOutput?.ToString()
                                   .Split('\n')
                                   .Select(line => line.Trim())
                                   .ToArray() ?? new string[0])
                                : results.Cast <string>().ToArray();
                            session.Output.SilencedOutput?.Clear();
                        }
                    }
                    finally
                    {
                        session.Output.SilenceOutput = false;
                    }
                }
                var variable = debugVariable.BaseObject();
                if (variable is PSCustomObject)
                {
                    variable = debugVariable;
                }
                var details  = new VariableDetails("$" + variableName, variable);
                var varValue = $"<div class='variableType'>{variable.GetType().FullName}</div>";
                varValue +=
                    $"<div class='variableLine'><span class='varName'>${variableName}</span> : <span class='varValue'>{details.HtmlEncodedValueString}</span></div>";

                if (!details.IsExpandable)
                {
                    return(varValue);
                }

                // sort only if the object is not an array otherwise the indexes will get scrambled.
                var children = details.ShowDotNetProperties
                    ? details.GetChildren().OrderBy(d => d.Name).ToArray()
                    : details.GetChildren();

                foreach (var child in children)
                {
                    if (!child.IsExpandable ||
                        defaultProps.Contains(child.Name, StringComparer.OrdinalIgnoreCase) ||
                        ImportantProperties.Contains(child.Name, StringComparer.OrdinalIgnoreCase))
                    {
                        varValue +=
                            $"<span class='varChild'><span class='childName'>{child.Name}</span> : <span class='childValue'>{child.HtmlEncodedValueString}</span></span>";
                    }
                    else
                    {
                        if (details.ShowDotNetProperties)
                        {
                            continue;
                        }
                        varValue +=
                            $"<span class='varChild'><span class='childName'>{child.Name}</span> : <span class='childValue'>{{";
                        foreach (var subChild in child.GetChildren())
                        {
                            if (!subChild.IsExpandable)
                            {
                                varValue +=
                                    $"<span class='childName'>{subChild.Name}</span> : {subChild.HtmlEncodedValueString}, ";
                            }
                        }
                        varValue  = varValue.TrimEnd(' ', ',');
                        varValue += "}</span></span>";
                    }
                }
                if (details.MaxArrayParseSizeExceeded)
                {
                    varValue +=
                        $"<span class='varChild'><span class='varName'>... first {VariableDetails.MaxArrayParseSize} items shown.</span></span>";
                }
                return(varValue);
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
Beispiel #5
0
        private static void ProcessScript(HttpContext context, string script, Dictionary <string, Stream> streams, string cliXmlArgs = null, bool rawOutput = false, string sessionId = null, bool persistentSession = false)
        {
            if (string.IsNullOrEmpty(script))
            {
                context.Response.StatusCode        = 404;
                context.Response.StatusDescription = "The specified script is invalid.";
                return;
            }

            var session = ScriptSessionManager.GetSession(sessionId, ApplicationNames.RemoteAutomation, false);

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

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

            if (streams != null)
            {
                var scriptArguments = new Hashtable();
                foreach (var param in context.Request.QueryString.AllKeys)
                {
                    var paramValue = HttpContext.Current.Request.QueryString[param];
                    if (string.IsNullOrEmpty(param))
                    {
                        continue;
                    }
                    if (string.IsNullOrEmpty(paramValue))
                    {
                        continue;
                    }

                    scriptArguments[param] = paramValue;
                }

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

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

                session.SetVariable("requestStreams", streams);
                session.SetVariable("scriptArguments", scriptArguments);
                session.ExecuteScriptPart(script, true);
                context.Response.Write(session.Output.ToString());
            }
            else
            {
                // Duplicate the behaviors of the original RemoteAutomation service.
                var requestUri = WebUtil.GetRequestUri();
                var site       = SiteContextFactory.GetSiteContext(requestUri.Host, Context.Request.FilePath,
                                                                   requestUri.Port);
                Context.SetActiveSite(site.Name);

                if (!string.IsNullOrEmpty(cliXmlArgs))
                {
                    session.SetVariable("cliXmlArgs", cliXmlArgs);
                    session.ExecuteScriptPart("$params = ConvertFrom-CliXml -InputObject $cliXmlArgs", false, true);
                    script = script.TrimEnd(' ', '\t', '\n');
                }

                var outObjects = session.ExecuteScriptPart(script, false, false, false) ?? new List <object>();
                var response   = context.Response;
                if (rawOutput)
                {
                    // In this output we want to give raw output data. No type information is needed. Error streams are lost.
                    if (outObjects.Any())
                    {
                        foreach (var outObject in outObjects)
                        {
                            response.Write(outObject.ToString());
                        }
                    }

                    if (session.LastErrors != null && session.LastErrors.Any())
                    {
                        var convertedObjects = new List <object>();
                        convertedObjects.AddRange(session.LastErrors);

                        session.SetVariable("results", convertedObjects);
                        session.Output.Clear();
                        session.ExecuteScriptPart("ConvertTo-CliXml -InputObject $results");

                        response.Write("<#messages#>");
                        foreach (var outputBuffer in session.Output)
                        {
                            response.Write(outputBuffer.Text);
                        }
                    }
                }
                else
                {
                    // In this output we want to preserve type information. Ideal for objects with a small output content.
                    if (session.LastErrors != null && session.LastErrors.Any())
                    {
                        outObjects.AddRange(session.LastErrors);
                    }

                    if (outObjects.Any())
                    {
                        session.SetVariable("results", outObjects);
                        session.Output.Clear();
                        session.ExecuteScriptPart("ConvertTo-CliXml -InputObject $results");

                        foreach (var outputBuffer in session.Output)
                        {
                            response.Write(outputBuffer.Text);
                        }
                    }
                }
            }

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

            if (string.IsNullOrEmpty(sessionId) || !persistentSession)
            {
                ScriptSessionManager.RemoveSession(session);
            }
        }
Beispiel #6
0
        protected void OKClick()
        {
            var sid = WebUtil.GetQueryString("sid");
            var mandatoryVariables = MandatoryVariables.Split(',').ToList();

            var scriptVariables = GetVariableValues();
            var varsHashtable   = new Hashtable();
            var canClose        = true;
            var fieldValidators = FieldValidators;

            if (!Validator.IsNullOrEmpty())
            {
                foreach (var variable in scriptVariables)
                {
                    varsHashtable.Add(variable["Name"], variable);
                }
                try
                {
                    using (var session = ScriptSessionManager.GetSession(string.Empty))
                    {
                        session.SetVariable("Variables", varsHashtable);
                        session.ExecuteScriptPart(Validator);
                    }
                }
                catch (Exception ex)
                {
                    PowerShellLog.Error("Error while running form validation script.", ex);
                }
            }

            foreach (var variable in scriptVariables)
            {
                var name = variable["Name"] as string;
                if (string.IsNullOrEmpty(name))
                {
                    continue;
                }

                if (fieldValidators.ContainsKey(name))
                {
                    var fieldValidator = fieldValidators[name];
                    try
                    {
                        using (var session = ScriptSessionManager.GetSession(string.Empty))
                        {
                            session.SetVariable("variable", variable);
                            session.ExecuteScriptPart(fieldValidator);
                        }
                    }
                    catch (Exception ex)
                    {
                        PowerShellLog.Error($"Error while validating variable: {name}", ex);
                    }
                }

                var error = variable["Error"] as string;
                if (!string.IsNullOrEmpty(error))
                {
                    SheerResponse.SetInnerHtml($"var_{name}_validator", error);
                    canClose = false;
                    continue;
                }
                SheerResponse.SetInnerHtml($"var_{name}_validator", string.Empty);

                if (!mandatoryVariables.Contains(name, StringComparer.OrdinalIgnoreCase))
                {
                    continue;
                }
                var value     = variable["Value"];
                var valueType = value?.GetType().Name ?? "null";

                switch (valueType)
                {
                case "String":
                    if (!string.IsNullOrEmpty(value as string))
                    {
                        continue;
                    }
                    break;

                case "String[]":
                    if ((value as string[]).Length > 0)
                    {
                        continue;
                    }
                    break;

                case "DateTime":
                    if ((DateTime)value != DateTime.MinValue && (DateTime)value != DateTime.MaxValue)
                    {
                        continue;
                    }
                    break;

                case "null":
                    break;

                case "List`1":
                    if (value is List <Item> )
                    {
                        var itemList  = value as List <Item>;
                        var itemFound = false;
                        foreach (var item in itemList)
                        {
                            if (item != null)
                            {
                                itemFound = true;
                            }
                        }
                        if (itemFound)
                        {
                            continue;
                        }
                    }
                    break;

                default:
                    continue;
                }
                SheerResponse.SetInnerHtml($"var_{name}_validator", "Please provide a value.");
                canClose = false;
            }

            if (!canClose)
            {
                return;
            }

            HttpContext.Current.Cache.Remove(sid);
            HttpContext.Current.Cache[sid] = scriptVariables;
            SheerResponse.SetDialogValue(sid);
            SheerResponse.CloseWindow();
        }
Beispiel #7
0
        public object GetVariableValue(string guid, string variableName)
        {
            var sessionExists = ScriptSessionManager.SessionExists(guid);

            if (sessionExists)
            {
                var session = ScriptSessionManager.GetSession(guid);
                try
                {
                    variableName = variableName.TrimStart('$');
                    var debugVariable = session.GetDebugVariable(variableName);
                    if (debugVariable == null)
                    {
                        return($"<div class='undefinedVariableType'>undefined</div>" +
                               $"<div class='variableLine'><span class='varName'>${variableName}</span> : <span class='varValue'>$null</span></div>");
                    }

                    var defaultProps = new List <string>();
                    if (debugVariable is PSObject && !session.IsRunning)
                    {
                        var script =
                            $"${variableName}.PSStandardMembers.DefaultDisplayPropertySet.ReferencedPropertyNames";
                        List <object> results;
                        if (session.TryInvokeInRunningSession(script, out results) && results != null)
                        {
                            defaultProps = results.Cast <string>().ToList();
                        }
                    }
                    var variable = debugVariable.BaseObject();
                    if (variable is PSCustomObject)
                    {
                        variable = debugVariable;
                    }
                    VariableDetails details  = new VariableDetails("$" + variableName, variable);
                    var             varValue = $"<div class='variableType'>{variable.GetType().FullName}</div>";
                    varValue +=
                        $"<div class='variableLine'><span class='varName'>${variableName}</span> : <span class='varValue'>{details.HtmlEncodedValueString}</span></div>";
                    if (details.IsExpandable)
                    {
                        foreach (var child in details.GetChildren().OrderBy(d => d.Name))
                        {
                            if (!child.IsExpandable ||
                                defaultProps.Contains(child.Name, StringComparer.OrdinalIgnoreCase) ||
                                ImportantProperties.Contains(child.Name, StringComparer.OrdinalIgnoreCase))
                            {
                                varValue +=
                                    $"<span class='varChild'><span class='childName'>{child.Name}</span> : <span class='childValue'>{child.HtmlEncodedValueString}</span></span>";
                            }
                            else
                            {
                                if (details.ShowDotNetProperties)
                                {
                                    continue;
                                }
                                varValue +=
                                    $"<span class='varChild'><span class='childName'>{child.Name}</span> : <span class='childValue'>{{";
                                foreach (var subChild in child.GetChildren())
                                {
                                    if (!subChild.IsExpandable)
                                    {
                                        varValue +=
                                            $"<span class='childName'>{subChild.Name}</span> : {subChild.HtmlEncodedValueString}, ";
                                    }
                                }
                                varValue  = varValue.TrimEnd(' ', ',');
                                varValue += "}</span></span>";
                            }
                        }
                    }
                    //var varValue = variable + " - "+ variable.GetType();
                    return(varValue);
                }
                catch (Exception ex)
                {
                    return(ex.Message);
                }
            }
            return($"<div class='undefinedVariableType'>Session not found</div>" +
                   $"<div class='variableLine'>A script needs to be executed in the session<br/>before the variable value can be inspected.</div>");
        }