private void HandleRunspaceStateChanged(object source, RunspaceStateEventArgs stateEventArgs) { switch (stateEventArgs.RunspaceStateInfo.State) { case RunspaceState.BeforeOpen: case RunspaceState.Opening: case RunspaceState.Closing: return; } OperationStateEventArgs operationStateEventArgs = null; lock (this._syncObject) { if (!this.stopComplete) { this.stopComplete = true; this.startComplete = true; operationStateEventArgs = new OperationStateEventArgs { BaseEvent = stateEventArgs, OperationState = OperationState.StopComplete }; } else if (!this.startComplete) { this.startComplete = true; operationStateEventArgs = new OperationStateEventArgs { BaseEvent = stateEventArgs, OperationState = OperationState.StartComplete }; } } if (operationStateEventArgs != null) { this.FireEvent(operationStateEventArgs); } }
private static void DefaultRunspace_StateChanged(object sender, RunspaceStateEventArgs e) { CimSessionState cimSessionState = null; Runspace runspace = (Runspace)sender; RunspaceState state = e.RunspaceStateInfo.State; switch (state) { case RunspaceState.Closed: case RunspaceState.Broken: { if (CimSessionBase.cimSessions.TryRemove(runspace.InstanceId, out cimSessionState)) { object[] instanceId = new object[2]; instanceId[0] = runspace.InstanceId; instanceId[1] = e.RunspaceStateInfo.State; DebugHelper.WriteLog(string.Format(CultureInfo.CurrentUICulture, DebugHelper.runspaceStateChanged, instanceId)); cimSessionState.Dispose(); } runspace.StateChanged -= new EventHandler<RunspaceStateEventArgs>(CimSessionBase.DefaultRunspace_StateChanged); return; } case RunspaceState.Closing: { return; } default: { return; } } }
private void OnRunspaceStateChanged(object sender, RunspaceStateEventArgs e) { if (RunspaceState.Closing == e.RunspaceStateInfo.State) { _runspace.StateChanged -= OnRunspaceStateChanged; Stop(true); } }
private void HandleRunspaceStateChanged(object sender, RunspaceStateEventArgs eventArgs) { switch (eventArgs.RunspaceStateInfo.State) { case RunspaceState.BeforeOpen: case RunspaceState.Opening: case RunspaceState.Opened: case RunspaceState.Closing: case RunspaceState.Disconnecting: return; } this.RaiseOperationCompleteEvent(); }
private void HandleRunspaceStateChanged(object sender, RunspaceStateEventArgs stateEventArgs) { switch (stateEventArgs.RunspaceStateInfo.State) { case RunspaceState.Opened: try { if (this.invokeAndDisconnect) { base.pipeline.InvokeAsyncAndDisconnect(); } else { base.pipeline.InvokeAsync(); } } catch (InvalidPipelineStateException) { this.remoteRunspace.CloseAsync(); } catch (InvalidRunspaceStateException exception) { base.internalException = exception; this.remoteRunspace.CloseAsync(); } return; case RunspaceState.Closed: if (stateEventArgs.RunspaceStateInfo.Reason == null) { this.RaiseOperationCompleteEvent(); return; } this.RaiseOperationCompleteEvent(stateEventArgs); return; case RunspaceState.Broken: this.RaiseOperationCompleteEvent(stateEventArgs); return; } }
private void HandleRunspaceStateChanged(object sender, RunspaceStateEventArgs eventArgs) { switch (eventArgs.RunspaceStateInfo.State) { case RunspaceState.BeforeOpen: break; case RunspaceState.Opening: break; case RunspaceState.Opened: break; case RunspaceState.Closing: break; default: this.RaiseOperationCompleteEvent(); break; } }
private void StateCallBackHandler(object sender, RunspaceStateEventArgs eArgs) { if (eArgs.RunspaceStateInfo.State == RunspaceState.Disconnecting) { return; } if (eArgs.RunspaceStateInfo.State == RunspaceState.Disconnected) { // If disconnect succeeded then write the PSSession object. WriteDisconnectedPSSession(); } else { // Write error if disconnect did not succeed. WriteDisconnectFailed(); } // Notify throttle manager that the start is complete. _remoteSession.Runspace.StateChanged -= StateCallBackHandler; SendStartComplete(); }
private void StateCallBackHandler(object sender, RunspaceStateEventArgs eArgs) { if (eArgs.RunspaceStateInfo.State != RunspaceState.Disconnecting) { if (eArgs.RunspaceStateInfo.State == RunspaceState.Disconnected) { this.WriteDisconnectedPSSession(); } else { this.WriteDisconnectFailed(null); } this.remoteSession.Runspace.StateChanged -= new EventHandler<RunspaceStateEventArgs>(this.StateCallBackHandler); this.SendStartComplete(); } }
/// <summary> /// Handles state changed event of the remote runspace. If the remote runspace /// gets into a broken or closed state, writes a message and pops out the /// runspace /// </summary> /// <param name="sender">not sure</param> /// <param name="eventArgs">arguments describing this event</param> private void HandleRemoteRunspaceStateChanged(object sender, RunspaceStateEventArgs eventArgs) { RunspaceState state = eventArgs.RunspaceStateInfo.State; switch (state) { case RunspaceState.Opening: case RunspaceState.Opened: { return; } case RunspaceState.Closing: case RunspaceState.Closed: case RunspaceState.Broken: case RunspaceState.Disconnected: { PopRunspace(); } break; } }
private void StateCallBackHandler(object sender, RunspaceStateEventArgs eArgs) { if (eArgs.RunspaceStateInfo.State == RunspaceState.Connecting || eArgs.RunspaceStateInfo.State == RunspaceState.Disconnecting || eArgs.RunspaceStateInfo.State == RunspaceState.Disconnected) { return; } Dbg.Assert(eArgs.RunspaceStateInfo.State != RunspaceState.BeforeOpen, "Can't reconnect a session that hasn't been previously Opened"); Dbg.Assert(eArgs.RunspaceStateInfo.State != RunspaceState.Opening, "Can't reconnect a session that hasn't been previously Opened"); if (eArgs.RunspaceStateInfo.State == RunspaceState.Opened) { // Connect operation succeeded, write the PSSession object. WriteConnectedPSSession(); } else { // Check to see if failure is due to stale PSSession error and // add to retry list if this is the case. bool writeError = true; if (_queryRunspaces == null) { PSRemotingTransportException transportException = eArgs.RunspaceStateInfo.Reason as PSRemotingTransportException; if (transportException != null && transportException.ErrorCode == WSManNativeApi.ERROR_WSMAN_INUSE_CANNOT_RECONNECT) { lock (s_LockObject) { _retryList.Add(_session); } writeError = false; } } if (writeError) { // Connect operation failed, write error. WriteConnectFailed(eArgs.RunspaceStateInfo.Reason, _session); } } _session.Runspace.StateChanged -= StateCallBackHandler; SendStartComplete(); }
private void HandleRunspaceStateChanged(object sender, RunspaceStateEventArgs e) { RemoteRunspace runspace = sender as RemoteRunspace; if ((runspace != null) && (e.RunspaceStateInfo.State != RunspaceState.Opening)) { runspace.URIRedirectionReported -= new EventHandler<RemoteDataEventArgs<Uri>>(this.HandleURIDirectionReported); runspace.StateChanged -= new EventHandler<RunspaceStateEventArgs>(this.HandleRunspaceStateChanged); } }
private void RunspaceStateChanged(object sender, RunspaceStateEventArgs e) { _structuredTracer.RunspaceStateChanged(this._instanceId.ToString(), e.RunspaceStateInfo.State.ToString(), string.Empty); _tracer.WriteMessage("PSW Conn: runspace state" + e.RunspaceStateInfo.State.ToString()); switch (e.RunspaceStateInfo.State) { case RunspaceState.Opening: return; case RunspaceState.Closing: return; case RunspaceState.Disconnecting: { ReadyForDisconnect = false; } return; case RunspaceState.Opened: { // runspace opened successfully, assign it to the asyncresult // reset retry counter RetryAttempt = 0; ReadyForReconnect = false; AsyncResult.Connection = this; // this SetAsCompleted will result in the callback to the // activity happening in the WinRM thread AsyncResult.SetAsCompleted(null); RaiseEvents(Open); RaiseEvents(Reconnect); } break; case RunspaceState.Broken: { // Dispose the broken runspace before retry DisposeRunspace(); // connection attempt failed, retry if (RetryCount > 0 && RetryAttempt < RetryCount) { RetryAttempt++; LogRetryAttempt(RetryAttempt, RetryCount); Timer timer = new Timer { AutoReset = false, Enabled = false, Interval = _retryInterval * 1000 }; timer.Elapsed += RetryTimerElapsed; timer.Start(); } else { // all retries have failed, end the asyncresult with an exception // message Busy = false; lock (_syncObject) { if (AsyncResult != null) { AsyncResult.Connection = null; AsyncResult.SetAsCompleted(e.RunspaceStateInfo.Reason); } } _tracer.WriteMessage(String.Format(CultureInfo.InvariantCulture, "Disposing broken connection to {0}", _runspace.ConnectionInfo.ComputerName)); RaiseEvents(Open); RaiseEvents(Disconnect); RaiseEvents(Close); RaiseEvents(Reconnect); } } break; case RunspaceState.Disconnected: { ReadyForReconnect = true; RaiseEvents(Disconnect); } break; case RunspaceState.Closed: { DisposeRunspace(); RaiseEvents(Close); } break; } }
/// <summary> /// <para> /// clean up the dictionaries if the runspace is closed or broken. /// </para> /// </summary> /// <param name="sender">Runspace</param> /// <param name="e">Event args</param> private static void DefaultRunspace_StateChanged(object sender, RunspaceStateEventArgs e) { Runspace runspace = (Runspace)sender; switch (e.RunspaceStateInfo.State) { case RunspaceState.Broken: case RunspaceState.Closed: CimSessionState state; if (cimSessions.TryRemove(runspace.InstanceId, out state)) { DebugHelper.WriteLog(String.Format(CultureInfo.CurrentUICulture, DebugHelper.runspaceStateChanged, runspace.InstanceId, e.RunspaceStateInfo.State)); state.Dispose(); } runspace.StateChanged -= DefaultRunspace_StateChanged; break; default: break; } }
private void RunspaceStateChanged(object sender, RunspaceStateEventArgs e) { Guid guid = this._instanceId; this._structuredTracer.RunspaceStateChanged(guid.ToString(), e.RunspaceStateInfo.State.ToString(), string.Empty); this._tracer.WriteMessage(string.Concat("PSW Conn: runspace state", e.RunspaceStateInfo.State.ToString())); RunspaceState state = e.RunspaceStateInfo.State; switch (state) { case RunspaceState.Opened: { this.RetryAttempt = 0; this.ReadyForReconnect = false; this.AsyncResult.Connection = this; this.AsyncResult.SetAsCompleted(null); this.RaiseEvents(1); this.RaiseEvents(4); return; } case RunspaceState.Closed: { this.DisposeRunspace(); this.RaiseEvents(2); return; } case RunspaceState.Broken: { if (this.RetryCount <= 0 || this.RetryAttempt >= this.RetryCount) { this.Busy = false; lock (this._syncObject) { if (this.AsyncResult != null) { this.AsyncResult.Connection = null; this.AsyncResult.SetAsCompleted(e.RunspaceStateInfo.Reason); } } object[] computerName = new object[1]; computerName[0] = this._runspace.ConnectionInfo.ComputerName; this._tracer.WriteMessage(string.Format(CultureInfo.InvariantCulture, "Disposing broken connection to {0}", computerName)); this.DisposeRunspace(); this.RaiseEvents(1); this.RaiseEvents(3); this.RaiseEvents(2); this.RaiseEvents(4); return; } else { Connection retryAttempt = this; retryAttempt.RetryAttempt = retryAttempt.RetryAttempt + 1; Timer timer = new Timer(); timer.AutoReset = false; timer.Enabled = false; timer.Interval = (double)((float)(this._retryInterval * 0x3e8)); Timer timer1 = timer; timer1.Elapsed += new ElapsedEventHandler(this.RetryTimerElapsed); timer1.Start(); return; } } case RunspaceState.Disconnecting: { this.ReadyForDisconnect = false; return; } case RunspaceState.Disconnected: { this.ReadyForReconnect = true; this.RaiseEvents(3); return; } default: { return; } } }
//!STOP! // With 'Opened' state it is called from another thread. // Also, it can be broken, e.g. x86 build may fail on x64 machine. void OnRunspaceStateEvent(object sender, RunspaceStateEventArgs e) { //! Carefully process events other than 'Opened'. if (e.RunspaceStateInfo.State != RunspaceState.Opened) { // alive? do nothing, wait for other events if (e.RunspaceStateInfo.State != RunspaceState.Broken) return; // broken; keep an error silently _errorFatal = e.RunspaceStateInfo.Reason; //! Set the broken flag, waiting threads may continue. //! The last code, Invoking() may be waiting for this. _isRunspaceOpenedOrBroken = true; return; } // Add the module path. // STOP: [_100127_182335 test] // *) Add before the profile, so that it can load modules. // *) Add after the core loading so that standard paths are added. // *) Check for already added, e.g. when starting from another Far. var modulePathAdd = string.Concat(AppHome, "\\Modules;"); var modulePathNow = Environment.GetEnvironmentVariable(Word.PSModulePath); if (!modulePathNow.Contains(modulePathAdd)) Environment.SetEnvironmentVariable(Word.PSModulePath, modulePathAdd + modulePathNow); //! If it is async then PS catches all and adds errors to $Error. //! Thus, we don't catch anything, because this is normally async. string message = null; try { //_090315_091325 // Get engine once to avoid this: "A pipeline is already executing. Concurrent SessionStateProxy method call is not allowed." // Looks like a hack, but it works fine. Problem case: run Test-CallStack-.ps1, Esc -> the error above. // SVN tag 4.2.26 _engine_ = Runspace.SessionStateProxy.PSVariable.GetValue(Word.ExecutionContext) as EngineIntrinsics; // get version try { _PSVersion = (Version)((IDictionary)Runspace.SessionStateProxy.PSVariable.GetValue("PSVersionTable"))["PSVersion"]; } catch { throw new InvalidOperationException("Cannot get PowerShell version."); } // new variables PSVariable var1 = new PSVariable("Psf", this, ScopedItemOptions.AllScope | ScopedItemOptions.Constant); var1.Description = "Exposes PowerShellFar."; Engine.SessionState.PSVariable.Set(var1); PSVariable var2 = new PSVariable("Far", Far.Api, ScopedItemOptions.AllScope | ScopedItemOptions.Constant); var2.Description = "Exposes FarNet."; Engine.SessionState.PSVariable.Set(var2); // invoke profiles using (var ps = NewPowerShell()) { // internal profile (NB: there is trap in there) ps.AddScript(Resource.PowerShellFar, false).Invoke(); // user profile, separately for better diagnostics var profile = Path.Combine(A.Psf.Manager.GetFolderPath(SpecialFolder.RoamingData, true), "Profile.ps1"); if (File.Exists(profile)) { ps.Commands.Clear(); try { ps.AddCommand(profile, false).Invoke(); } catch (RuntimeException ex) { message = string.Format(null, @" Error in the profile: {0} Error message: {1} See $Error for details. ", profile, ex.Message); } } } } finally { // GUI message if (message != null) Far.Api.Message(message, Res.Me, MessageOptions.Warning | MessageOptions.Gui | MessageOptions.Ok); //! The last code, Invoking() may be waiting for this. _isRunspaceOpenedOrBroken = true; } }
private static void CurrentRunspace_StateChanged(object sender, RunspaceStateEventArgs e) { switch (e.RunspaceStateInfo.State) { case RunspaceState.Broken: case RunspaceState.Closed: try { GetRandomCommand.s_runspaceGeneratorMapLock.EnterWriteLock(); GetRandomCommand.s_runspaceGeneratorMap.Remove(((Runspace)sender).InstanceId); } finally { GetRandomCommand.s_runspaceGeneratorMapLock.ExitWriteLock(); } break; } }
protected virtual void HandleRunspaceStateChanged (object sender, RunspaceStateEventArgs e) { }
private void HandleRemoteRunspaceStateChanged(object sender, RunspaceStateEventArgs eventArgs) { RunspaceState state = eventArgs.RunspaceStateInfo.State; RunspaceState runspaceState = state; switch (runspaceState) { case RunspaceState.Closed: case RunspaceState.Closing: case RunspaceState.Broken: case RunspaceState.Disconnected: { this.PopRunspace(); return; } case RunspaceState.Disconnecting: { return; } default: { return; } } }
static void runspace_StateChanged(object sender, RunspaceStateEventArgs e) { // Console.WriteLine("RunspaceState = " + e.RunspaceStateInfo.ToString()); // Console.WriteLine("e.RunspaceStateInfo.Reason.Message = " + e.RunspaceStateInfo.Reason.Message); // Console.WriteLine("e.RunspaceStateInfo.State = " + e.RunspaceStateInfo.State.ToString()); }
/// <summary> /// Handler for handling runspace state changed events. This method will be /// registered in the StartOperation and StopOperation methods. This handler /// will in turn invoke the OperationComplete event for all events that are /// necessary - Opened, Closed, Disconnected, Broken. It will ignore all other state /// changes. /// </summary> /// <remarks> /// There are two problems that need to be handled. /// 1) We need to make sure that the ThrottleManager StartComplete and StopComplete /// operation events are called or the ThrottleManager will never end (hang). /// 2) The HandleRunspaceStateChanged event handler remains in the Runspace /// StateChanged event call chain until this object is disposed. We have to /// disallow the HandleRunspaceStateChanged event from running and throwing /// an exception since this prevents other event handlers in the chain from /// being called. /// </remarks> /// <param name="source">Source of this event</param> /// <param name="stateEventArgs">object describing state information of the /// runspace</param> private void HandleRunspaceStateChanged(object source, RunspaceStateEventArgs stateEventArgs) { // Disregard intermediate states. switch (stateEventArgs.RunspaceStateInfo.State) { case RunspaceState.Opening: case RunspaceState.BeforeOpen: case RunspaceState.Closing: return; } OperationStateEventArgs operationStateEventArgs = null; lock (_syncObject) { // We must call OperationComplete ony *once* for each Start/Stop operation. if (!_stopComplete) { // Note that the StopComplete callback removes *both* the Start and Stop // operations from their respective queues. So update the member vars // accordingly. _stopComplete = true; _startComplete = true; operationStateEventArgs = new OperationStateEventArgs(); operationStateEventArgs.BaseEvent = stateEventArgs; operationStateEventArgs.OperationState = OperationState.StopComplete; } else if (!_startComplete) { _startComplete = true; operationStateEventArgs = new OperationStateEventArgs(); operationStateEventArgs.BaseEvent = stateEventArgs; operationStateEventArgs.OperationState = OperationState.StartComplete; } } if (operationStateEventArgs != null) { // Fire callbacks in list order. FireEvent(operationStateEventArgs); } }
private void HandleRunspaceStateChanged(object sender, RunspaceStateEventArgs e) { Runspace runspace = sender as Runspace; bool remove = false; switch (e.RunspaceStateInfo.State) { // Detect transition to Opened state. case RunspaceState.Opened: remove = !SetUpDebuggerOnRunspace(runspace); break; // Detect any transition to a finished runspace. case RunspaceState.Broken: case RunspaceState.Closed: case RunspaceState.Disconnected: remove = true; break; } if (remove) { RemoveFromRunningRunspaceList(runspace); } }
private void StateCallBackHandler(object sender, RunspaceStateEventArgs eArgs) { if (eArgs.RunspaceStateInfo.State == RunspaceState.Connecting || eArgs.RunspaceStateInfo.State == RunspaceState.Disconnecting || eArgs.RunspaceStateInfo.State == RunspaceState.Disconnected) { return; } else { if (eArgs.RunspaceStateInfo.State != RunspaceState.Opened) { bool flag = true; if (this._queryRunspaces == null) { PSRemotingTransportException reason = eArgs.RunspaceStateInfo.Reason as PSRemotingTransportException; if (reason != null && reason.ErrorCode == -2144108083) { lock (ConnectPSSessionCommand.ConnectRunspaceOperation.s_LockObject) { this._retryList.Add(this._session); } flag = false; } } if (flag) { this.WriteConnectFailed(eArgs.RunspaceStateInfo.Reason, this._session); } } else { this.WriteConnectedPSSession(); } this._session.Runspace.StateChanged -= new EventHandler<RunspaceStateEventArgs>(this.StateCallBackHandler); this.SendStartComplete(); return; } }
private static void CurrentRunspace_StateChanged(object sender, RunspaceStateEventArgs e) { switch (e.RunspaceStateInfo.State) { case RunspaceState.Closed: case RunspaceState.Broken: try { runspaceGeneratorMapLock.AcquireWriterLock(-1); RunspaceGeneratorMap.Remove(((Runspace) sender).InstanceId); } finally { runspaceGeneratorMapLock.ReleaseWriterLock(); } break; case RunspaceState.Closing: break; default: return; } }
private void PipelineStateChanged(object sender, RunspaceStateEventArgs e) { }
private static void HandleRunspaceStateChanged(object sender, RunspaceStateEventArgs eventArgs) { RunCommandsArguments runCommandsArgument = null; if (eventArgs.RunspaceStateInfo.State == RunspaceState.Opened || eventArgs.RunspaceStateInfo.State == RunspaceState.Disconnected) { Runspace runspace = sender as Runspace; PSActivity.ArgsTableForRunspaces.TryGetValue(runspace.InstanceId, out runCommandsArgument); if (runCommandsArgument != null) { PowerShell powerShellInstance = runCommandsArgument.ImplementationContext.PowerShellInstance; PSWorkflowHost workflowHost = runCommandsArgument.PSActivityContext.WorkflowHost; if (eventArgs.RunspaceStateInfo.State != RunspaceState.Opened || powerShellInstance.InvocationStateInfo.State != PSInvocationState.Disconnected) { if (eventArgs.RunspaceStateInfo.State == RunspaceState.Disconnected && !workflowHost.RemoteRunspaceProvider.IsDisconnectedByRunspaceProvider(runspace)) { PSActivity.ArgsTableForRunspaces.TryRemove(runspace.InstanceId, out runCommandsArgument); object[] computerName = new object[1]; computerName[0] = runspace.ConnectionInfo.ComputerName; RuntimeException runtimeException = new RuntimeException(string.Format(CultureInfo.CurrentCulture, Resources.ActivityFailedDueToRunspaceDisconnect, computerName), eventArgs.RunspaceStateInfo.Reason); PSActivity.RunspaceDisconnectedCallback(runCommandsArgument, runtimeException); } return; } else { powerShellInstance.ConnectAsync(); return; } } else { return; } } else { return; } }
/// <summary> /// Handles the state changed event for runspace operations /// </summary> /// <param name="sender">sender of this information</param> /// <param name="stateEventArgs">object describing this event</param> private void HandleRunspaceStateChanged(object sender, RunspaceStateEventArgs stateEventArgs) { RunspaceState state = stateEventArgs.RunspaceStateInfo.State; switch (state) { case RunspaceState.BeforeOpen: case RunspaceState.Opening: case RunspaceState.Closing: return; case RunspaceState.Opened: { // if successfully opened // Call InvokeAsync() on the pipeline try { if (_invokeAndDisconnect) { pipeline.InvokeAsyncAndDisconnect(); } else { pipeline.InvokeAsync(); } } catch (InvalidPipelineStateException) { RemoteRunspace.CloseAsync(); } catch (InvalidRunspaceStateException e) { internalException = e; RemoteRunspace.CloseAsync(); } } break; case RunspaceState.Broken: { RaiseOperationCompleteEvent(stateEventArgs); } break; case RunspaceState.Closed: { // raise a OperationComplete event with // StopComplete message if (stateEventArgs.RunspaceStateInfo.Reason != null) { RaiseOperationCompleteEvent(stateEventArgs); } else { RaiseOperationCompleteEvent(); } } break; } // switch (state... } // HandleRunspaceStateChanged
private void OnRunspaceStateEvent(object sender, RunspaceStateEventArgs e) { //! Carefully process events other than 'Opened'. if (e.RunspaceStateInfo.State != RunspaceState.Opened) { // alive? do nothing, wait for other events if (e.RunspaceStateInfo.State != RunspaceState.Broken) return; // broken; keep an error silently errorFatal = e.RunspaceStateInfo.Reason; //! Set the broken flag, waiting threads may continue. //! The last code, Invoking() may be waiting for this. isRunspaceOpenedOrBroken = true; return; } Engine = host.Runspace.SessionStateProxy.PSVariable.GetValue("ExecutionContext") as EngineIntrinsics; }