/// <summary>
        /// Initializes the session.
        /// </summary>
        /// <param name="connectionUri">
        /// Uri to connect to.
        /// </param>
        /// <param name="connectionInfo">
        /// Connection info object used for retrieving credential, auth. mechanism etc.
        /// </param>
        /// <exception cref="PSInvalidOperationException">
        /// 1. Create Session failed with a non-zero error code.
        /// </exception>
        private void Initialize(Uri connectionUri, WSManConnectionInfo connectionInfo)
        {
            Dbg.Assert(null != connectionInfo, "connectionInfo cannot be null.");

            ConnectionInfo = connectionInfo;

            // this will generate: http://ComputerName:port/appname?PSVersion=<version>
            // PSVersion= pattern is needed to make Exchange compatible with PS V2 CTP3
            // release. Using the PSVersion= logic, Exchange R4 server will redirect
            // clients to an R3 endpoint.
            bool isSSLSpecified = false;
            string connectionStr = connectionUri.OriginalString;
            if ((connectionUri == connectionInfo.ConnectionUri) &&
                (connectionInfo.UseDefaultWSManPort))
            {
                connectionStr = WSManConnectionInfo.GetConnectionString(connectionInfo.ConnectionUri,
                    out isSSLSpecified);
            }

            // TODO: Remove this after RDS moved to $using
            string additionalUriSuffixString = string.Empty;
            if (PSSessionConfigurationData.IsServerManager)
            {
                additionalUriSuffixString = ";MSP=7a83d074-bb86-4e52-aa3e-6cc73cc066c8";
            }
            if (string.IsNullOrEmpty(connectionUri.Query))
            {
                // if there is no query string already, create one..see RFC 3986
                connectionStr = string.Format(CultureInfo.InvariantCulture,
                    "{0}?PSVersion={1}{2}",
                    // Trimming the last '/' as this will allow WSMan to
                    // properly apply URLPrefix. 
                    // Ex: http://localhost?PSVersion=2.0 will be converted
                    // to http://localhost:<port>/<urlprefix>?PSVersion=2.0
                    // by WSMan
                    connectionStr.TrimEnd('/'),
                    PSVersionInfo.PSVersion,
                    additionalUriSuffixString);
            }
            else
            {
                // if there is already a query string, append using & .. see RFC 3986
                connectionStr = string.Format(CultureInfo.InvariantCulture,
                       "{0};PSVersion={1}{2}",
                       connectionStr,
                       PSVersionInfo.PSVersion,
                       additionalUriSuffixString);
            }

            WSManNativeApi.BaseWSManAuthenticationCredentials authCredentials;
            // use certificate thumbprint for authentication
            if (connectionInfo.CertificateThumbprint != null)
            {
                authCredentials = new WSManNativeApi.WSManCertificateThumbprintCredentials(connectionInfo.CertificateThumbprint);
            }
            else
            {
                // use credential based authentication
                string userName = null;
                System.Security.SecureString password = null;
                if ((null != connectionInfo.Credential) && (!string.IsNullOrEmpty(connectionInfo.Credential.UserName)))
                {
                    userName = connectionInfo.Credential.UserName;
                    password = connectionInfo.Credential.Password;
                }

                WSManNativeApi.WSManUserNameAuthenticationCredentials userNameCredentials =
                    new WSManNativeApi.WSManUserNameAuthenticationCredentials(userName,
                        password,
                        connectionInfo.WSManAuthenticationMechanism);

                authCredentials = userNameCredentials;
            }

            // proxy related data
            WSManNativeApi.WSManUserNameAuthenticationCredentials proxyAuthCredentials = null;
            if (connectionInfo.ProxyCredential != null)
            {
                WSManNativeApi.WSManAuthenticationMechanism authMechanism = WSManNativeApi.WSManAuthenticationMechanism.WSMAN_FLAG_AUTH_NEGOTIATE;
                string userName = null;
                System.Security.SecureString password = null;

                switch (connectionInfo.ProxyAuthentication)
                {
                    case AuthenticationMechanism.Negotiate:
                        authMechanism = WSManNativeApi.WSManAuthenticationMechanism.WSMAN_FLAG_AUTH_NEGOTIATE;
                        break;
                    case AuthenticationMechanism.Basic:
                        authMechanism = WSManNativeApi.WSManAuthenticationMechanism.WSMAN_FLAG_AUTH_BASIC;
                        break;
                    case AuthenticationMechanism.Digest:
                        authMechanism = WSManNativeApi.WSManAuthenticationMechanism.WSMAN_FLAG_AUTH_DIGEST;
                        break;
                }

                if (!string.IsNullOrEmpty(connectionInfo.ProxyCredential.UserName))
                {
                    userName = connectionInfo.ProxyCredential.UserName;
                    password = connectionInfo.ProxyCredential.Password;
                }

                // use credential based authentication
                proxyAuthCredentials = new WSManNativeApi.WSManUserNameAuthenticationCredentials(userName, password, authMechanism);
            }

            WSManNativeApi.WSManProxyInfo proxyInfo = (ProxyAccessType.None == connectionInfo.ProxyAccessType) ?
                null :
                new WSManNativeApi.WSManProxyInfo(connectionInfo.ProxyAccessType, proxyAuthCredentials);

            int result = 0;

            try
            {
                result = WSManNativeApi.WSManCreateSession(WSManAPIData.WSManAPIHandle, connectionStr, 0,
                     authCredentials.GetMarshalledObject(),
                     (null == proxyInfo) ? IntPtr.Zero : (IntPtr)proxyInfo,
                     ref _wsManSessionHandle);
            }
            finally
            {
                // release resources
                if (null != proxyAuthCredentials)
                {
                    proxyAuthCredentials.Dispose();
                }

                if (null != proxyInfo)
                {
                    proxyInfo.Dispose();
                }

                if (null != authCredentials)
                {
                    authCredentials.Dispose();
                }
            }

            if (result != 0)
            {
                // Get the error message from WSMan
                string errorMessage = WSManNativeApi.WSManGetErrorMessage(WSManAPIData.WSManAPIHandle, result);

                PSInvalidOperationException exception = new PSInvalidOperationException(errorMessage);
                throw exception;
            }

            // set the packet size for this session
            int packetSize;
            WSManNativeApi.WSManGetSessionOptionAsDword(_wsManSessionHandle,
                WSManNativeApi.WSManSessionOption.WSMAN_OPTION_SHELL_MAX_DATA_SIZE_PER_MESSAGE_KB,
                out packetSize);
            // packet size returned is in KB. Convert this into bytes..
            Fragmentor.FragmentSize = packetSize << 10;

            // Get robust connections maximum retries time.
            WSManNativeApi.WSManGetSessionOptionAsDword(_wsManSessionHandle,
                WSManNativeApi.WSManSessionOption.WSMAN_OPTION_MAX_RETRY_TIME,
                out _maxRetryTime);

            this.dataToBeSent.Fragmentor = base.Fragmentor;
            _noCompression = !connectionInfo.UseCompression;
            _noMachineProfile = connectionInfo.NoMachineProfile;

            // set other WSMan session related defaults            
            if (isSSLSpecified)
            {
                // WSMan Port DCR related changes - BUG 542726
                // this session option will tell WSMan to use port for HTTPS from
                // config provider.
                SetWSManSessionOption(WSManNativeApi.WSManSessionOption.WSMAN_OPTION_USE_SSL, 1);
            }
            if (connectionInfo.NoEncryption)
            {
                // send unencrypted messages
                SetWSManSessionOption(WSManNativeApi.WSManSessionOption.WSMAN_OPTION_UNENCRYPTED_MESSAGES, 1);
            }
            // check if implicit credentials can be used for Negotiate
            if (connectionInfo.AllowImplicitCredentialForNegotiate)
            {
                result = WSManNativeApi.WSManSetSessionOption(_wsManSessionHandle,
                    WSManNativeApi.WSManSessionOption.WSMAN_OPTION_ALLOW_NEGOTIATE_IMPLICIT_CREDENTIALS,
                    new WSManNativeApi.WSManDataDWord(1));
            }
            if (connectionInfo.UseUTF16)
            {
                SetWSManSessionOption(WSManNativeApi.WSManSessionOption.WSMAN_OPTION_UTF16, 1);
            }

            if (connectionInfo.SkipCACheck)
            {
                SetWSManSessionOption(WSManNativeApi.WSManSessionOption.WSMAN_OPTION_SKIP_CA_CHECK, 1);
            }

            if (connectionInfo.SkipCNCheck)
            {
                SetWSManSessionOption(WSManNativeApi.WSManSessionOption.WSMAN_OPTION_SKIP_CN_CHECK, 1);
            }

            if (connectionInfo.SkipRevocationCheck)
            {
                SetWSManSessionOption(WSManNativeApi.WSManSessionOption.WSMAN_OPTION_SKIP_REVOCATION_CHECK, 1);
            }

            if (connectionInfo.IncludePortInSPN)
            {
                SetWSManSessionOption(WSManNativeApi.WSManSessionOption.WSMAN_OPTION_ENABLE_SPN_SERVER_PORT, 1);
            }

            // Set use interactive token flag based on EnableNetworkAccess property.
            SetWSManSessionOption(WSManNativeApi.WSManSessionOption.WSMAN_OPTION_USE_INTERACTIVE_TOKEN,
                (connectionInfo.EnableNetworkAccess) ? 1 : 0);

            // set UI Culture for this session from current thread's UI Culture
            string currentUICulture = connectionInfo.UICulture.Name;
            if (!string.IsNullOrEmpty(currentUICulture))
            {
                // WSMan API cannot handle empty culture names
                SetWSManSessionOption(WSManNativeApi.WSManSessionOption.WSMAN_OPTION_UI_LANGUAGE, currentUICulture);
            }

            // set Culture for this session from current thread's Culture
            string currentCulture = connectionInfo.Culture.Name;
            if (!string.IsNullOrEmpty(currentCulture))
            {
                SetWSManSessionOption(WSManNativeApi.WSManSessionOption.WSMAN_OPTION_LOCALE, currentCulture);
            }

            // set the PowerShell specific default client timeouts
            SetDefaultTimeOut(connectionInfo.OperationTimeout);
            SetConnectTimeOut(connectionInfo.OpenTimeout);
            SetCloseTimeOut(connectionInfo.CancelTimeout);
            SetSignalTimeOut(connectionInfo.CancelTimeout);
        }
        private void Initialize(Uri connectionUri, WSManConnectionInfo connectionInfo)
        {
            WSManNativeApi.BaseWSManAuthenticationCredentials credentials;
            int num2;
            this._connectionInfo = connectionInfo;
            bool isSSLSpecified = false;
            string originalString = connectionUri.OriginalString;
            if ((connectionUri == connectionInfo.ConnectionUri) && connectionInfo.UseDefaultWSManPort)
            {
                originalString = WSManConnectionInfo.GetConnectionString(connectionInfo.ConnectionUri, out isSSLSpecified);
            }
            string str2 = string.Empty;
            if (PSSessionConfigurationData.IsServerManager)
            {
                str2 = ";MSP=7a83d074-bb86-4e52-aa3e-6cc73cc066c8";
            }
            if (string.IsNullOrEmpty(connectionUri.Query))
            {
                originalString = string.Format(CultureInfo.InvariantCulture, "{0}?PSVersion={1}{2}", new object[] { originalString.TrimEnd(new char[] { '/' }), PSVersionInfo.PSVersion, str2 });
            }
            else
            {
                originalString = string.Format(CultureInfo.InvariantCulture, "{0};PSVersion={1}{2}", new object[] { originalString, PSVersionInfo.PSVersion, str2 });
            }
            if (connectionInfo.CertificateThumbprint != null)
            {
                credentials = new WSManNativeApi.WSManCertificateThumbprintCredentials(connectionInfo.CertificateThumbprint);
            }
            else
            {
                string userName = null;
                SecureString pwd = null;
                if ((connectionInfo.Credential != null) && !string.IsNullOrEmpty(connectionInfo.Credential.UserName))
                {
                    userName = connectionInfo.Credential.UserName;
                    pwd = connectionInfo.Credential.Password;
                }
                WSManNativeApi.WSManUserNameAuthenticationCredentials credentials2 = new WSManNativeApi.WSManUserNameAuthenticationCredentials(userName, pwd, connectionInfo.WSManAuthenticationMechanism);
                credentials = credentials2;
            }
            WSManNativeApi.WSManUserNameAuthenticationCredentials authCredentials = null;
            if (connectionInfo.ProxyCredential != null)
            {
                WSManNativeApi.WSManAuthenticationMechanism authMechanism = WSManNativeApi.WSManAuthenticationMechanism.WSMAN_FLAG_AUTH_NEGOTIATE;
                string str5 = null;
                SecureString password = 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))
                {
                    str5 = connectionInfo.ProxyCredential.UserName;
                    password = connectionInfo.ProxyCredential.Password;
                }
                authCredentials = new WSManNativeApi.WSManUserNameAuthenticationCredentials(str5, password, authMechanism);
            }
            WSManNativeApi.WSManProxyInfo info = (connectionInfo.ProxyAccessType == ProxyAccessType.None) ? null : new WSManNativeApi.WSManProxyInfo(connectionInfo.ProxyAccessType, authCredentials);
            int errorCode = 0;
            try
            {
                errorCode = WSManNativeApi.WSManCreateSession(wsManApiStaticData.WSManAPIHandle, originalString, 0, (IntPtr) credentials.GetMarshalledObject(), (info == null) ? IntPtr.Zero : ((IntPtr) info), ref this.wsManSessionHandle);
            }
			catch(Exception ex)
			{

			}
            finally
            {
                if (authCredentials != null)
                {
                    authCredentials.Dispose();
                }
                if (info != null)
                {
                    info.Dispose();
                }
                if (credentials != null)
                {
                    credentials.Dispose();
                }
            }
            if (errorCode != 0)
            {
                PSInvalidOperationException exception = new PSInvalidOperationException(WSManNativeApi.WSManGetErrorMessage(wsManApiStaticData.WSManAPIHandle, errorCode));
                throw exception;
            }
            WSManNativeApi.WSManGetSessionOptionAsDword(this.wsManSessionHandle, WSManNativeApi.WSManSessionOption.WSMAN_OPTION_SHELL_MAX_DATA_SIZE_PER_MESSAGE_KB, out num2);
            base.Fragmentor.FragmentSize = num2 << 10;
            WSManNativeApi.WSManGetSessionOptionAsDword(this.wsManSessionHandle, WSManNativeApi.WSManSessionOption.WSMAN_OPTION_MAX_RETRY_TIME, out this.maxRetryTime);
            base.dataToBeSent.Fragmentor = base.Fragmentor;
            this.noCompression = !connectionInfo.UseCompression;
            this.noMachineProfile = connectionInfo.NoMachineProfile;
            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)
            {
                errorCode = 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);
            }
            if (connectionInfo.IncludePortInSPN)
            {
                this.SetWSManSessionOption(WSManNativeApi.WSManSessionOption.WSMAN_OPTION_ENABLE_SPN_SERVER_PORT, 1);
            }
            this.SetWSManSessionOption(WSManNativeApi.WSManSessionOption.WSMAN_OPTION_USE_INTERACTIVE_TOKEN, connectionInfo.EnableNetworkAccess ? 1 : 0);
            string name = connectionInfo.UICulture.Name;
            if (!string.IsNullOrEmpty(name))
            {
                this.SetWSManSessionOption(WSManNativeApi.WSManSessionOption.WSMAN_OPTION_UI_LANGUAGE, name);
            }
            string str9 = connectionInfo.Culture.Name;
            if (!string.IsNullOrEmpty(str9))
            {
                this.SetWSManSessionOption(WSManNativeApi.WSManSessionOption.WSMAN_OPTION_LOCALE, str9);
            }
            this.SetDefaultTimeOut(connectionInfo.OperationTimeout);
            this.SetConnectTimeOut(connectionInfo.OpenTimeout);
            this.SetCloseTimeOut(connectionInfo.CancelTimeout);
            this.SetSignalTimeOut(connectionInfo.CancelTimeout);
        }