public object ExecuteEndpoint(ExecutionContext context, AbstractEndpoint endpoint)
        {
            if (endpoint.Language != Common.Models.Language.PowerShell)
            {
                throw new Exception($"Invalid language {endpoint.Language}");
            }

            var psEndpoint = endpoint as Endpoint;

            var scriptBuilder  = new StringBuilder();
            var scriptBlockAst = psEndpoint.ScriptBlock.Ast as ScriptBlockAst;

            string header = string.Empty;

            if (scriptBlockAst.ParamBlock == null && context.Parameters.Any())
            {
                if (Log.IsDebugEnabled)
                {
                    Log.Debug("Parameters--------------");
                    foreach (var variable in context.Parameters)
                    {
                        Log.Debug($"{variable.Key} = {variable.Value}");
                    }
                }

                var paramBlockBuilder = new StringBuilder();

                if (scriptBlockAst.UsingStatements != null)
                {
                    foreach (var usingStatement in scriptBlockAst.UsingStatements)
                    {
                        paramBlockBuilder.AppendLine(usingStatement.ToString());
                    }
                }

                paramBlockBuilder.Append("param(");

                foreach (var parameter in context.Parameters)
                {
                    paramBlockBuilder.Append($"${parameter.Key},");
                }
                paramBlockBuilder.Remove(paramBlockBuilder.Length - 1, 1);
                paramBlockBuilder.Append(")");
                paramBlockBuilder.AppendLine();
                header = paramBlockBuilder.ToString();
            }
            else if (scriptBlockAst.ParamBlock != null)
            {
                header = scriptBlockAst.ParamBlock.ToString();
            }

            scriptBuilder.AppendLine(header);

            if (_dashboardService.Debugger.ShouldBreak(endpoint.Name))
            {
                scriptBuilder.AppendLine("Wait-Debugger");
            }

            foreach (var statement in scriptBlockAst.EndBlock.Statements)
            {
                scriptBuilder.AppendLine(statement.ToString());
            }

            Collection <PSObject> output;
            string json;

            using (var ps = PowerShell.Create())
            {
                using (var runspaceRef = _runspace.GetRunspace())
                {
                    runspaceRef.Runspace.ResetRunspaceState();
                    Runspace.DefaultRunspace  = runspaceRef.Runspace;
                    runspaceRef.Runspace.Name = endpoint.Name;
                    ps.Runspace = runspaceRef.Runspace;

                    var host = (UDHost)_host.GetValue(ps.Runspace);
                    var ui   = (UDHostUserInterface)host.UI;

                    if (endpoint.Variables != null)
                    {
                        Log.Debug("Scope variables--------------");
                        SetVariables(ps.Runspace, endpoint.Variables);
                    }

                    if (context.Variables != null)
                    {
                        Log.Debug("Context variables--------------");
                        SetVariables(ps.Runspace, context.Variables);
                    }

                    SetVariable(ps, "DashboardHub", _hubContext);
                    SetVariable(ps, "Cache", _memoryCache);
                    SetVariable(ps, "StateRequestService", _stateRequestService);
                    SetVariable(ps, "ConnectionId", context.ConnectionId);
                    SetVariable(ps, Constants.SessionId, context.SessionId);
                    SetVariable(ps, "ArgumentList", context.Endpoint.ArgumentList?.ToList());
                    SetVariable(ps, Constants.UDPage, context.Endpoint.Page);

                    ui.HubContext   = _hubContext;
                    ui.ConnectionId = context.ConnectionId;

                    if (context.User != null)
                    {
                        SetVariable(ps, "ClaimsPrinciple", context.User);
                        SetVariable(ps, "ClaimsPrincipal", context.User);
                    }

                    ps.AddStatement().AddScript(scriptBuilder.ToString());

                    foreach (var parameter in context.Parameters)
                    {
                        ps.AddParameter(parameter.Key, parameter.Value);
                    }

                    try
                    {
                        output = ps.Invoke();

                        if (!context.IgnoreNonTerminatingErrors)
                        {
                            if (ps.HadErrors)
                            {
                                if (ps.Streams.Error.Any())
                                {
                                    var error = ps.Streams.Error[0].Exception.Message;

                                    foreach (var errorRecord in ps.Streams.Error)
                                    {
                                        Log.Warn($"Error executing endpoint {endpoint.Name}. {errorRecord} {Environment.NewLine} {errorRecord.ScriptStackTrace}");
                                    }

                                    return(new { Error = new Error {
                                                     Message = error
                                                 } });
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Warn(ex, $"Error executing endpoint {endpoint.Name}.");

                        return(new { Error = new Error {
                                         Message = ex.Message, Location = ex.StackTrace
                                     } });
                    }
                }
            }

            if (context.NoSerialization)
            {
                return(output.Select(m => m.BaseObject).ToArray());
            }

            json = output.FirstOrDefault()?.BaseObject as string;
            if (json != null)
            {
                return(json);
            }

            return(output.Where(m => m != null).Select(m => m.BaseObject).ToList());
        }
Exemple #2
0
        public object ExecuteEndpoint(ExecutionContext context, Endpoint endpoint)
        {
            var script         = endpoint.ScriptBlock.ToString();
            var scriptBlockAst = endpoint.ScriptBlock.Ast as ScriptBlockAst;

            if (scriptBlockAst.ParamBlock == null && context.Parameters.Any())
            {
                if (Log.IsDebugEnabled)
                {
                    Log.Debug("Parameters--------------");
                    foreach (var variable in context.Parameters)
                    {
                        Log.Debug($"{variable.Key} = {variable.Value}");
                    }
                }

                var paramBlockBuilder = new StringBuilder();
                paramBlockBuilder.Append("param(");

                foreach (var parameter in context.Parameters)
                {
                    paramBlockBuilder.Append($"${parameter.Key},");
                }
                paramBlockBuilder.Remove(paramBlockBuilder.Length - 1, 1);
                paramBlockBuilder.Append(")");
                paramBlockBuilder.AppendLine();

                script = paramBlockBuilder.ToString() + script;
            }

            Collection <PSObject> output;
            string json;

            using (var ps = PowerShell.Create())
            {
                using (var runspaceRef = _runspace.GetRunspace())
                {
                    runspaceRef.Runspace.ResetRunspaceState();
                    Runspace.DefaultRunspace = runspaceRef.Runspace;
                    ps.Runspace = runspaceRef.Runspace;

                    if (endpoint.Variables != null)
                    {
                        Log.Debug("Scope variables--------------");
                        SetVariables(ps.Runspace, endpoint.Variables);
                    }

                    if (context.Variables != null)
                    {
                        Log.Debug("Context variables--------------");
                        SetVariables(ps.Runspace, context.Variables);
                    }

                    SetVariable(ps, "DashboardHub", _hubContext);
                    SetVariable(ps, "Cache", MemoryCache);
                    SetVariable(ps, "StateRequestService", _stateRequestService);
                    SetVariable(ps, "ConnectionId", context.ConnectionId);
                    SetVariable(ps, Constants.SessionId, context.SessionId);
                    SetVariable(ps, "ArgumentList", context.Endpoint.ArgumentList?.ToList());
                    SetVariable(ps, Constants.UDPage, context.Endpoint.Page);

                    if (context.User != null)
                    {
                        SetVariable(ps, "ClaimsPrinciple", context.User);
                    }

                    ps.AddStatement().AddScript(script);

                    foreach (var parameter in context.Parameters)
                    {
                        ps.AddParameter(parameter.Key, parameter.Value);
                    }

                    try
                    {
                        output = ps.Invoke();

                        if (ps.HadErrors)
                        {
                            if (ps.Streams.Error.Any())
                            {
                                var error = ps.Streams.Error[0].Exception.Message;

                                Log.Warn($"Error executing endpoint script. {error}");

                                return(new { Error = new Error {
                                                 Message = error
                                             } });
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Log.Warn(ex, "Error executing endpoint script.");

                        return(new { Error = new Error {
                                         Message = ex.Message, Location = ex.StackTrace
                                     } });
                    }
                }
            }

            if (context.NoSerialization)
            {
                return(output.Select(m => m.BaseObject).ToArray());
            }

            json = output.FirstOrDefault()?.BaseObject as string;
            if (json != null)
            {
                return(json);
            }

            if (!output.Where(m => m != null).Select(m => m.BaseObject).OfType <InputAction>().Any() && !output.Where(m => m != null).Select(m => m.BaseObject).OfType <Component>().Any())
            {
                return(output.Where(m => m != null).Select(m => m.BaseObject));
            }

            return(FindComponents(output, endpoint.Page));
        }