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();
                }
            }
        }
 internal override void PrepareForRedirection()
 {
     this.closeSessionCompleted = new WSManNativeApi.WSManShellAsync(new IntPtr(this.sessionContextID), WSManClientSessionTransportManager.sessionCloseCallback);
     WSManNativeApi.WSManCloseShell(this.wsManShellOperationHandle, 0, (IntPtr)this.closeSessionCompleted);
 }
        private void Initialize(Uri connectionUri, WSManConnectionInfo connectionInfo)
        {
            bool   isSSLSpecified = false;
            string str            = connectionUri.OriginalString;

            if (connectionUri == connectionInfo.ConnectionUri && connectionInfo.UseDefaultWSManPort)
            {
                str = WSManConnectionInfo.GetConnectionString(connectionInfo.ConnectionUri, out isSSLSpecified);
            }
            string connection;

            if (string.IsNullOrEmpty(connectionUri.Query))
            {
                connection = string.Format((IFormatProvider)CultureInfo.InvariantCulture, "{0}?PSVersion={1}", (object)str.TrimEnd('/'), (object)PSVersionInfo.PSVersion);
            }
            else
            {
                connection = string.Format((IFormatProvider)CultureInfo.InvariantCulture, "{0};PSVersion={1}", (object)str, (object)PSVersionInfo.PSVersion);
            }
            WSManNativeApi.BaseWSManAuthenticationCredentials authenticationCredentials;
            if (connectionInfo.CertificateThumbprint != null)
            {
                authenticationCredentials = (WSManNativeApi.BaseWSManAuthenticationCredentials) new WSManNativeApi.WSManCertificateThumbprintCredentials(connectionInfo.CertificateThumbprint);
            }
            else
            {
                string       name = (string)null;
                SecureString pwd  = (SecureString)null;
                if (connectionInfo.Credential != null && !string.IsNullOrEmpty(connectionInfo.Credential.UserName))
                {
                    name = connectionInfo.Credential.UserName;
                    pwd  = connectionInfo.Credential.Password;
                }
                authenticationCredentials = (WSManNativeApi.BaseWSManAuthenticationCredentials) new WSManNativeApi.WSManUserNameAuthenticationCredentials(name, pwd, connectionInfo.WSManAuthenticationMechanism);
            }
            WSManNativeApi.WSManUserNameAuthenticationCredentials authCredentials = (WSManNativeApi.WSManUserNameAuthenticationCredentials)null;
            if (connectionInfo.ProxyCredential != null)
            {
                WSManNativeApi.WSManAuthenticationMechanism authMechanism = WSManNativeApi.WSManAuthenticationMechanism.WSMAN_FLAG_AUTH_NEGOTIATE;
                string       name = (string)null;
                SecureString pwd  = (SecureString)null;
                switch (connectionInfo.ProxyAuthentication)
                {
                case AuthenticationMechanism.Basic:
                    authMechanism = WSManNativeApi.WSManAuthenticationMechanism.WSMAN_FLAG_AUTH_BASIC;
                    break;

                case AuthenticationMechanism.Negotiate:
                    authMechanism = WSManNativeApi.WSManAuthenticationMechanism.WSMAN_FLAG_AUTH_NEGOTIATE;
                    break;

                case AuthenticationMechanism.Digest:
                    authMechanism = WSManNativeApi.WSManAuthenticationMechanism.WSMAN_FLAG_AUTH_DIGEST;
                    break;
                }
                if (!string.IsNullOrEmpty(connectionInfo.ProxyCredential.UserName))
                {
                    name = connectionInfo.ProxyCredential.UserName;
                    pwd  = connectionInfo.ProxyCredential.Password;
                }
                authCredentials = new WSManNativeApi.WSManUserNameAuthenticationCredentials(name, pwd, authMechanism);
            }
            WSManNativeApi.WSManProxyInfo wsManProxyInfo = connectionInfo.ProxyAccessType == ProxyAccessType.None ? (WSManNativeApi.WSManProxyInfo)null : new WSManNativeApi.WSManProxyInfo(connectionInfo.ProxyAccessType, authCredentials);
            int errorCode = 0;

            try
            {
                errorCode = WSManNativeApi.WSManCreateSession(WSManClientSessionTransportManager.wsManApiStaticData.WSManAPIHandle, connection, 0, (IntPtr)authenticationCredentials.GetMarshalledObject(), wsManProxyInfo == null ? IntPtr.Zero : (IntPtr)wsManProxyInfo, ref this.wsManSessionHandle);
            }
            finally
            {
                authCredentials?.Dispose();
                wsManProxyInfo?.Dispose();
                authenticationCredentials?.Dispose();
            }
            if (errorCode != 0)
            {
                throw new PSInvalidOperationException(WSManNativeApi.WSManGetErrorMessage(WSManClientSessionTransportManager.wsManApiStaticData.WSManAPIHandle, errorCode));
            }
            int num;

            WSManNativeApi.WSManGetSessionOptionAsDword(this.wsManSessionHandle, WSManNativeApi.WSManSessionOption.WSMAN_OPTION_SHELL_MAX_DATA_SIZE_PER_MESSAGE_KB, out num);
            this.Fragmentor.FragmentSize = num << 10;
            this.dataToBeSent.Fragmentor = this.Fragmentor;
            this.noCompression           = !connectionInfo.UseCompression;
            this.noMachineProfile        = connectionInfo.NoMachineProfile;
            this.idleTimeout             = (long)connectionInfo.IdleTimeout;
            if (isSSLSpecified)
            {
                this.SetWSManSessionOption(WSManNativeApi.WSManSessionOption.WSMAN_OPTION_USE_SSL, 1);
            }
            if (connectionInfo.NoEncryption)
            {
                this.SetWSManSessionOption(WSManNativeApi.WSManSessionOption.WSMAN_OPTION_UNENCRYPTED_MESSAGES, 1);
            }
            if (connectionInfo.AllowImplicitCredentialForNegotiate)
            {
                WSManNativeApi.WSManSetSessionOption(this.wsManSessionHandle, WSManNativeApi.WSManSessionOption.WSMAN_OPTION_ALLOW_NEGOTIATE_IMPLICIT_CREDENTIALS, new WSManNativeApi.WSManDataDWord(1));
            }
            if (connectionInfo.UseUTF16)
            {
                this.SetWSManSessionOption(WSManNativeApi.WSManSessionOption.WSMAN_OPTION_UTF16, 1);
            }
            if (connectionInfo.SkipCACheck)
            {
                this.SetWSManSessionOption(WSManNativeApi.WSManSessionOption.WSMAN_OPTION_SKIP_CA_CHECK, 1);
            }
            if (connectionInfo.SkipCNCheck)
            {
                this.SetWSManSessionOption(WSManNativeApi.WSManSessionOption.WSMAN_OPTION_SKIP_CN_CHECK, 1);
            }
            if (connectionInfo.SkipRevocationCheck)
            {
                this.SetWSManSessionOption(WSManNativeApi.WSManSessionOption.WSMAN_OPTION_SKIP_REVOCATION_CHECK, 1);
            }
            string name1 = connectionInfo.UICulture.Name;

            if (!string.IsNullOrEmpty(name1))
            {
                this.SetWSManSessionOption(WSManNativeApi.WSManSessionOption.WSMAN_OPTION_UI_LANGUAGE, name1);
            }
            string name2 = connectionInfo.Culture.Name;

            if (!string.IsNullOrEmpty(name2))
            {
                this.SetWSManSessionOption(WSManNativeApi.WSManSessionOption.WSMAN_OPTION_LOCALE, name2);
            }
            this.SetDefaultTimeOut(connectionInfo.OperationTimeout);
            this.SetConnectTimeOut(connectionInfo.OpenTimeout);
            this.SetCloseTimeOut(connectionInfo.CancelTimeout);
            this.SetSignalTimeOut(connectionInfo.CancelTimeout);
        }
        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();
            }
        }