private void CloseSessionAndClearResources()
        {
            BaseClientTransportManager.tracer.WriteLine("Clearing session with session context: {0} Operation Context: {1}", (object)this.sessionContextID, (object)this.wsManShellOperationHandle);
            IntPtr manSessionHandle = this.wsManSessionHandle;

            this.wsManSessionHandle = IntPtr.Zero;
            object obj;

            ThreadPool.QueueUserWorkItem((WaitCallback)(state =>
            {
                obj = state;
                if (!(IntPtr.Zero != (IntPtr)obj))
                {
                    return;
                }
                WSManNativeApi.WSManCloseSession((IntPtr)obj, 0);
            }), (object)manSessionHandle);
            WSManClientSessionTransportManager.RemoveSessionTransportManager(this.sessionContextID);
            if (this.closeSessionCompleted == null)
            {
                return;
            }
            this.closeSessionCompleted.Dispose();
            this.closeSessionCompleted = (WSManNativeApi.WSManShellAsync)null;
        }
        private static void OnCloseSessionCompleted(
            IntPtr operationContext,
            int flags,
            IntPtr error,
            IntPtr shellOperationHandle,
            IntPtr commandOperationHandle,
            IntPtr operationHandle,
            IntPtr data)
        {
            BaseClientTransportManager.tracer.WriteLine("Client Session TM: CloseShell callback received", new object[0]);
            long sessnTMId = 0;
            WSManClientSessionTransportManager sessnTransportManager = (WSManClientSessionTransportManager)null;

            if (!WSManClientSessionTransportManager.TryGetSessionTransportManager(operationContext, out sessnTransportManager, out sessnTMId))
            {
                BaseClientTransportManager.tracer.WriteLine(string.Format((IFormatProvider)CultureInfo.InvariantCulture, "Unable to find a transport manager for context {0}.", (object)sessnTMId), new object[0]);
            }
            else
            {
                BaseTransportManager.ETWTracer.AnalyticChannel.WriteInformation(PSEventId.WSManCloseShellCallbackReceived, PSOpcode.Disconnect, PSTask.None, (object)sessnTransportManager.RunspacePoolInstanceId);
                if (IntPtr.Zero != error)
                {
                    WSManNativeApi.WSManError errorStruct = WSManNativeApi.WSManError.UnMarshal(error);
                    if (errorStruct.errorCode != 0)
                    {
                        BaseClientTransportManager.tracer.WriteLine(string.Format((IFormatProvider)CultureInfo.InvariantCulture, "Got error with error code {0}. Message {1}", (object)errorStruct.errorCode, (object)errorStruct.errorDetail), new object[0]);
                        TransportErrorOccuredEventArgs eventArgs = WSManTransportManagerUtils.ConstructTransportErrorEventArgs(WSManClientSessionTransportManager.wsManApiStaticData.WSManAPIHandle, sessnTransportManager.wsManSessionHandle, errorStruct, TransportMethodEnum.CloseShellOperationEx, PSRemotingErrorId.CloseExCallBackError, (object)WSManTransportManagerUtils.ParseEscapeWSManErrorMessage(errorStruct.errorDetail));
                        sessnTransportManager.RaiseErrorHandler(eventArgs);
                        return;
                    }
                }
                sessnTransportManager.RaiseCloseCompleted();
            }
        }
 private static void AddSessionTransportManager(
     long sessnTMId,
     WSManClientSessionTransportManager sessnTransportManager)
 {
     lock (WSManClientSessionTransportManager.SessionTMHandles)
         WSManClientSessionTransportManager.SessionTMHandles.Add(sessnTMId, sessnTransportManager);
 }
Ejemplo n.º 4
0
 internal static TransportErrorOccuredEventArgs ConstructTransportErrorEventArgs(IntPtr wsmanAPIHandle, WSManClientSessionTransportManager wsmanSessionTM, WSManNativeApi.WSManError errorStruct, TransportMethodEnum transportMethodReportingError, string resourceString, params object[] resourceArgs)
 {
     PSRemotingTransportException exception;
     if ((errorStruct.errorCode == -2144108135) && (wsmanSessionTM != null))
     {
         string redirectLocation = WSManNativeApi.WSManGetSessionOptionAsString(wsmanSessionTM.SessionHandle, WSManNativeApi.WSManSessionOption.WSMAN_OPTION_REDIRECT_LOCATION);
         string str2 = ParseEscapeWSManErrorMessage(WSManNativeApi.WSManGetErrorMessage(wsmanAPIHandle, errorStruct.errorCode)).Trim();
         exception = new PSRemotingTransportRedirectException(redirectLocation, PSRemotingErrorId.URIEndPointNotResolved, RemotingErrorIdStrings.URIEndPointNotResolved, new object[] { str2, redirectLocation });
     }
     else if ((errorStruct.errorCode == -2144108485) && (wsmanSessionTM != null))
     {
         string str3 = wsmanSessionTM.ConnectionInfo.ShellUri.Replace("http://schemas.microsoft.com/powershell/", string.Empty);
         string str4 = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.InvalidConfigurationName, new object[] { str3, wsmanSessionTM.ConnectionInfo.ComputerName });
         exception = new PSRemotingTransportException(PSRemotingErrorId.InvalidConfigurationName, RemotingErrorIdStrings.ConnectExCallBackError, new object[] { wsmanSessionTM.ConnectionInfo.ComputerName, str4 }) {
             TransportMessage = ParseEscapeWSManErrorMessage(WSManNativeApi.WSManGetErrorMessage(wsmanAPIHandle, errorStruct.errorCode))
         };
     }
     else
     {
         string str5 = PSRemotingErrorInvariants.FormatResourceString(resourceString, resourceArgs);
         exception = new PSRemotingTransportException(PSRemotingErrorId.TroubleShootingHelpTopic, RemotingErrorIdStrings.TroubleShootingHelpTopic, new object[] { str5 }) {
             TransportMessage = ParseEscapeWSManErrorMessage(WSManNativeApi.WSManGetErrorMessage(wsmanAPIHandle, errorStruct.errorCode))
         };
     }
     exception.ErrorCode = errorStruct.errorCode;
     return new TransportErrorOccuredEventArgs(exception, transportMethodReportingError);
 }
 private static bool TryGetSessionTransportManager(
     IntPtr operationContext,
     out WSManClientSessionTransportManager sessnTransportManager,
     out long sessnTMId)
 {
     sessnTMId             = operationContext.ToInt64();
     sessnTransportManager = (WSManClientSessionTransportManager)null;
     lock (WSManClientSessionTransportManager.SessionTMHandles)
         return(WSManClientSessionTransportManager.SessionTMHandles.TryGetValue(sessnTMId, out sessnTransportManager));
 }
Ejemplo n.º 6
0
 internal WSManClientCommandTransportManager(WSManConnectionInfo connectionInfo, IntPtr wsManShellOperationHandle, ClientRemotePowerShell shell, bool noInput, WSManClientSessionTransportManager sessnTM) : base(shell, sessnTM.CryptoHelper, sessnTM)
 {
     this.wsManShellOperationHandle = wsManShellOperationHandle;
     base.ReceivedDataCollection.MaximumReceivedDataSize   = connectionInfo.MaximumReceivedDataSizePerCommand;
     base.ReceivedDataCollection.MaximumReceivedObjectSize = connectionInfo.MaximumReceivedObjectSize;
     this.cmdLine = shell.PowerShell.Commands.Commands.GetCommandStringForHistory();
     this.onDataAvailableToSendCallback = new System.Management.Automation.Remoting.PrioritySendDataCollection.OnDataAvailableCallback(this.OnDataAvailableCallback);
     this._sessnTm = sessnTM;
     sessnTM.RobustConnectionsInitiated += new EventHandler <EventArgs>(this.HandleRobustConnectionsIntiated);
     sessnTM.RobustConnectionsCompleted += new EventHandler <EventArgs>(this.HandleRobusConnectionsCompleted);
 }
 internal WSManClientCommandTransportManager(WSManConnectionInfo connectionInfo, IntPtr wsManShellOperationHandle, ClientRemotePowerShell shell, bool noInput, WSManClientSessionTransportManager sessnTM) : base(shell, sessnTM.CryptoHelper, sessnTM)
 {
     this.wsManShellOperationHandle = wsManShellOperationHandle;
     base.ReceivedDataCollection.MaximumReceivedDataSize = connectionInfo.MaximumReceivedDataSizePerCommand;
     base.ReceivedDataCollection.MaximumReceivedObjectSize = connectionInfo.MaximumReceivedObjectSize;
     this.cmdLine = shell.PowerShell.Commands.Commands.GetCommandStringForHistory();
     this.onDataAvailableToSendCallback = new System.Management.Automation.Remoting.PrioritySendDataCollection.OnDataAvailableCallback(this.OnDataAvailableCallback);
     this._sessnTm = sessnTM;
     sessnTM.RobustConnectionsInitiated += new EventHandler<EventArgs>(this.HandleRobustConnectionsIntiated);
     sessnTM.RobustConnectionsCompleted += new EventHandler<EventArgs>(this.HandleRobusConnectionsCompleted);
 }
        private static void OnRemoteSessionDataReceived(
            IntPtr operationContext,
            int flags,
            IntPtr error,
            IntPtr shellOperationHandle,
            IntPtr commandOperationHandle,
            IntPtr operationHandle,
            IntPtr data)
        {
            BaseClientTransportManager.tracer.WriteLine("Client Session TM: OnRemoteDataReceived callback.", new object[0]);
            long sessnTMId = 0;
            WSManClientSessionTransportManager sessnTransportManager = (WSManClientSessionTransportManager)null;

            if (!WSManClientSessionTransportManager.TryGetSessionTransportManager(operationContext, out sessnTransportManager, out sessnTMId))
            {
                BaseClientTransportManager.tracer.WriteLine(string.Format((IFormatProvider)CultureInfo.InvariantCulture, "Unable to find a transport manager for context {0}.", (object)sessnTMId), new object[0]);
            }
            else
            {
                sessnTransportManager.ClearReceiveOrSendResources(flags, false);
                if (sessnTransportManager.isClosed)
                {
                    BaseClientTransportManager.tracer.WriteLine("Client Session TM: Transport manager is closed. So returning", new object[0]);
                }
                else if (!shellOperationHandle.Equals((object)sessnTransportManager.wsManShellOperationHandle))
                {
                    TransportErrorOccuredEventArgs eventArgs = new TransportErrorOccuredEventArgs(new PSRemotingTransportException(PSRemotingErrorId.ReceiveExFailed, new object[0]), TransportMethodEnum.ReceiveShellOutputEx);
                    sessnTransportManager.RaiseErrorHandler(eventArgs);
                }
                else
                {
                    if (IntPtr.Zero != error)
                    {
                        WSManNativeApi.WSManError errorStruct = WSManNativeApi.WSManError.UnMarshal(error);
                        if (errorStruct.errorCode != 0)
                        {
                            BaseClientTransportManager.tracer.WriteLine(string.Format((IFormatProvider)CultureInfo.InvariantCulture, "Got error with error code {0}. Message {1}", (object)errorStruct.errorCode, (object)errorStruct.errorDetail), new object[0]);
                            TransportErrorOccuredEventArgs eventArgs = WSManTransportManagerUtils.ConstructTransportErrorEventArgs(WSManClientSessionTransportManager.wsManApiStaticData.WSManAPIHandle, sessnTransportManager.wsManSessionHandle, errorStruct, TransportMethodEnum.ReceiveShellOutputEx, PSRemotingErrorId.ReceiveExCallBackError, (object)WSManTransportManagerUtils.ParseEscapeWSManErrorMessage(errorStruct.errorDetail));
                            sessnTransportManager.RaiseErrorHandler(eventArgs);
                            return;
                        }
                    }
                    WSManNativeApi.WSManReceiveDataResult receiveDataResult = WSManNativeApi.WSManReceiveDataResult.UnMarshal(data);
                    if (receiveDataResult.data == null)
                    {
                        return;
                    }
                    BaseClientTransportManager.tracer.WriteLine("Session Received Data : {0}", (object)receiveDataResult.data.Length);
                    BaseTransportManager.ETWTracer.AnalyticChannel.WriteInformation(PSEventId.WSManReceiveShellOutputExCallbackReceived, PSOpcode.Receive, PSTask.None, (object)sessnTransportManager.RunspacePoolInstanceId, (object)Guid.Empty, (object)receiveDataResult.data.Length.ToString((IFormatProvider)CultureInfo.InvariantCulture));
                    sessnTransportManager.ProcessRawData(receiveDataResult.data, receiveDataResult.stream);
                }
            }
        }
 internal WSManClientCommandTransportManager(
     WSManConnectionInfo connectionInfo,
     IntPtr wsManShellOperationHandle,
     ClientRemotePowerShell shell,
     bool noInput,
     WSManClientSessionTransportManager sessnTM)
     : base(shell, sessnTM.CryptoHelper, (BaseClientSessionTransportManager)sessnTM)
 {
     this.wsManShellOperationHandle = wsManShellOperationHandle;
     this.ReceivedDataCollection.MaximumReceivedDataSize   = connectionInfo.MaximumReceivedDataSizePerCommand;
     this.ReceivedDataCollection.MaximumReceivedObjectSize = connectionInfo.MaximumReceivedObjectSize;
     this.onDataAvailableToSendCallback = new PrioritySendDataCollection.OnDataAvailableCallback(this.OnDataAvailableCallback);
 }
        internal override void CloseAsync()
        {
            bool flag = false;

            lock (this.syncObject)
            {
                if (this.isClosed)
                {
                    return;
                }
                if (!this.isCreateCallbackReceived)
                {
                    this.isClosePending = true;
                    return;
                }
                this.isClosed = true;
                if (IntPtr.Zero == this.wsManShellOperationHandle)
                {
                    flag = true;
                }
            }
            base.CloseAsync();
            if (flag)
            {
                try
                {
                    this.RaiseCloseCompleted();
                }
                finally
                {
                    WSManClientSessionTransportManager.RemoveSessionTransportManager(this.sessionContextID);
                }
            }
            else
            {
                BaseTransportManager.ETWTracer.AnalyticChannel.WriteInformation(PSEventId.WSManCloseShell, PSOpcode.Disconnect, PSTask.None, (object)this.RunspacePoolInstanceId);
                this.closeSessionCompleted = new WSManNativeApi.WSManShellAsync(new IntPtr(this.sessionContextID), WSManClientSessionTransportManager.sessionCloseCallback);
                WSManNativeApi.WSManCloseShell(this.wsManShellOperationHandle, 0, (IntPtr)this.closeSessionCompleted);
            }
        }
 internal CompletionEventArgs(WSManClientSessionTransportManager.CompletionNotification notification)
 {
     this._notification = notification;
 }
Ejemplo n.º 12
0
 // we need a synchronized add and remove so that multiple threads
 // update the data store concurrently
 private static bool TryGetSessionTransportManager(IntPtr operationContext,
     out WSManClientSessionTransportManager sessnTransportManager,
     out long sessnTMId)
 {
     sessnTMId = operationContext.ToInt64();
     sessnTransportManager = null;
     lock (s_sessionTMHandles)
     {
         return s_sessionTMHandles.TryGetValue(sessnTMId, out sessnTransportManager);
     }
 }
Ejemplo n.º 13
0
 // we need a synchronized add and remove so that multiple threads
 // update the data store concurrently
 private static void AddSessionTransportManager(long sessnTMId,
     WSManClientSessionTransportManager sessnTransportManager)
 {
     lock (s_sessionTMHandles)
     {
         s_sessionTMHandles.Add(sessnTMId, sessnTransportManager);
     }
 }
Ejemplo n.º 14
0
        /// <summary>
        /// This is an internal constructor used by WSManClientSessionTransportManager.
        /// </summary>
        /// <param name="connectionInfo">
        /// connection info to be used for creating the command.
        /// </param>
        /// <param name="wsManShellOperationHandle">
        /// Shell operation handle in whose context this transport manager sends/receives
        /// data packets.
        /// </param>
        /// <param name="shell">
        /// The command to be sent to the remote end.
        /// </param>
        /// <param name="noInput">
        /// true if the command has input, false otherwise.
        /// </param>
        /// <param name="sessnTM">
        /// Session transport manager creating this command transport manager instance.
        /// Used by Command TM to apply session specific properties
        /// </param>
        internal WSManClientCommandTransportManager(WSManConnectionInfo connectionInfo,
            IntPtr wsManShellOperationHandle,
            ClientRemotePowerShell shell,
            bool noInput,
            WSManClientSessionTransportManager sessnTM) :
            base(shell, sessnTM.CryptoHelper, sessnTM)
        {
            Dbg.Assert(IntPtr.Zero != wsManShellOperationHandle, "Shell operation handle cannot be IntPtr.Zero.");
            Dbg.Assert(null != connectionInfo, "connectionInfo cannot be null");

            _wsManShellOperationHandle = wsManShellOperationHandle;

            // Apply quota limits.. allow for data to be unlimited..
            ReceivedDataCollection.MaximumReceivedDataSize = connectionInfo.MaximumReceivedDataSizePerCommand;
            ReceivedDataCollection.MaximumReceivedObjectSize = connectionInfo.MaximumReceivedObjectSize;
            _cmdLine = shell.PowerShell.Commands.Commands.GetCommandStringForHistory();
            _onDataAvailableToSendCallback =
                new PrioritySendDataCollection.OnDataAvailableCallback(OnDataAvailableCallback);
            _sessnTm = sessnTM;
            // Suspend queue on robust connections initiated event.
            sessnTM.RobustConnectionsInitiated += HandleRobustConnectionsIntiated;

            // Resume queue on robust connections completed event.
            sessnTM.RobustConnectionsCompleted += HandleRobusConnectionsCompleted;
        }
Ejemplo n.º 15
0
        private static bool HandleRobustConnectionCallback(int flags, WSManClientSessionTransportManager sessionTM)
        {
            if (flags != (int)WSManNativeApi.WSManCallbackFlags.WSMAN_FLAG_CALLBACK_SHELL_AUTODISCONNECTED &&
                flags != (int)WSManNativeApi.WSManCallbackFlags.WSMAN_FLAG_CALLBACK_NETWORK_FAILURE_DETECTED &&
                flags != (int)WSManNativeApi.WSManCallbackFlags.WSMAN_FLAG_CALLBACK_RETRYING_AFTER_NETWORK_FAILURE &&
                flags != (int)WSManNativeApi.WSManCallbackFlags.WSMAN_FLAG_CALLBACK_RECONNECTED_AFTER_NETWORK_FAILURE &&
                flags != (int)WSManNativeApi.WSManCallbackFlags.WSMAN_FLAG_CALLBACK_SHELL_AUTODISCONNECTING &&
                flags != (int)WSManNativeApi.WSManCallbackFlags.WSMAN_FLAG_CALLBACK_RETRY_ABORTED_DUE_TO_INTERNAL_ERROR)
            {
                return false;
            }

            // Raise transport event notifying start of robust connections.
            if (flags == (int)WSManNativeApi.WSManCallbackFlags.WSMAN_FLAG_CALLBACK_NETWORK_FAILURE_DETECTED)
            {
                try
                {
                    sessionTM.RobustConnectionsInitiated.SafeInvoke(sessionTM, EventArgs.Empty);
                }
                catch (ObjectDisposedException)
                { }
            }

            // Send robust notification to client.
            sessionTM.QueueRobustConnectionNotification(flags);

            // Raise transport event notifying completion of robust connections.
            if (flags == (int)WSManNativeApi.WSManCallbackFlags.WSMAN_FLAG_CALLBACK_SHELL_AUTODISCONNECTED ||
                flags == (int)WSManNativeApi.WSManCallbackFlags.WSMAN_FLAG_CALLBACK_RECONNECTED_AFTER_NETWORK_FAILURE ||
                flags == (int)WSManNativeApi.WSManCallbackFlags.WSMAN_FLAG_CALLBACK_RETRY_ABORTED_DUE_TO_INTERNAL_ERROR)
            {
                try
                {
                    sessionTM.RobustConnectionsCompleted.SafeInvoke(sessionTM, EventArgs.Empty);
                }
                catch (ObjectDisposedException)
                { }
            }

            return true;
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Constructs a WSManTransportErrorOccuredEventArgs instance from the supplied data
        /// </summary>
        /// <param name="wsmanAPIHandle">
        /// WSMan API handle to use to get error messages from WSMan error id(s)
        /// </param>
        /// <param name="wsmanSessionTM">
        /// Session Transportmanager to use to get error messages (for redirect)
        /// </param>
        /// <param name="errorStruct">
        /// Error structure supplied by callbacks from WSMan API
        /// </param>
        /// <param name="transportMethodReportingError">
        /// The transport method call that reported this error.
        /// </param>
        /// <param name="resourceString">
        /// resource string that holds the message.
        /// </param>
        /// <param name="resourceArgs">
        /// Arguments to pass to the resource
        /// </param>
        /// <returns>
        /// An instance of WSManTransportErrorOccuredEventArgs
        /// </returns>
        internal static TransportErrorOccuredEventArgs ConstructTransportErrorEventArgs(IntPtr wsmanAPIHandle,
            WSManClientSessionTransportManager wsmanSessionTM,
            WSManNativeApi.WSManError errorStruct,
            TransportMethodEnum transportMethodReportingError,
            string resourceString,
            params object[] resourceArgs)
        {
            PSRemotingTransportException e;

            //For the first two special error conditions, it is remotely possible that the wsmanSessionTM is null when the failures are returned 
            //as part of command TM operations (could be returned because of RC retries under the hood)
            //Not worth to handle these cases separately as there are very corner scenarios, but need to make sure wsmanSessionTM is not referenced


            // Destination server is reporting that URI redirect is required for this user.
            if ((errorStruct.errorCode == WSManNativeApi.ERROR_WSMAN_REDIRECT_REQUESTED) && (wsmanSessionTM != null))
            {
                IntPtr wsmanSessionHandle = wsmanSessionTM.SessionHandle;
                // populate the transport message with the redirection uri..this will
                // allow caller to make a new connection.
                string redirectLocation = WSManNativeApi.WSManGetSessionOptionAsString(wsmanSessionHandle,
                    WSManNativeApi.WSManSessionOption.WSMAN_OPTION_REDIRECT_LOCATION);
                string winrmMessage = ParseEscapeWSManErrorMessage(
                    WSManNativeApi.WSManGetErrorMessage(wsmanAPIHandle, errorStruct.errorCode)).Trim();

                e = new PSRemotingTransportRedirectException(redirectLocation,
                    PSRemotingErrorId.URIEndPointNotResolved,
                    RemotingErrorIdStrings.URIEndPointNotResolved,
                    winrmMessage,
                    redirectLocation);
            }
            else if ((errorStruct.errorCode == WSManNativeApi.ERROR_WSMAN_INVALID_RESOURCE_URI) && (wsmanSessionTM != null))
            {
                string configurationName =
                    wsmanSessionTM.ConnectionInfo.ShellUri.Replace(Remoting.Client.WSManNativeApi.ResourceURIPrefix, string.Empty);
                string errorMessage = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.InvalidConfigurationName,
                                                   configurationName,
                                                   wsmanSessionTM.ConnectionInfo.ComputerName);

                e = new PSRemotingTransportException(PSRemotingErrorId.InvalidConfigurationName,
                                                   RemotingErrorIdStrings.ConnectExCallBackError, wsmanSessionTM.ConnectionInfo.ComputerName, errorMessage);

                e.TransportMessage = ParseEscapeWSManErrorMessage(
                   WSManNativeApi.WSManGetErrorMessage(wsmanAPIHandle, errorStruct.errorCode));
            }
            else
            {
                // Construct specific error message and then append this message pointing to our own
                // help topic. PowerShell's about help topic "about_Remote_Troubleshooting" should
                // contain all the trouble shooting information.
                string wsManErrorMessage = PSRemotingErrorInvariants.FormatResourceString(resourceString, resourceArgs);
                e = new PSRemotingTransportException(PSRemotingErrorId.TroubleShootingHelpTopic,
                    RemotingErrorIdStrings.TroubleShootingHelpTopic,
                    wsManErrorMessage);

                e.TransportMessage = ParseEscapeWSManErrorMessage(
                    WSManNativeApi.WSManGetErrorMessage(wsmanAPIHandle, errorStruct.errorCode));
            }

            e.ErrorCode = errorStruct.errorCode;
            TransportErrorOccuredEventArgs eventargs =
                new TransportErrorOccuredEventArgs(e, transportMethodReportingError);
            return eventargs;
        }
Ejemplo n.º 17
0
        internal static TransportErrorOccuredEventArgs ConstructTransportErrorEventArgs(IntPtr wsmanAPIHandle, WSManClientSessionTransportManager wsmanSessionTM, WSManNativeApi.WSManError errorStruct, TransportMethodEnum transportMethodReportingError, string resourceString, params object[] resourceArgs)
        {
            PSRemotingTransportException exception;

            if ((errorStruct.errorCode == -2144108135) && (wsmanSessionTM != null))
            {
                string redirectLocation = WSManNativeApi.WSManGetSessionOptionAsString(wsmanSessionTM.SessionHandle, WSManNativeApi.WSManSessionOption.WSMAN_OPTION_REDIRECT_LOCATION);
                string str2             = ParseEscapeWSManErrorMessage(WSManNativeApi.WSManGetErrorMessage(wsmanAPIHandle, errorStruct.errorCode)).Trim();
                exception = new PSRemotingTransportRedirectException(redirectLocation, PSRemotingErrorId.URIEndPointNotResolved, RemotingErrorIdStrings.URIEndPointNotResolved, new object[] { str2, redirectLocation });
            }
            else if ((errorStruct.errorCode == -2144108485) && (wsmanSessionTM != null))
            {
                string str3 = wsmanSessionTM.ConnectionInfo.ShellUri.Replace("http://schemas.microsoft.com/powershell/", string.Empty);
                string str4 = PSRemotingErrorInvariants.FormatResourceString(RemotingErrorIdStrings.InvalidConfigurationName, new object[] { str3, wsmanSessionTM.ConnectionInfo.ComputerName });
                exception = new PSRemotingTransportException(PSRemotingErrorId.InvalidConfigurationName, RemotingErrorIdStrings.ConnectExCallBackError, new object[] { wsmanSessionTM.ConnectionInfo.ComputerName, str4 })
                {
                    TransportMessage = ParseEscapeWSManErrorMessage(WSManNativeApi.WSManGetErrorMessage(wsmanAPIHandle, errorStruct.errorCode))
                };
            }
            else
            {
                string str5 = PSRemotingErrorInvariants.FormatResourceString(resourceString, resourceArgs);
                exception = new PSRemotingTransportException(PSRemotingErrorId.TroubleShootingHelpTopic, RemotingErrorIdStrings.TroubleShootingHelpTopic, new object[] { str5 })
                {
                    TransportMessage = ParseEscapeWSManErrorMessage(WSManNativeApi.WSManGetErrorMessage(wsmanAPIHandle, errorStruct.errorCode))
                };
            }
            exception.ErrorCode = errorStruct.errorCode;
            return(new TransportErrorOccuredEventArgs(exception, transportMethodReportingError));
        }
        internal override void ConnectAsync()
        {
            List <WSManNativeApi.WSManOption> wsManOptionList = new List <WSManNativeApi.WSManOption>((IEnumerable <WSManNativeApi.WSManOption>)WSManClientSessionTransportManager.wsManApiStaticData.CommonOptionSet);

            if ((object)WSManClientSessionTransportManager.protocolVersionRedirect != null)
            {
                string str = (string)WSManClientSessionTransportManager.protocolVersionRedirect.DynamicInvoke();
                wsManOptionList.Clear();
                wsManOptionList.Add(new WSManNativeApi.WSManOption()
                {
                    name       = "protocolversion",
                    value      = str,
                    mustComply = true
                });
            }
            WSManNativeApi.WSManShellStartupInfo startupInfo = new WSManNativeApi.WSManShellStartupInfo(WSManClientSessionTransportManager.wsManApiStaticData.InputStreamSet, WSManClientSessionTransportManager.wsManApiStaticData.OutputStreamSet, 0L > this.idleTimeout || this.idleTimeout >= (long)uint.MaxValue ? uint.MaxValue : (uint)this.idleTimeout);
            if (this.openContent == null)
            {
                byte[] inArray = this.dataToBeSent.ReadOrRegisterCallback((PrioritySendDataCollection.OnDataAvailableCallback)null, out DataPriorityType _);
                bool   flag    = true;
                if ((object)WSManClientSessionTransportManager.sessionSendRedirect != null)
                {
                    object[] objArray = new object[2]
                    {
                        null,
                        (object)inArray
                    };
                    flag    = (bool)WSManClientSessionTransportManager.sessionSendRedirect.DynamicInvoke(objArray);
                    inArray = (byte[])objArray[0];
                }
                if (!flag)
                {
                    return;
                }
                if (inArray != null)
                {
                    this.openContent = new WSManNativeApi.WSManData(string.Format((IFormatProvider)CultureInfo.InvariantCulture, "<{0} xmlns=\"{1}\">{2}</{0}>", (object)"creationXml", (object)"http://schemas.microsoft.com/powershell", (object)Convert.ToBase64String(inArray, Base64FormattingOptions.None)));
                }
            }
            this.sessionContextID = WSManClientSessionTransportManager.GetNextSessionTMHandleId();
            WSManClientSessionTransportManager.AddSessionTransportManager(this.sessionContextID, this);
            BaseTransportManager.ETWTracer.AnalyticChannel.WriteInformation(PSEventId.WSManCreateShell, PSOpcode.Connect, PSTask.CreateRunspace, (object)this.RunspacePoolInstanceId);
            this.createSessionCompleted         = new WSManNativeApi.WSManShellAsync(new IntPtr(this.sessionContextID), WSManClientSessionTransportManager.sessionCreateCallback);
            this.createSessionCompletedGCHandle = GCHandle.Alloc((object)this.createSessionCompleted);
            try
            {
                lock (this.syncObject)
                {
                    if (this.isClosed)
                    {
                        return;
                    }
                    if (this.noMachineProfile)
                    {
                        wsManOptionList.Add(new WSManNativeApi.WSManOption()
                        {
                            name       = "WINRS_NOPROFILE",
                            mustComply = true,
                            value      = "1"
                        });
                    }
                    using (WSManNativeApi.WSManOptionSet optionSet = new WSManNativeApi.WSManOptionSet(wsManOptionList.ToArray()))
                        WSManNativeApi.WSManCreateShellEx(this.wsManSessionHandle, this.noCompression ? 1 : 0, this.resourceUri, startupInfo, optionSet, this.openContent, (IntPtr)this.createSessionCompleted, ref this.wsManShellOperationHandle);
                }
                if (!(this.wsManShellOperationHandle == IntPtr.Zero))
                {
                    return;
                }
                this.RaiseErrorHandler(WSManTransportManagerUtils.ConstructTransportErrorEventArgs(WSManClientSessionTransportManager.wsManApiStaticData.WSManAPIHandle, IntPtr.Zero, new WSManNativeApi.WSManError(), TransportMethodEnum.CreateShellEx, PSRemotingErrorId.ConnectExFailed));
            }
            finally
            {
                startupInfo.Dispose();
            }
        }
 private static bool HandleRobustConnectionCallback(int flags, WSManClientSessionTransportManager sessionTM)
 {
     if ((((flags != 0x40) && (flags != 0x100)) && ((flags != 0x200) && (flags != 0x400))) && ((flags != 0x800) && (flags != 0x1000)))
     {
         return false;
     }
     if (flags == 0x100)
     {
         try
         {
             sessionTM.RobustConnectionsInitiated.SafeInvoke<EventArgs>(sessionTM, EventArgs.Empty);
         }
         catch (ObjectDisposedException)
         {
         }
     }
     sessionTM.QueueRobustConnectionNotification(flags);
     if (((flags == 0x40) || (flags == 0x400)) || (flags == 0x1000))
     {
         try
         {
             sessionTM.RobustConnectionsCompleted.SafeInvoke<EventArgs>(sessionTM, EventArgs.Empty);
         }
         catch (ObjectDisposedException)
         {
         }
     }
     return true;
 }
        private static void OnCreateSessionCompleted(
            IntPtr operationContext,
            int flags,
            IntPtr error,
            IntPtr shellOperationHandle,
            IntPtr commandOperationHandle,
            IntPtr operationHandle,
            IntPtr data)
        {
            BaseClientTransportManager.tracer.WriteLine("Client Session TM: CreateShell callback received", new object[0]);
            long sessnTMId = 0;
            WSManClientSessionTransportManager sessnTransportManager = (WSManClientSessionTransportManager)null;

            if (!WSManClientSessionTransportManager.TryGetSessionTransportManager(operationContext, out sessnTransportManager, out sessnTMId))
            {
                BaseClientTransportManager.tracer.WriteLine(string.Format((IFormatProvider)CultureInfo.InvariantCulture, "Unable to find a transport manager for context {0}.", (object)sessnTMId), new object[0]);
            }
            else
            {
                BaseTransportManager.ETWTracer.AnalyticChannel.WriteInformation(PSEventId.WSManCreateShellCallbackReceived, PSOpcode.Connect, PSTask.None, (object)sessnTransportManager.RunspacePoolInstanceId);
                if (sessnTransportManager.createSessionCompleted != null)
                {
                    sessnTransportManager.createSessionCompletedGCHandle.Free();
                    sessnTransportManager.createSessionCompleted.Dispose();
                    sessnTransportManager.createSessionCompleted = (WSManNativeApi.WSManShellAsync)null;
                }
                sessnTransportManager.wsManShellOperationHandle = shellOperationHandle;
                bool flag = false;
                lock (sessnTransportManager.syncObject)
                {
                    sessnTransportManager.isCreateCallbackReceived = true;
                    if (sessnTransportManager.isClosePending)
                    {
                        flag = true;
                    }
                }
                if (flag)
                {
                    sessnTransportManager.CloseAsync();
                }
                else
                {
                    if (IntPtr.Zero != error)
                    {
                        WSManNativeApi.WSManError errorStruct = WSManNativeApi.WSManError.UnMarshal(error);
                        if (errorStruct.errorCode != 0)
                        {
                            BaseClientTransportManager.tracer.WriteLine(string.Format((IFormatProvider)CultureInfo.InvariantCulture, "Got error with error code {0}. Message {1}", (object)errorStruct.errorCode, (object)errorStruct.errorDetail), new object[0]);
                            TransportErrorOccuredEventArgs eventArgs = WSManTransportManagerUtils.ConstructTransportErrorEventArgs(WSManClientSessionTransportManager.wsManApiStaticData.WSManAPIHandle, sessnTransportManager.wsManSessionHandle, errorStruct, TransportMethodEnum.CreateShellEx, PSRemotingErrorId.ConnectExCallBackError, (object)WSManTransportManagerUtils.ParseEscapeWSManErrorMessage(errorStruct.errorDetail));
                            sessnTransportManager.RaiseErrorHandler(eventArgs);
                            return;
                        }
                    }
                    if (sessnTransportManager.openContent != null)
                    {
                        sessnTransportManager.openContent.Dispose();
                        sessnTransportManager.openContent = (WSManNativeApi.WSManData)null;
                    }
                    lock (sessnTransportManager.syncObject)
                    {
                        if (sessnTransportManager.isClosed)
                        {
                            BaseClientTransportManager.tracer.WriteLine("Client Session TM: Transport manager is closed. So returning", new object[0]);
                            return;
                        }
                        sessnTransportManager.RaiseConnectCompleted();
                        BaseClientTransportManager.tracer.WriteLine("Client Session TM: Placing Receive request using WSManReceiveShellOutputEx", new object[0]);
                        BaseTransportManager.ETWTracer.AnalyticChannel.WriteInformation(PSEventId.WSManReceiveShellOutputEx, PSOpcode.Receive, PSTask.None, (object)sessnTransportManager.RunspacePoolInstanceId, (object)Guid.Empty);
                        sessnTransportManager.receivedFromRemote = new WSManNativeApi.WSManShellAsync(operationContext, WSManClientSessionTransportManager.sessionReceiveCallback);
                        WSManNativeApi.WSManReceiveShellOutputEx(sessnTransportManager.wsManShellOperationHandle, IntPtr.Zero, 0, (IntPtr)WSManClientSessionTransportManager.wsManApiStaticData.OutputStreamSet, (IntPtr)sessnTransportManager.receivedFromRemote, ref sessnTransportManager.wsManRecieveOperationHandle);
                    }
                    sessnTransportManager.SendOneItem();
                }
            }
        }