/// <summary>
        /// Initializes Connection Host Attributes.
        /// </summary>
        /// <param name="HostAddress">String Value of Host Address.</param>
        /// <param name="HostPort">Host port as positive integer.</param>
        /// <param name="TimeOut">Connection Timeout in Seconds.</param>
        private void InitializeHost(String HostAddress, int HostPort, int TimeOut)
        {
            Logger.Instance.Log("PayPal.Payments.Communication.PaymentConnection.InitializeHost(String,int,int): Entered.",
                                PayflowConstants.SEVERITY_DEBUG);

            if (HostAddress != null && HostAddress.Length > 0)
            {
                mHostAddress = HostAddress;
                Logger.Instance.Log("PayPal.Payments.Communication.PaymentConnection.InitializeHost(String,int,int): HostAddress = " + mHostAddress,
                                    PayflowConstants.SEVERITY_INFO);
            }
            else
            {
                ErrorObject NullHostError = PayflowUtility.PopulateCommError(PayflowConstants.E_NULL_HOST_STRING, null,
                                                                             PayflowConstants.SEVERITY_FATAL, IsXmlPayRequest,
                                                                             null);
                if (!ConnContext.IsCommunicationErrorContained(NullHostError))
                {
                    ConnContext.AddError(NullHostError);
                }
            }

            mHostPort = HostPort;
            Logger.Instance.Log("PayPal.Payments.Communication.PaymentConnection.InitializeHost(String,int,int): HostPort = " + mHostPort.ToString(),
                                PayflowConstants.SEVERITY_INFO);
            mConnectionTimeOut = TimeOut;
            Logger.Instance.Log("PayPal.Payments.Communication.PaymentConnection.InitializeHost(String,int,int): Exiting.",
                                PayflowConstants.SEVERITY_DEBUG);
        }
        /// <summary>
        ///     Initializes Connection Host Attributes.
        /// </summary>
        /// <param name="hostAddress">String Value of Host Address.</param>
        /// <param name="hostPort">Host port as positive integer.</param>
        /// <param name="timeOut">Connection Timeout in Seconds.</param>
        private void InitializeHost(string hostAddress, int hostPort, int timeOut)
        {
            Logger.Instance.Log(
                "PayPal.Payments.Communication.PaymentConnection.InitializeHost(String,int,int): Entered.",
                PayflowConstants.SeverityDebug);

            if (hostAddress != null && hostAddress.Length > 0)
            {
                _mHostAddress = hostAddress;
                Logger.Instance.Log(
                    "PayPal.Payments.Communication.PaymentConnection.InitializeHost(String,int,int): HostAddress = " +
                    _mHostAddress,
                    PayflowConstants.SeverityInfo);
            }
            else
            {
                var nullHostError = PayflowUtility.PopulateCommError(PayflowConstants.ENullHostString, null,
                                                                     PayflowConstants.SeverityFatal, IsXmlPayRequest,
                                                                     null);
                if (!ConnContext.IsCommunicationErrorContained(nullHostError))
                {
                    ConnContext.AddError(nullHostError);
                }
            }

            _mHostPort = hostPort;
            Logger.Instance.Log(
                "PayPal.Payments.Communication.PaymentConnection.InitializeHost(String,int,int): HostPort = " +
                _mHostPort,
                PayflowConstants.SeverityInfo);
            TimeOut = timeOut;
            Logger.Instance.Log(
                "PayPal.Payments.Communication.PaymentConnection.InitializeHost(String,int,int): Exiting.",
                PayflowConstants.SeverityDebug);
        }
        /// <summary>
        ///     Receives the transaction response from
        ///     the server.
        /// </summary>
        /// <returns>String Value of Response.</returns>
        public async Task <string> ReceiveResponseAsync()
        {
            Logger.Instance.Log("PayPal.Payments.Communication.PaymentConnection.ReceiveResponse(): Entered.",
                                PayflowConstants.SeverityDebug);
            var response = PayflowConstants.EmptyString;

            try
            {
                var serverResponse = await _mServerConnection.GetResponseAsync();

                var responseStream = serverResponse.GetResponseStream();
                RequestId = serverResponse.Headers.Get(PayflowConstants.PayflowheaderRequestId);
                Logger.Instance.Log(
                    "PayPal.Payments.Communication.PaymentConnection.ReceiveResponse(): Obtained RequestId = " +
                    RequestId,
                    PayflowConstants.SeverityInfo);

                // v4.3.1 - changed stream handling due to issue with code below not returning a complete
                // stream.//read the stream in bytes
                //long RespLen = ServerResponse.ContentLength ;
                //Byte[] RespByteBuffer = new byte[RespLen];
                //ResponseStream.Read (RespByteBuffer,0,Convert.ToInt32 (RespLen));
                //UTF8Encoding UtfEncoding = new UTF8Encoding ();
                //Response = UtfEncoding.GetString(RespByteBuffer);

                response = await new StreamReader(serverResponse.GetResponseStream()).ReadToEndAsync();

                Logger.Instance.Log(
                    "PayPal.Payments.Communication.PaymentConnection.ReceiveResponse(): Obtained Response.",
                    PayflowConstants.SeverityInfo);
                responseStream.Close();
                _mServerConnection = null;
            }
            catch (Exception ex)
            {
                var addlMessage = "Input Server Uri = " + _mServerUri.AbsoluteUri;
                if (IsProxy)
                {
                    addlMessage += " Input Proxy info = " + _mProxyInfo.Address;
                }
                var initError = PayflowUtility.PopulateCommError(PayflowConstants.ETimeoutWaitResp, ex,
                                                                 PayflowConstants.SeverityError, IsXmlPayRequest,
                                                                 addlMessage);
                if (!ConnContext.IsCommunicationErrorContained(initError))
                {
                    ConnContext.AddError(initError);
                }
            }
            finally
            {
                Logger.Instance.Log("PayPal.Payments.Communication.PaymentConnection.ReceiveResponse(): Exiting.",
                                    PayflowConstants.SeverityDebug);
            }

            return(response);
        }
        /// <summary>
        /// Receives the transaction response from
        /// the server.
        /// </summary>
        /// <returns>String Value of Response.</returns>
        public String ReceiveResponse()
        {
            Logger.Instance.Log("PayPal.Payments.Communication.PaymentConnection.ReceiveResponse(): Entered.",
                                PayflowConstants.SEVERITY_DEBUG);
            String Response = PayflowConstants.EMPTY_STRING;

            try
            {
                HttpWebResponse ServerResponse = (HttpWebResponse)mServerConnection.GetResponse();
                Stream          ResponseStream = ServerResponse.GetResponseStream();
                mRequestId = ServerResponse.Headers.Get(PayflowConstants.PAYFLOWHEADER_REQUEST_ID);
                Logger.Instance.Log("PayPal.Payments.Communication.PaymentConnection.ReceiveResponse(): Obtained RequestId = " + mRequestId,
                                    PayflowConstants.SEVERITY_INFO);

                // v4.3.1 - changed stream handling due to issue with code below not returning a complete
                // stream.//read the stream in bytes
                //long RespLen = ServerResponse.ContentLength ;
                //Byte[] RespByteBuffer = new byte[RespLen];
                //ResponseStream.Read (RespByteBuffer,0,Convert.ToInt32 (RespLen));
                //UTF8Encoding UtfEncoding = new UTF8Encoding ();
                //Response = UtfEncoding.GetString(RespByteBuffer);

                Response = new StreamReader(ServerResponse.GetResponseStream()).ReadToEnd();

                Logger.Instance.Log("PayPal.Payments.Communication.PaymentConnection.ReceiveResponse(): Obtained Response.",
                                    PayflowConstants.SEVERITY_INFO);
                ResponseStream.Close();
                mServerConnection = null;
            }
            catch (Exception Ex)
            {
                String AddlMessage = "Input Server Uri = " + mServerUri.AbsoluteUri;
                if (IsProxy)
                {
                    AddlMessage += " Input Proxy info = " + mProxyInfo.Address.ToString();
                }
                ErrorObject InitError = PayflowUtility.PopulateCommError(PayflowConstants.E_TIMEOUT_WAIT_RESP, Ex,
                                                                         PayflowConstants.SEVERITY_ERROR, IsXmlPayRequest,
                                                                         AddlMessage);
                if (!ConnContext.IsCommunicationErrorContained(InitError))
                {
                    ConnContext.AddError(InitError);
                }
            }
            finally
            {
                Logger.Instance.Log("PayPal.Payments.Communication.PaymentConnection.ReceiveResponse(): Exiting.",
                                    PayflowConstants.SEVERITY_DEBUG);
            }
            return(Response);
        }
        /// <summary>
        ///     Initialized the Server Uri object from
        ///     available connection attributes.
        /// </summary>
        private void InitServerUri()
        {
            Logger.Instance.Log("PayPal.Payments.Communication.PaymentConnection.InitServerUri(String): Entered.",
                                PayflowConstants.SeverityDebug);

            var serverUriBuilder = new UriBuilder();

            try
            {
                serverUriBuilder.Host   = _mHostAddress;
                serverUriBuilder.Scheme = "https";
                serverUriBuilder.Port   = _mHostPort;
                _mServerUri             = serverUriBuilder.Uri;
            }
            catch (Exception ex)
            {
                var addlMessage = "Input Server Uri = " + serverUriBuilder.Scheme + "://" + serverUriBuilder.Host +
                                  ":" + serverUriBuilder.Port;
                if (ex is UriFormatException && IsProxy)
                {
                    addlMessage  += " Input Proxy info = http://" + _mProxyAddress;
                    _mProxyStatus = false;
                }
                else if (IsProxy)
                {
                    addlMessage += " Input Proxy info = " + _mProxyInfo.Address;
                }

                var initError = PayflowUtility.PopulateCommError(PayflowConstants.ESokConnFailed, ex,
                                                                 PayflowConstants.SeverityError, IsXmlPayRequest,
                                                                 addlMessage);
                if (!ConnContext.IsCommunicationErrorContained(initError))
                {
                    ConnContext.AddError(initError);
                }
            }
            finally
            {
                Logger.Instance.Log("PayPal.Payments.Communication.PaymentConnection.InitServerUri(String): Exiting.",
                                    PayflowConstants.SeverityDebug);
            }
        }
        /// <summary>
        /// Initialized the Server Uri object from
        /// available connection attributes.
        /// </summary>
        private void InitServerUri()
        {
            Logger.Instance.Log("PayPal.Payments.Communication.PaymentConnection.InitServerUri(String): Entered.",
                                PayflowConstants.SEVERITY_DEBUG);

            UriBuilder ServerUriBuilder = new UriBuilder();

            try
            {
                ServerUriBuilder.Host   = mHostAddress;
                ServerUriBuilder.Scheme = "https";
                ServerUriBuilder.Port   = mHostPort;
                mServerUri = ServerUriBuilder.Uri;
            }
            catch (Exception Ex)
            {
                String AddlMessage = "Input Server Uri = " + ServerUriBuilder.Scheme + "://" + ServerUriBuilder.Host + ":" + ServerUriBuilder.Port;
                if (Ex is System.UriFormatException && IsProxy)
                {
                    AddlMessage += " Input Proxy info = http://" + mProxyAddress;
                    mProxyStatus = false;
                }
                else if (IsProxy)
                {
                    AddlMessage += " Input Proxy info = " + mProxyInfo.Address.ToString();
                }
                ErrorObject InitError = PayflowUtility.PopulateCommError(PayflowConstants.E_SOK_CONN_FAILED, Ex,
                                                                         PayflowConstants.SEVERITY_ERROR, IsXmlPayRequest,
                                                                         AddlMessage);
                if (!ConnContext.IsCommunicationErrorContained(InitError))
                {
                    ConnContext.AddError(InitError);
                }
            }
            finally
            {
                Logger.Instance.Log("PayPal.Payments.Communication.PaymentConnection.InitServerUri(String): Exiting.",
                                    PayflowConstants.SEVERITY_DEBUG);
            }
        }
        /// <summary>
        ///     Sends the request to the server.
        /// </summary>
        /// <param name="request">String Value of request.</param>
        /// <returns>True if success, False otherwise.</returns>
        public async Task <bool> SendToServer(string request)
        {
            Logger.Instance.Log("PayPal.Payments.Communication.PaymentConnection.SendToServer(String): Entered.",
                                PayflowConstants.SeverityDebug);
            var retVal = false;

            // Uncomment this line to test this SDK in QA.  This will override the certificate check where the
            // host URL does not match the server certificate causing the exception:
            //
            // "The underlying connection was closed: Could not establish trust relationship with remote server."
            //
            // See notes in LocalPolicy.cs in the Utility directory.
            //
            //System.Net.ServicePointManager.CertificatePolicy = new LocalPolicy(ref mContext,IsXmlPayRequest);

            try
            {
                var encoding = new ASCIIEncoding();
                if (request != null)
                {
                    var paramListBytes = encoding.GetBytes(request);
                    _mServerConnection.ContentLength = paramListBytes.Length;
                    var reqStram = _mServerConnection.GetRequestStream();
                    await reqStram.WriteAsync(paramListBytes, 0, paramListBytes.Length);

                    reqStram.Close();
                    retVal = true;

                    var headerKeys = _mServerConnection.Headers.AllKeys;
                    if (headerKeys != null)
                    {
                        var keysLen = headerKeys.GetLength(0);
                        int index;
                        Logger.Instance.Log("++++++++++++++++++++++", PayflowConstants.SeverityDebug);
                        for (index = 0; index < keysLen; index++)
                        {
                            //if (!(HeaderKeys[index].Equals(PayflowConstants.PAYFLOWHEADER_CLIENT_VERSION)))
                            //	 || HeaderKeys[index].Equals(PayflowConstants.PAYFLOWHEADER_CLIENT_TYPE)))
                            //{
                            Logger.Instance.Log(
                                "HTTP Header: " + headerKeys[index] + ": " +
                                _mServerConnection.Headers.Get(headerKeys[index]), PayflowConstants.SeverityDebug);
                        }
                        //}
                        Logger.Instance.Log("++++++++++++++++++++++", PayflowConstants.SeverityDebug);
                    }
                }
                else
                {
                    var initError = PayflowUtility.PopulateCommError(PayflowConstants.EEmptyParamList, null,
                                                                     PayflowConstants.SeverityError, IsXmlPayRequest,
                                                                     null);
                    if (!ConnContext.IsCommunicationErrorContained(initError))
                    {
                        ConnContext.AddError(initError);
                    }
                }
            }
            catch (Exception ex)
            {
                var addlMessage = "Input Server Uri = " + _mServerUri.AbsoluteUri;
                if (IsProxy)
                {
                    addlMessage += " Input Proxy info = " + _mProxyInfo.Address;
                }
                var initError = PayflowUtility.PopulateCommError(PayflowConstants.ESokConnFailed, ex,
                                                                 PayflowConstants.SeverityError, IsXmlPayRequest,
                                                                 addlMessage);
                if (!ConnContext.IsCommunicationErrorContained(initError))
                {
                    ConnContext.AddError(initError);
                }
                Logger.Instance.Log("PayPal.Payments.Communication.PaymentConnection.SendToServer(String): InitError: ",
                                    PayflowConstants.SeverityDebug);
            }
            finally
            {
                Logger.Instance.Log("PayPal.Payments.Communication.PaymentConnection.SendToServer(String): Exiting.",
                                    PayflowConstants.SeverityDebug);
            }

            return(retVal);
        }
        /// <summary>
        ///     Initializes the Server Connection.
        /// </summary>
        /// <returns>True if success, False otherwise.</returns>
        public bool ConnectToServer()
        {
            Logger.Instance.Log("PayPal.Payments.Communication.PaymentConnection.ConnectToServer(String): Entered.",
                                PayflowConstants.SeverityDebug);
            var retVal = false;

            try
            {
                //Initialize Server Uri.
                Logger.Instance.Log(
                    "PayPal.Payments.Communication.PaymentConnection.ConnectToServer(String): Initializing Server Uri.",
                    PayflowConstants.SeverityInfo);
                InitServerUri();
                Logger.Instance.Log(
                    "PayPal.Payments.Communication.PaymentConnection.ConnectToServer(String): Initialized Server Uri = " +
                    _mServerUri.AbsoluteUri,
                    PayflowConstants.SeverityInfo);

                //Create Connection object & Set Connection Attributes
                Logger.Instance.Log(
                    "PayPal.Payments.Communication.PaymentConnection.ConnectToServer(String): Initializing Connection Attributes.",
                    PayflowConstants.SeverityInfo);
                CreateConnection();
                if (_mServerConnection != null)
                {
                    if (_mProxyStatus)
                    {
                        retVal = true;
                        Logger.Instance.Log(
                            "PayPal.Payments.Communication.PaymentConnection.ConnectToServer(String): Connection Created.",
                            PayflowConstants.SeverityInfo);
                    }
                    else
                    {
                        retVal = false;
                        Logger.Instance.Log(
                            "PayPal.Payments.Communication.PaymentConnection.ConnectToServer(String): Connection Creation Failure: Incorrect Proxy Details.",
                            PayflowConstants.SeverityInfo);
                    }
                }
                else
                {
                    retVal = false;
                    Logger.Instance.Log(
                        "PayPal.Payments.Communication.PaymentConnection.ConnectToServer(String): Connection Creation Failure.",
                        PayflowConstants.SeverityInfo);
                }
            }
            catch (Exception ex)
            {
                var addlMessage = "Input Server Uri = " + _mServerUri.AbsoluteUri;
                if (IsProxy)
                {
                    addlMessage += " Input Proxy info = " + _mProxyInfo.Address;
                }
                var initError = PayflowUtility.PopulateCommError(PayflowConstants.ESokConnFailed, ex,
                                                                 PayflowConstants.SeverityError, IsXmlPayRequest,
                                                                 addlMessage);
                if (!ConnContext.IsCommunicationErrorContained(initError))
                {
                    ConnContext.AddError(initError);
                }
            }
            finally
            {
                Logger.Instance.Log("PayPal.Payments.Communication.PaymentConnection.ConnectToServer(String): Exiting.",
                                    PayflowConstants.SeverityDebug);
            }

            return(retVal);
        }
        /// <summary>
        ///     Initializes all the connection attributes and creates the connection.
        /// </summary>
        private void CreateConnection()
        {
            Logger.Instance.Log("PayPal.Payments.Communication.PaymentConnection.CreateConnection(): Entered.",
                                PayflowConstants.SeverityDebug);

            try
            {
                //Create Connection Object.
                _mServerConnection = (HttpWebRequest)WebRequest.Create(_mServerUri);
                // Create a new request to the above mentioned URL.
                // WebRequest mServerConnection = WebRequest.Create(mServerUri);

                //Set Connection Properties
                _mServerConnection.Method      = "POST";
                _mServerConnection.KeepAlive   = false;
                _mServerConnection.UserAgent   = PayflowConstants.UserAgent;
                _mServerConnection.ContentType = ContentType;
                _mServerConnection.Timeout     = (int)TimeOut;
                // Add request id in the header.
                _mServerConnection.Headers.Add(PayflowConstants.PayflowheaderRequestId, RequestId);
                var timeOut = TimeOut / 1000;
                _mServerConnection.Headers.Add(PayflowConstants.PayflowheaderTimeout, timeOut.ToString());

                if (IsProxy)
                {
                    if (_mProxyInfo == null)
                    {
                        InitProxyInfo();
                    }

                    //mServerConnection.Proxy = mProxyInfo;
                }
                else
                {
                    _mServerConnection.Proxy = WebRequest.DefaultWebProxy;
                }

                //Add VIT Headers
                if (ClientInfo != null)
                {
                    //Get the Hash map.
                    var clientInfoHash = ClientInfo.ClientInfoHash;
                    if (clientInfoHash != null && clientInfoHash.Count > 0)
                    {
                        foreach (DictionaryEntry headerKeyValue in clientInfoHash)
                        {
                            var valueObj = headerKeyValue.Value;
                            if (valueObj != null)
                            {
                                var    currHeader  = (ClientInfoHeader)valueObj;
                                var    hdrName     = currHeader.HeaderName;
                                var    hdrValueObj = currHeader.HeaderValue;
                                string hdrValueStr = null;
                                //Check if Header name is non-null, non-empty string.
                                var validHeaderName  = hdrName != null && hdrName.Length > 0;
                                var validHeaderValue = hdrValueObj != null;
                                //Check if Header value object is non-null, object.
                                if (validHeaderValue)
                                {
                                    hdrValueStr = currHeader.HeaderValue.ToString();
                                    //Check if the header value is non-null, non-empty.
                                    validHeaderValue = hdrValueStr != null && hdrValueStr.Length > 0;
                                }

                                //If all conditions are satisfied, then add header to request.
                                if (validHeaderName && validHeaderValue)
                                {
                                    try
                                    {
                                        _mServerConnection.Headers.Add(hdrName, hdrValueStr);
                                    }
                                    catch (Exception ex)
                                    {
                                        var addlMessage = "Invalid Client(Wrapper) Header: " + hdrName;
                                        var headerError = PayflowUtility.PopulateCommError(
                                            PayflowConstants.MessageWrapperheaderError, ex,
                                            PayflowConstants.SeverityWarn, IsXmlPayRequest,
                                            addlMessage);
                                        if (!ConnContext.IsCommunicationErrorContained(headerError))
                                        {
                                            ConnContext.AddError(headerError);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                //Added VIT Headers to the http request.
            }
            catch (Exception ex)
            {
                var addlMessage = "Input Server Uri = " + _mServerUri.AbsoluteUri;

                if (ex is UriFormatException && IsProxy)
                {
                    addlMessage  += " Input Proxy info = http://" + _mProxyAddress;
                    _mProxyStatus = false;
                }
                else if (IsProxy)
                {
                    addlMessage += " Input Proxy info = " + _mProxyInfo.Address;
                }

                var initError = PayflowUtility.PopulateCommError(PayflowConstants.ESokConnFailed, ex,
                                                                 PayflowConstants.SeverityError, IsXmlPayRequest,
                                                                 addlMessage);
                if (!ConnContext.IsCommunicationErrorContained(initError))
                {
                    ConnContext.AddError(initError);
                }
            }
            finally
            {
                Logger.Instance.Log("PayPal.Payments.Communication.PaymentConnection.CreateConnection(): Exiting.",
                                    PayflowConstants.SeverityDebug);
            }
        }
        /// <summary>
        /// Sends the request to the server.
        /// </summary>
        /// <param name="Request">String Value of request.</param>
        /// <returns>True if success, False otherwise.</returns>
        public bool SendToServer(String Request)
        {
            Logger.Instance.Log("PayPal.Payments.Communication.PaymentConnection.SendToServer(String): Entered.",
                                PayflowConstants.SEVERITY_DEBUG);
            bool RetVal = false;

            // Uncomment this line to test this SDK in QA.  This will override the certificate check where the
            // host URL does not match the server certificate causing the exception:
            //
            // "The underlying connection was closed: Could not establish trust relationship with remote server."
            //
            // See notes in LocalPolicy.cs in the Utility directory.
            //
            //System.Net.ServicePointManager.CertificatePolicy = new LocalPolicy(ref mContext,IsXmlPayRequest);

            try
            {
                ASCIIEncoding Encoding = new ASCIIEncoding();
                if (Request != null)
                {
                    Byte[] ParamListBytes = Encoding.GetBytes(Request);
                    mServerConnection.ContentLength = ParamListBytes.Length;
                    Stream ReqStram = mServerConnection.GetRequestStream();
                    ReqStram.Write(ParamListBytes, 0, ParamListBytes.Length);
                    ReqStram.Close();
                    RetVal = true;

                    String[] HeaderKeys = mServerConnection.Headers.AllKeys;
                    if (HeaderKeys != null)
                    {
                        int KeysLen = HeaderKeys.GetLength(0);
                        int index;
                        Logger.Instance.Log("++++++++++++++++++++++", PayflowConstants.SEVERITY_DEBUG);
                        for (index = 0; index < KeysLen; index++)
                        {
                            //if (!(HeaderKeys[index].Equals(PayflowConstants.PAYFLOWHEADER_CLIENT_VERSION)))
                            //	 || HeaderKeys[index].Equals(PayflowConstants.PAYFLOWHEADER_CLIENT_TYPE)))
                            //{
                            Logger.Instance.Log("HTTP Header: " + HeaderKeys[index] + ": " + mServerConnection.Headers.Get(HeaderKeys[index]), PayflowConstants.SEVERITY_DEBUG);
                            //}
                        }
                        Logger.Instance.Log("++++++++++++++++++++++", PayflowConstants.SEVERITY_DEBUG);
                    }
                }
                else
                {
                    ErrorObject InitError = PayflowUtility.PopulateCommError(PayflowConstants.E_EMPTY_PARAM_LIST, null,
                                                                             PayflowConstants.SEVERITY_ERROR, IsXmlPayRequest,
                                                                             null);
                    if (!ConnContext.IsCommunicationErrorContained(InitError))
                    {
                        ConnContext.AddError(InitError);
                    }
                }
            }
            catch (Exception Ex)
            {
                String AddlMessage = "Input Server Uri = " + mServerUri.AbsoluteUri;
                if (IsProxy)
                {
                    AddlMessage += " Input Proxy info = " + mProxyInfo.Address.ToString();
                }
                ErrorObject InitError = PayflowUtility.PopulateCommError(PayflowConstants.E_SOK_CONN_FAILED, Ex,
                                                                         PayflowConstants.SEVERITY_ERROR, IsXmlPayRequest,
                                                                         AddlMessage);
                if (!ConnContext.IsCommunicationErrorContained(InitError))
                {
                    ConnContext.AddError(InitError);
                }
                Logger.Instance.Log("PayPal.Payments.Communication.PaymentConnection.SendToServer(String): InitError: ", PayflowConstants.SEVERITY_DEBUG);
            }
            finally
            {
                Logger.Instance.Log("PayPal.Payments.Communication.PaymentConnection.SendToServer(String): Exiting.",
                                    PayflowConstants.SEVERITY_DEBUG);
            }
            return(RetVal);
        }
        /// <summary>
        /// Initializes the Server Connection.
        /// </summary>
        /// <returns>True if success, False otherwise.</returns>
        public bool ConnectToServer()
        {
            Logger.Instance.Log("PayPal.Payments.Communication.PaymentConnection.ConnectToServer(String): Entered.",
                                PayflowConstants.SEVERITY_DEBUG);
            bool RetVal = false;

            try
            {
                //Initialize Server Uri.
                Logger.Instance.Log("PayPal.Payments.Communication.PaymentConnection.ConnectToServer(String): Initializing Server Uri.",
                                    PayflowConstants.SEVERITY_INFO);
                InitServerUri();
                Logger.Instance.Log("PayPal.Payments.Communication.PaymentConnection.ConnectToServer(String): Initialized Server Uri = " + mServerUri.AbsoluteUri,
                                    PayflowConstants.SEVERITY_INFO);

                //Create Connection object & Set Connection Attributes
                Logger.Instance.Log("PayPal.Payments.Communication.PaymentConnection.ConnectToServer(String): Initializing Connection Attributes.",
                                    PayflowConstants.SEVERITY_INFO);
                CreateConnection();
                if (mServerConnection != null)
                {
                    if (mProxyStatus)
                    {
                        RetVal = true;
                        Logger.Instance.Log("PayPal.Payments.Communication.PaymentConnection.ConnectToServer(String): Connection Created.",
                                            PayflowConstants.SEVERITY_INFO);
                    }
                    else
                    {
                        RetVal = false;
                        Logger.Instance.Log("PayPal.Payments.Communication.PaymentConnection.ConnectToServer(String): Connection Creation Failure: Incorrect Proxy Details.",
                                            PayflowConstants.SEVERITY_INFO);
                    }
                }
                else
                {
                    RetVal = false;
                    Logger.Instance.Log("PayPal.Payments.Communication.PaymentConnection.ConnectToServer(String): Connection Creation Failure.",
                                        PayflowConstants.SEVERITY_INFO);
                }
            }
            catch (Exception Ex)
            {
                String AddlMessage = "Input Server Uri = " + mServerUri.AbsoluteUri;
                if (IsProxy)
                {
                    AddlMessage += " Input Proxy info = " + mProxyInfo.Address.ToString();
                }
                ErrorObject InitError = PayflowUtility.PopulateCommError(PayflowConstants.E_SOK_CONN_FAILED, Ex,
                                                                         PayflowConstants.SEVERITY_ERROR, IsXmlPayRequest,
                                                                         AddlMessage);
                if (!ConnContext.IsCommunicationErrorContained(InitError))
                {
                    ConnContext.AddError(InitError);
                }
            }
            finally
            {
                Logger.Instance.Log("PayPal.Payments.Communication.PaymentConnection.ConnectToServer(String): Exiting.",
                                    PayflowConstants.SEVERITY_DEBUG);
            }
            return(RetVal);
        }
        /// <summary>
        /// Initializes all the connection attributes and creates the connection.
        /// </summary>
        private void CreateConnection()
        {
            Logger.Instance.Log("PayPal.Payments.Communication.PaymentConnection.CreateConnection(): Entered.",
                                PayflowConstants.SEVERITY_DEBUG);

            try
            {
                //Create Connection Object.

                // 03/06/2017 Added TLS 1.2 support for .NET 4.5 support.  Only TLS 1.2 is supported going forward.
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;  // | SecurityProtocolType.Tls11;
                mServerConnection = (HttpWebRequest)WebRequest.Create(mServerUri);
                // Create a new request to the above mentioned URL.
                // WebRequest mServerConnection = WebRequest.Create(mServerUri);

                //Set Connection Properties
                mServerConnection.Method      = "POST";
                mServerConnection.KeepAlive   = false;
                mServerConnection.UserAgent   = PayflowConstants.USER_AGENT;
                mServerConnection.ContentType = mContentType;
                mServerConnection.Timeout     = (int)mConnectionTimeOut;
                // Add request id in the header.
                mServerConnection.Headers.Add(PayflowConstants.PAYFLOWHEADER_REQUEST_ID, mRequestId);
                long TimeOut = mConnectionTimeOut / 1000;
                mServerConnection.Headers.Add(PayflowConstants.PAYFLOWHEADER_TIMEOUT, TimeOut.ToString());

                if (IsProxy)
                {
                    if (mProxyInfo == null)
                    {
                        InitProxyInfo();
                    }

                    //mServerConnection.Proxy = mProxyInfo;
                }
                else
                {
                    // added 09/02/2009, v4.33
                    // reference: http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.proxy.aspx
                    // sets the the global proxy to an empty proxy.
                    // mServerConnection.Proxy = GlobalProxySelection.GetEmptyWebProxy();
                    // GlobalProxySelection is deprecated, replaced with WebRequest.DefaultWebProxy v4.50 0-3/15/2016
                    WebRequest.DefaultWebProxy = null;
                    mServerConnection.Proxy    = WebRequest.DefaultWebProxy;
                }

                //Add VIT Headers
                if (mClientInfo != null)
                {
                    //Get the Hash map.
                    Hashtable ClientInfoHash = mClientInfo.ClientInfoHash;
                    if (ClientInfoHash != null && ClientInfoHash.Count > 0)
                    {
                        //Iterate through the hash map to add the
                        //appropriate headers.
                        foreach (DictionaryEntry HeaderKeyValue in ClientInfoHash)
                        {
                            Object ValueObj = HeaderKeyValue.Value;
                            if (ValueObj != null)
                            {
                                ClientInfoHeader CurrHeader  = (ClientInfoHeader)ValueObj;
                                String           HdrName     = CurrHeader.HeaderName;
                                Object           HdrValueObj = CurrHeader.HeaderValue;
                                String           HdrValueStr = null;
                                //Check if Header name is non-null, non-empty string.
                                bool ValidHeaderName  = (HdrName != null && HdrName.Length > 0);
                                bool ValidHeaderValue = (HdrValueObj != null);
                                //Check if Header value object is non-null, object.
                                if (ValidHeaderValue)
                                {
                                    HdrValueStr = CurrHeader.HeaderValue.ToString();
                                    //Check if the header value is non-null, non-empty.
                                    ValidHeaderValue = (HdrValueStr != null && HdrValueStr.Length > 0);
                                }

                                //If all conditions are satisfied, then add header to request.
                                if (ValidHeaderName && ValidHeaderValue)
                                {
                                    try
                                    {
                                        mServerConnection.Headers.Add(HdrName, HdrValueStr);
                                    }
                                    catch (Exception Ex)
                                    {
                                        string      AddlMessage = "Invalid Client(Wrapper) Header: " + HdrName;
                                        ErrorObject HeaderError = PayflowUtility.PopulateCommError(PayflowConstants.MESSAGE_WRAPPERHEADER_ERROR, Ex,
                                                                                                   PayflowConstants.SEVERITY_WARN, IsXmlPayRequest,
                                                                                                   AddlMessage);
                                        if (!ConnContext.IsCommunicationErrorContained(HeaderError))
                                        {
                                            ConnContext.AddError(HeaderError);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                //Added VIT Headers to the http request.
            }
            catch (Exception Ex)
            {
                String AddlMessage = "Input Server Uri = " + mServerUri.AbsoluteUri;

                if (Ex is System.UriFormatException && IsProxy)
                {
                    AddlMessage += " Input Proxy info = http://" + mProxyAddress;
                    mProxyStatus = false;
                }
                else if (IsProxy)
                {
                    AddlMessage += " Input Proxy info = " + mProxyInfo.Address.ToString();
                }
                ErrorObject InitError = PayflowUtility.PopulateCommError(PayflowConstants.E_SOK_CONN_FAILED, Ex,
                                                                         PayflowConstants.SEVERITY_ERROR, IsXmlPayRequest,
                                                                         AddlMessage);
                if (!ConnContext.IsCommunicationErrorContained(InitError))
                {
                    ConnContext.AddError(InitError);
                }
            }
            finally
            {
                Logger.Instance.Log("PayPal.Payments.Communication.PaymentConnection.CreateConnection(): Exiting.",
                                    PayflowConstants.SEVERITY_DEBUG);
            }
        }