public LanguageServiceTests()
        {
            this.workspace = new Workspace();

            this.powerShellContext = new PowerShellContext();
            this.languageService   = new LanguageService(this.powerShellContext);
        }
        public async Task InitializeAsync()
        {
            var logger = new NullLogger();

            this.powerShellContext = PowerShellContextFactory.Create(logger);
            await this.powerShellContext.ImportCommandsModule(@"..\..\..\..\..\module\PowerShellEditorServices\Commands");

            this.extensionService = new ExtensionService(this.powerShellContext);
            this.editorOperations = new TestEditorOperations();

            this.extensionService.CommandAdded   += ExtensionService_ExtensionAdded;
            this.extensionService.CommandUpdated += ExtensionService_ExtensionUpdated;
            this.extensionService.CommandRemoved += ExtensionService_ExtensionRemoved;

            await this.extensionService.Initialize(this.editorOperations);

            var filePath = @"c:\Test\Test.ps1";

            this.currentFile    = new ScriptFile(filePath, filePath, "This is a test file", new Version("5.0"));
            this.commandContext =
                new EditorContext(
                    this.editorOperations,
                    currentFile,
                    new BufferPosition(1, 1),
                    BufferRange.None);
        }
 public PowerShellContextTests()
 {
     this.powerShellContext = new PowerShellContext();
     this.powerShellContext.SessionStateChanged += OnSessionStateChanged;
     this.powerShellContext.OutputWritten       += OnOutputWritten;
     this.stateChangeQueue = new AsyncProducerConsumerQueue <SessionStateChangedEventArgs>();
 }
Пример #4
0
        /// <summary>
        /// Creates a new instance of the TemplateService class.
        /// </summary>
        /// <param name="powerShellContext">The PowerShellContext to use for this service.</param>
        /// <param name="logger">An ILogger implementation used for writing log messages.</param>
        public TemplateService(PowerShellContext powerShellContext, ILogger logger)
        {
            Validate.IsNotNull(nameof(powerShellContext), powerShellContext);

            this.logger            = logger;
            this.powerShellContext = powerShellContext;
        }
        public async Task InitializeAsync()
        {
            var logger = Logging.NullLogger;

            this.powerShellContext = PowerShellContextFactory.Create(logger);
            await this.powerShellContext.ImportCommandsModuleAsync(
                TestUtilities.NormalizePath("../../../../../module/PowerShellEditorServices/Commands"));

            this.extensionService = new ExtensionService(this.powerShellContext);
            this.editorOperations = new TestEditorOperations();

            this.extensionService.CommandAdded   += ExtensionService_ExtensionAdded;
            this.extensionService.CommandUpdated += ExtensionService_ExtensionUpdated;
            this.extensionService.CommandRemoved += ExtensionService_ExtensionRemoved;

            await this.extensionService.InitializeAsync(
                this.editorOperations,
                new ComponentRegistry());

            var filePath = TestUtilities.NormalizePath("c:/Test/Test.ps1");

            this.currentFile    = new ScriptFile(filePath, filePath, "This is a test file", new Version("5.0"));
            this.commandContext =
                new EditorContext(
                    this.editorOperations,
                    currentFile,
                    new BufferPosition(1, 1),
                    BufferRange.None);
        }
Пример #6
0
        public IEnumerable <TResult> ExecuteCommandInDebugger <TResult>(
            PowerShellContext powerShellContext,
            Runspace currentRunspace,
            PSCommand psCommand,
            bool sendOutputToHost)
        {
            PSDataCollection <PSObject> outputCollection = new PSDataCollection <PSObject>();

#if !PowerShellv3
            if (sendOutputToHost)
            {
                outputCollection.DataAdded +=
                    (obj, e) =>
                {
                    for (int i = e.Index; i < outputCollection.Count; i++)
                    {
                        powerShellContext.WriteOutput(
                            outputCollection[i].ToString(),
                            true);
                    }
                };
            }

            DebuggerCommandResults commandResults =
                currentRunspace.Debugger.ProcessCommand(
                    psCommand,
                    outputCollection);
#endif

            return
                (outputCollection
                 .Select(pso => pso.BaseObject)
                 .Cast <TResult>());
        }
        /// <summary>
        /// Creates a new instance of the RemoteFileManager class.
        /// </summary>
        /// <param name="powerShellContext">
        /// The PowerShellContext to use for file loading operations.
        /// </param>
        /// <param name="editorOperations">
        /// The IEditorOperations instance to use for opening/closing files in the editor.
        /// </param>
        /// <param name="logger">An ILogger implementation used for writing log messages.</param>
        public RemoteFileManager(
            PowerShellContext powerShellContext,
            IEditorOperations editorOperations,
            ILogger logger)
        {
            Validate.IsNotNull(nameof(powerShellContext), powerShellContext);

            this.logger            = logger;
            this.powerShellContext = powerShellContext;
            this.powerShellContext.RunspaceChanged += HandleRunspaceChanged;

            this.editorOperations = editorOperations;

            this.processTempPath =
                Path.Combine(
                    Path.GetTempPath(),
                    "PSES-" + Process.GetCurrentProcess().Id);

            this.remoteFilesPath = Path.Combine(this.processTempPath, "RemoteFiles");

            // Delete existing temporary file cache path if it already exists
            this.TryDeleteTemporaryPath();

            // Register the psedit function in the current runspace
            this.RegisterPSEditFunction(this.powerShellContext.CurrentRunspace);
        }
Пример #8
0
        private EditorSession CreateDebugSession(
            HostDetails hostDetails,
            ProfilePaths profilePaths,
            IMessageSender messageSender,
            IMessageHandlers messageHandlers,
            IEditorOperations editorOperations,
            bool enableConsoleRepl)
        {
            EditorSession     editorSession     = new EditorSession(this.logger);
            PowerShellContext powerShellContext = new PowerShellContext(this.logger);

            EditorServicesPSHostUserInterface hostUserInterface =
                enableConsoleRepl
                    ? (EditorServicesPSHostUserInterface) new TerminalPSHostUserInterface(powerShellContext, this.logger)
                    : new ProtocolPSHostUserInterface(powerShellContext, messageSender, this.logger);

            EditorServicesPSHost psHost =
                new EditorServicesPSHost(
                    powerShellContext,
                    hostDetails,
                    hostUserInterface,
                    this.logger);

            Runspace initialRunspace = PowerShellContext.CreateRunspace(psHost);

            powerShellContext.Initialize(profilePaths, initialRunspace, true, hostUserInterface);

            editorSession.StartDebugSession(
                powerShellContext,
                hostUserInterface,
                editorOperations);

            return(editorSession);
        }
        internal static InvocationEventQueue Create(PowerShellContext powerShellContext, PromptNest promptNest)
        {
            var eventQueue = new InvocationEventQueue(powerShellContext, promptNest);

            eventQueue.CreateInvocationSubscriber();
            return(eventQueue);
        }
        public IEnumerable <TResult> ExecuteCommandInDebugger <TResult>(
            PowerShellContext powerShellContext,
            Runspace currentRunspace,
            PSCommand psCommand,
            bool sendOutputToHost)
        {
            IEnumerable <TResult> executionResult = null;

            using (var nestedPipeline = currentRunspace.CreateNestedPipeline())
            {
                foreach (var command in psCommand.Commands)
                {
                    nestedPipeline.Commands.Add(command);
                }

                executionResult =
                    nestedPipeline
                    .Invoke()
                    .Select(pso => pso.BaseObject)
                    .Cast <TResult>();
            }

            // Write the output to the host if necessary
            if (sendOutputToHost)
            {
                foreach (var line in executionResult)
                {
                    powerShellContext.WriteOutput(line.ToString(), true);
                }
            }

            return(executionResult);
        }
Пример #11
0
        public DebugServiceTests()
        {
            var logger = Logging.NullLogger;

            this.powerShellContext = PowerShellContextFactory.Create(logger);
            this.powerShellContext.SessionStateChanged += powerShellContext_SessionStateChanged;

            this.workspace = new Workspace(this.powerShellContext.LocalPowerShellVersion.Version, logger);

            // Load the test debug file
            this.debugScriptFile =
                this.workspace.GetFile(
                    @"..\..\..\..\PowerShellEditorServices.Test.Shared\Debugging\DebugTest.ps1");

            this.variableScriptFile =
                this.workspace.GetFile(
                    @"..\..\..\..\PowerShellEditorServices.Test.Shared\Debugging\VariableTest.ps1");

            this.debugService = new DebugService(this.powerShellContext, logger);
            this.debugService.DebuggerStopped   += debugService_DebuggerStopped;
            this.debugService.BreakpointUpdated += debugService_BreakpointUpdated;
            this.runnerContext = SynchronizationContext.Current;

            // Load the test debug file
            this.debugScriptFile =
                this.workspace.GetFile(
                    @"..\..\..\..\PowerShellEditorServices.Test.Shared\Debugging\DebugTest.ps1");
        }
        public LanguageServiceTests()
        {
            this.workspace = new Workspace();

            this.powerShellContext = new PowerShellContext();
            this.languageService = new LanguageService(this.powerShellContext);
        }
 public PowerShellContextTests()
 {
     this.powerShellContext = new PowerShellContext();
     this.powerShellContext.SessionStateChanged += OnSessionStateChanged;
     this.powerShellContext.OutputWritten += OnOutputWritten;
     this.stateChangeQueue = new AsyncProducerConsumerQueue<SessionStateChangedEventArgs>();
 }
Пример #14
0
        /// <summary>
        /// Creates and populates a new RunspaceDetails instance for the given runspace.
        /// </summary>
        /// <param name="runspace">
        /// The runspace for which details will be gathered.
        /// </param>
        /// <param name="sessionDetails">
        /// The SessionDetails for the runspace.
        /// </param>
        /// <param name="logger">An ILogger implementation used for writing log messages.</param>
        /// <returns>A new RunspaceDetails instance.</returns>
        internal static RunspaceDetails CreateFromRunspace(
            Runspace runspace,
            SessionDetails sessionDetails,
            ILogger logger)
        {
            Validate.IsNotNull(nameof(runspace), runspace);
            Validate.IsNotNull(nameof(sessionDetails), sessionDetails);

            var runspaceLocation = RunspaceLocation.Local;
            var runspaceContext  = RunspaceContext.Original;
            var versionDetails   = PowerShellVersionDetails.GetVersionDetails(runspace, logger);

            string connectionString = null;

            if (runspace.ConnectionInfo != null)
            {
                // Use 'dynamic' to avoid missing NamedPipeRunspaceConnectionInfo
                // on PS v3 and v4
                try
                {
                    dynamic connectionInfo = runspace.ConnectionInfo;
                    if (connectionInfo.ProcessId != null)
                    {
                        connectionString = connectionInfo.ProcessId.ToString();
                        runspaceContext  = RunspaceContext.EnteredProcess;
                    }
                }
                catch (RuntimeBinderException)
                {
                    // ProcessId property isn't on the object, move on.
                }

                // Grab the $host.name which will tell us if we're in a PSRP session or not
                string hostName =
                    PowerShellContext.ExecuteScriptAndGetItem <string>(
                        "$Host.Name",
                        runspace,
                        defaultValue: string.Empty);

                // hostname is 'ServerRemoteHost' when the user enters a session.
                // ex. Enter-PSSession, Enter-PSHostProcess
                if (hostName.Equals("ServerRemoteHost", StringComparison.Ordinal))
                {
                    runspaceLocation = RunspaceLocation.Remote;
                    connectionString =
                        runspace.ConnectionInfo.ComputerName +
                        (connectionString != null ? $"-{connectionString}" : string.Empty);
                }
            }

            return
                (new RunspaceDetails(
                     runspace,
                     sessionDetails,
                     versionDetails,
                     runspaceLocation,
                     runspaceContext,
                     connectionString));
        }
        /// <summary>
        /// Initializes a new instance of the DebugService class and uses
        /// the given PowerShellContext for all future operations.
        /// </summary>
        /// <param name="powerShellContext">
        /// The PowerShellContext to use for all debugging operations.
        /// </param>
        public DebugService(PowerShellContext powerShellContext)
        {
            Validate.IsNotNull("powerShellContext", powerShellContext);

            this.powerShellContext = powerShellContext;
            this.powerShellContext.DebuggerStop += this.OnDebuggerStop;
            this.powerShellContext.BreakpointUpdated += this.OnBreakpointUpdated;
        }
Пример #16
0
 public void StopCommandInDebugger(PowerShellContext powerShellContext)
 {
     // If the RunspaceAvailability is None, the runspace is dead and we should not try to run anything in it.
     if (powerShellContext.CurrentRunspace.Runspace.RunspaceAvailability != RunspaceAvailability.None)
     {
         powerShellContext.CurrentRunspace.Runspace.Debugger.StopProcessCommand();
     }
 }
Пример #17
0
        public LanguageServiceTests()
        {
            var logger = Logging.NullLogger;

            this.powerShellContext = PowerShellContextFactory.Create(logger);
            this.workspace         = new Workspace(this.powerShellContext.LocalPowerShellVersion.Version, logger);
            this.languageService   = new LanguageService(this.powerShellContext, logger);
        }
        /// <summary>
        /// Constructs an instance of the LanguageService class and uses
        /// the given Runspace to execute language service operations.
        /// </summary>
        /// <param name="powerShellContext">
        /// The PowerShellContext in which language service operations will be executed.
        /// </param>
        public LanguageService(PowerShellContext powerShellContext)
        {
            Validate.IsNotNull("powerShellContext", powerShellContext);

            this.powerShellContext = powerShellContext;

            this.CmdletToAliasDictionary = new Dictionary<String, List<String>>(StringComparer.OrdinalIgnoreCase);
            this.AliasToCmdletDictionary = new Dictionary<String, String>(StringComparer.OrdinalIgnoreCase);
        }
 /// <summary>
 /// Creates a new instance of the ConsoleServicePSHostUserInterface
 /// class with the given IConsoleHost implementation.
 /// </summary>
 /// <param name="powerShellContext"></param>
 public ProtocolPSHostUserInterface(
     PowerShellContext powerShellContext,
     IMessageSender messageSender,
     ILogger logger)
     : base(powerShellContext, new SimplePSHostRawUserInterface(logger), logger)
 {
     this.messageSender   = messageSender;
     this.outputDebouncer = new OutputDebouncer(messageSender);
 }
 public TestPSHostUserInterface(
     PowerShellContext powerShellContext,
     ILogger logger)
     : base(
         powerShellContext,
         new SimplePSHostRawUserInterface(logger),
         new NullLogger())
 {
 }
Пример #21
0
        protected async Task HandleLaunchRequest(
            LaunchRequestArguments launchParams,
            RequestContext <object> requestContext)
        {
            // Set the working directory for the PowerShell runspace to the cwd passed in via launch.json.
            // In case that is null, use the the folder of the script to be executed.  If the resulting
            // working dir path is a file path then extract the directory and use that.
            string workingDir = launchParams.Cwd ?? launchParams.Program;

            workingDir = PowerShellContext.UnescapePath(workingDir);
            try
            {
                if ((File.GetAttributes(workingDir) & FileAttributes.Directory) != FileAttributes.Directory)
                {
                    workingDir = Path.GetDirectoryName(workingDir);
                }
            }
            catch (Exception ex)
            {
                Logger.Write(LogLevel.Error, "cwd path is invalid: " + ex.Message);
                workingDir = Environment.CurrentDirectory;
            }

            editorSession.PowerShellContext.SetWorkingDirectory(workingDir);
            Logger.Write(LogLevel.Verbose, "Working dir set to: " + workingDir);

            // Prepare arguments to the script - if specified
            string arguments = null;

            if ((launchParams.Args != null) && (launchParams.Args.Length > 0))
            {
                arguments = string.Join(" ", launchParams.Args);
                Logger.Write(LogLevel.Verbose, "Script arguments are: " + arguments);
            }

            // We may not actually launch the script in response to this
            // request unless it comes after the configurationDone request.
            // If the launch request comes first, then stash the launch
            // params so that the subsequent configurationDone request handler
            // can launch the script.
            this.noDebug            = launchParams.NoDebug;
            this.scriptPathToLaunch = launchParams.Program;
            this.arguments          = arguments;

            // The order of debug protocol messages apparently isn't as guaranteed as we might like.
            // Need to be able to handle the case where we get the launch request after the
            // configurationDone request.
            if (this.isConfigurationDoneRequestComplete)
            {
                this.LaunchScript(requestContext);
            }

            this.isLaunchRequestComplete = true;

            await requestContext.SendResult(null);
        }
        /// <summary>
        /// Creates and populates a new RunspaceDetails instance for the given runspace.
        /// </summary>
        /// <param name="runspace">
        /// The runspace for which details will be gathered.
        /// </param>
        /// <param name="sessionDetails">
        /// The SessionDetails for the runspace.
        /// </param>
        /// <param name="logger">An ILogger implementation used for writing log messages.</param>
        /// <returns>A new RunspaceDetails instance.</returns>
        internal static RunspaceDetails CreateFromRunspace(
            Runspace runspace,
            SessionDetails sessionDetails,
            ILogger logger)
        {
            Validate.IsNotNull(nameof(runspace), runspace);
            Validate.IsNotNull(nameof(sessionDetails), sessionDetails);

            var runspaceId       = runspace.InstanceId;
            var runspaceLocation = RunspaceLocation.Local;
            var runspaceContext  = RunspaceContext.Original;
            var versionDetails   = PowerShellVersionDetails.GetVersionDetails(runspace, logger);

            string connectionString = null;

            if (runspace.ConnectionInfo != null)
            {
                // Use 'dynamic' to avoid missing NamedPipeRunspaceConnectionInfo
                // on PS v3 and v4
                try
                {
                    dynamic connectionInfo = runspace.ConnectionInfo;
                    if (connectionInfo.ProcessId != null)
                    {
                        connectionString = connectionInfo.ProcessId.ToString();
                        runspaceContext  = RunspaceContext.EnteredProcess;
                    }
                }
                catch (RuntimeBinderException)
                {
                    // ProcessId property isn't on the object, move on.
                }

                if (runspace.ConnectionInfo.ComputerName != "localhost")
                {
                    runspaceId =
                        PowerShellContext.ExecuteScriptAndGetItem <Guid>(
                            "$host.Runspace.InstanceId",
                            runspace);

                    runspaceLocation = RunspaceLocation.Remote;
                    connectionString =
                        runspace.ConnectionInfo.ComputerName +
                        (connectionString != null ? $"-{connectionString}" : string.Empty);
                }
            }

            return
                (new RunspaceDetails(
                     runspace,
                     sessionDetails,
                     versionDetails,
                     runspaceLocation,
                     runspaceContext,
                     connectionString));
        }
 public PipelineExecutionRequest(
     PowerShellContext powerShellContext,
     PSCommand psCommand,
     StringBuilder errorMessages,
     ExecutionOptions executionOptions)
 {
     _powerShellContext = powerShellContext;
     _psCommand         = psCommand;
     _errorMessages     = errorMessages;
     _executionOptions  = executionOptions;
     _resultsTask       = new TaskCompletionSource <IEnumerable <TResult> >();
 }
        public void CanDotSourcePath(string rawFileName)
        {
            string fullPath   = Path.Combine(ScriptAssetPath, rawFileName);
            string quotedPath = PowerShellContext.QuoteEscapeString(fullPath);

            var psCommand = new System.Management.Automation.PSCommand().AddScript($". {quotedPath}");

            using (var pwsh = System.Management.Automation.PowerShell.Create())
            {
                pwsh.Commands = psCommand;
                pwsh.Invoke();
            }
        }
Пример #25
0
        /// <summary>
        /// Creates a new instance of the ConsoleServicePSHostUserInterface
        /// class with the given IConsoleHost implementation.
        /// </summary>
        /// <param name="powerShellContext"></param>
        public ProtocolPSHostUserInterface(
            PowerShellContext powerShellContext,
            IMessageSender messageSender,
            IMessageHandlers messageHandlers,
            ILogger logger)
            : base(powerShellContext, new SimplePSHostRawUserInterface(logger), logger)
        {
            this.messageSender   = messageSender;
            this.outputDebouncer = new OutputDebouncer(messageSender);

            messageHandlers.SetRequestHandler(
                EvaluateRequest.Type,
                this.HandleEvaluateRequest);
        }
Пример #26
0
        public IEnumerable <TResult> ExecuteCommandInDebugger <TResult>(
            PowerShellContext powerShellContext,
            Runspace currentRunspace,
            PSCommand psCommand,
            bool sendOutputToHost,
            out DebuggerResumeAction?debuggerResumeAction)
        {
            debuggerResumeAction = null;
            PSDataCollection <PSObject> outputCollection = new PSDataCollection <PSObject>();

#if !PowerShellv3
            if (sendOutputToHost)
            {
                outputCollection.DataAdded +=
                    (obj, e) =>
                {
                    for (int i = e.Index; i < outputCollection.Count; i++)
                    {
                        powerShellContext.WriteOutput(
                            outputCollection[i].ToString(),
                            true);
                    }
                };
            }

            DebuggerCommandResults commandResults =
                currentRunspace.Debugger.ProcessCommand(
                    psCommand,
                    outputCollection);

            // Pass along the debugger's resume action if the user's
            // command caused one to be returned
            debuggerResumeAction = commandResults.ResumeAction;
#endif

            IEnumerable <TResult> results = null;
            if (typeof(TResult) != typeof(PSObject))
            {
                results =
                    outputCollection
                    .Select(pso => pso.BaseObject)
                    .Cast <TResult>();
            }
            else
            {
                results = outputCollection.Cast <TResult>();
            }

            return(results);
        }
 public PipelineExecutionRequest(
     PowerShellContext powerShellContext,
     PSCommand psCommand,
     StringBuilder errorMessages,
     bool sendOutputToHost)
     : this(
         powerShellContext,
         psCommand,
         errorMessages,
         new ExecutionOptions()
 {
     WriteOutputToHost = sendOutputToHost
 })
 {
 }
        public static PowerShellContext Create(ILogger logger)
        {
            PowerShellContext powerShellContext = new PowerShellContext(logger);

            powerShellContext.Initialize(
                PowerShellContextTests.TestProfilePaths,
                PowerShellContext.CreateRunspace(
                    PowerShellContextTests.TestHostDetails,
                    powerShellContext,
                    new TestPSHostUserInterface(powerShellContext, logger),
                    logger),
                true);

            return(powerShellContext);
        }
        public ConsoleServiceTests()
        {
            this.powerShellContext = new PowerShellContext();

            this.promptHandlerContext = 
                new TestConsolePromptHandlerContext();

            this.consoleService =
                new ConsoleService(
                    this.powerShellContext,
                    promptHandlerContext);

            this.consoleService.OutputWritten += OnOutputWritten;
            promptHandlerContext.ConsoleHost = this.consoleService;
        }
        public ConsoleServiceTests()
        {
            this.powerShellContext = new PowerShellContext();

            this.promptHandlerContext =
                new TestConsolePromptHandlerContext();

            this.consoleService =
                new ConsoleService(
                    this.powerShellContext,
                    promptHandlerContext);

            this.consoleService.OutputWritten += OnOutputWritten;
            promptHandlerContext.ConsoleHost   = this.consoleService;
        }
        public DebugServiceTests()
        {
            this.workspace = new Workspace();

            // Load the test debug file
            this.debugScriptFile =
                this.workspace.GetFile(
                    @"..\..\..\PowerShellEditorServices.Test.Shared\Debugging\DebugTest.ps1");

            this.powerShellContext = new PowerShellContext();
            this.powerShellContext.SessionStateChanged += powerShellContext_SessionStateChanged;

            this.debugService = new DebugService(this.powerShellContext);
            this.debugService.DebuggerStopped += debugService_DebuggerStopped;
            this.debugService.BreakpointUpdated += debugService_BreakpointUpdated;
        }
        public DebugServiceTests()
        {
            this.workspace = new Workspace();

            // Load the test debug file
            this.debugScriptFile =
                this.workspace.GetFile(
                    @"..\..\..\PowerShellEditorServices.Test.Shared\Debugging\DebugTest.ps1");

            this.powerShellContext = new PowerShellContext();
            this.powerShellContext.SessionStateChanged += powerShellContext_SessionStateChanged;

            this.debugService = new DebugService(this.powerShellContext);
            this.debugService.DebuggerStopped   += debugService_DebuggerStopped;
            this.debugService.BreakpointUpdated += debugService_BreakpointUpdated;
        }
        public async Task <List <BreakpointDetails> > SetLineBreakpoints(
            PowerShellContext powerShellContext,
            string scriptPath,
            BreakpointDetails[] breakpoints)
        {
            List <BreakpointDetails> resultBreakpointDetails =
                new List <BreakpointDetails>();

            // We always get the latest array of breakpoint line numbers
            // so store that for future use
            if (breakpoints.Length > 0)
            {
                // Set the breakpoints for this scriptPath
                this.breakpointsPerFile[scriptPath] =
                    breakpoints.Select(b => b.LineNumber).ToArray();
            }
            else
            {
                // No more breakpoints for this scriptPath, remove it
                this.breakpointsPerFile.Remove(scriptPath);
            }

            string hashtableString =
                string.Join(
                    ", ",
                    this.breakpointsPerFile
                    .Select(file => $"@{{Path=\"{file.Key}\";Line=@({string.Join(",", file.Value)})}}"));

            // Run Enable-DscDebug as a script because running it as a PSCommand
            // causes an error which states that the Breakpoint parameter has not
            // been passed.
            await powerShellContext.ExecuteScriptString(
                hashtableString.Length > 0
                ?$"Enable-DscDebug -Breakpoint {hashtableString}"
                : "Disable-DscDebug",
                false,
                false);

            // Verify all the breakpoints and return them
            foreach (var breakpoint in breakpoints)
            {
                breakpoint.Verified = true;
            }

            return(breakpoints.ToList());
        }
Пример #34
0
        /// <summary>
        /// Creates a new instance of the ConsoleService class.
        /// </summary>
        /// <param name="powerShellContext">
        /// The PowerShellContext that will be used for executing commands
        /// against a runspace.
        /// </param>
        /// <param name="defaultPromptHandlerContext">
        /// The default IPromptHandlerContext implementation to use for
        /// displaying prompts to the user.
        /// </param>
        public ConsoleService(
            PowerShellContext powerShellContext,
            IPromptHandlerContext defaultPromptHandlerContext)
        {
            // Register this instance as the IConsoleHost for the PowerShellContext
            this.powerShellContext             = powerShellContext;
            this.powerShellContext.ConsoleHost = this;

            // Set the default prompt handler factory or create
            // a default if one is not provided
            if (defaultPromptHandlerContext == null)
            {
                defaultPromptHandlerContext =
                    new ConsolePromptHandlerContext(this);
            }

            this.promptHandlerContextStack.Push(
                defaultPromptHandlerContext);
        }
        protected virtual void Dispose(bool disposing)
        {
            lock (_disposeSyncObject)
            {
                if (_isDisposed || !disposing)
                {
                    return;
                }

                while (NestedPromptLevel > 1)
                {
                    _consoleReader?.StopCommandLoop();
                    var currentFrame = CurrentFrame;
                    if (currentFrame.FrameType.HasFlag(PromptNestFrameType.Debug))
                    {
                        _versionSpecificOperations.StopCommandInDebugger(_powerShellContext);
                        currentFrame.ThreadController.StartThreadExit(DebuggerResumeAction.Stop);
                        currentFrame.WaitForFrameExit(CancellationToken.None);
                        continue;
                    }

                    if (currentFrame.FrameType.HasFlag(PromptNestFrameType.NestedPrompt))
                    {
                        _powerShellContext.ExitAllNestedPrompts();
                        continue;
                    }

                    currentFrame.PowerShell.BeginStop(null, null);
                    currentFrame.WaitForFrameExit(CancellationToken.None);
                }

                _consoleReader?.StopCommandLoop();
                _readLineFrame.Dispose();
                CurrentFrame.Dispose();
                _frameStack.Clear();
                _powerShellContext = null;
                _consoleReader     = null;
                _isDisposed        = true;
            }
        }
Пример #36
0
        private EditorSession CreateSession(
            HostDetails hostDetails,
            ProfilePaths profilePaths,
            IMessageSender messageSender,
            IMessageHandlers messageHandlers,
            bool enableConsoleRepl)
        {
            EditorSession     editorSession     = new EditorSession(this.logger);
            PowerShellContext powerShellContext = new PowerShellContext(this.logger);

            EditorServicesPSHostUserInterface hostUserInterface =
                enableConsoleRepl
                    ? (EditorServicesPSHostUserInterface) new TerminalPSHostUserInterface(powerShellContext, this.logger)
                    : new ProtocolPSHostUserInterface(powerShellContext, messageSender, this.logger);

            EditorServicesPSHost psHost =
                new EditorServicesPSHost(
                    powerShellContext,
                    hostDetails,
                    hostUserInterface,
                    this.logger);

            Runspace initialRunspace = PowerShellContext.CreateRunspace(psHost);

            powerShellContext.Initialize(profilePaths, initialRunspace, true, hostUserInterface);

            editorSession.StartSession(powerShellContext, hostUserInterface);

            // TODO: Move component registrations elsewhere!
            editorSession.Components.Register(this.logger);
            editorSession.Components.Register(messageHandlers);
            editorSession.Components.Register(messageSender);
            editorSession.Components.Register(powerShellContext);

            CodeLensFeature.Create(editorSession.Components, editorSession);
            DocumentSymbolFeature.Create(editorSession.Components, editorSession);

            return(editorSession);
        }
 /// <summary>
 /// Initializes a new instance of the RunspaceHandle class using the
 /// given runspace.
 /// </summary>
 /// <param name="runspace">The runspace instance which is temporarily owned by this handle.</param>
 /// <param name="powerShellContext">The PowerShellContext instance which manages the runspace.</param>
 public RunspaceHandle(Runspace runspace, PowerShellContext powerShellContext)
 {
     this.Runspace = runspace;
     this.powerShellContext = powerShellContext;
 }
 public PowerShellContextTests()
 {
     this.powerShellContext = new PowerShellContext();
     this.powerShellContext.SessionStateChanged += OnSessionStateChanged;
     this.stateChangeQueue = new AsyncQueue<SessionStateChangedEventArgs>();
 }
 public void Dispose()
 {
     this.powerShellContext.Dispose();
     this.powerShellContext = null;
 }
 public ConsoleServiceTests()
 {
     this.consoleHost = new TestConsoleHost();
     this.powerShellContext = new PowerShellContext();
 }