public static ANetApiResponse PostData <TQ, TS>(AuthorizeNet.Environment env, TQ request)
            where TQ : ANetApiRequest
            where TS : ANetApiResponse
        {
            ANetApiResponse response = null;

            if (null == request)
            {
                throw new ArgumentNullException("request");
            }
            Logger.LogDebug("MerchantInfo->LoginId/TransactionKey: '{0}':'{1}'->{2}", request.merchantAuthentication.name, request.merchantAuthentication.ItemElementName, request.merchantAuthentication.Item);

            var    postUrl          = GetPostUrl(env);
            var    requestType      = typeof(TQ);
            string responseAsString = null;

            using (var clientHandler = new HttpClientHandler())
            {
                //TODO: clientHandler.Proxy = SetProxyIfRequested(clientHandler.Proxy);
                using (var client = new HttpClient(clientHandler))
                {
                    //set the http connection timeout
                    var httpConnectionTimeout = AuthorizeNet.Environment.getIntProperty(Constants.HttpConnectionTimeout);
                    client.Timeout = TimeSpan.FromMilliseconds(httpConnectionTimeout != 0 ? httpConnectionTimeout : Constants.HttpConnectionDefaultTimeout);

                    //set the time out to read/write from stream
                    //var httpReadWriteTimeout = AuthorizeNet.Environment.getIntProperty(Constants.HttpReadWriteTimeout);
                    //client.ReadWriteTimeout = (httpReadWriteTimeout != 0 ? httpReadWriteTimeout : Constants.HttpReadWriteDefaultTimeout);

                    var content     = new StringContent(XmlUtility.Serialize(request), Encoding.UTF8, "text/xml");
                    var webResponse = client.PostAsync(postUrl, content).Result;
                    Logger.LogDebug("Retrieving Response from Url: '{0}'", postUrl);
                    // Get the response
                    Logger.LogDebug("Received Response: '{0}'", webResponse);
                    responseAsString = webResponse.Content.ReadAsStringAsync().Result;
                    Logger.LogDebug("Response from Stream: '{0}'", responseAsString);
                }
            }
            if (null != responseAsString)
            {
                try
                {
                    // try deserializing to the expected response type
                    response = XmlUtility.Deserialize <TS>(responseAsString);
                }
                catch (Exception)
                {
                    // probably a bad response, try if this is an error response
                    response = XmlUtility.Deserialize <ANetApiResponse>(responseAsString);
                }

                //if error response
                if (response is ErrorResponse)
                {
                    response = response as ErrorResponse;
                }
            }

            return(response);
        }
        public static IWebProxy SetProxyIfRequested(IWebProxy proxy, AuthorizeNet.Environment env)
        {
            var          newProxy    = proxy as WebProxy;
            ICredentials credentials = null;

            if (env.HttpUseProxy)
            {
                var proxyUri = new Uri(string.Format("{0}://{1}:{2}", Constants.ProxyProtocol, env.HttpProxyHost, env.HttpProxyPort));
                if (!_proxySet)
                {
                    Logger.LogInformation(string.Format("Setting up proxy to URL: '{0}'", proxyUri));
                    _proxySet = true;
                }

                if (!string.IsNullOrEmpty(env.HttpsProxyUsername))
                {
                    //Set credentials
                    credentials = new NetworkCredential(env.HttpsProxyUsername, env.HttpsProxyPassword);
                }

                if (null == proxy || null == newProxy)
                {
                    if (credentials == null)
                    {
                        newProxy = new WebProxy(proxyUri);
                    }
                    else
                    {
                        newProxy = new WebProxy(proxyUri, true, null, credentials);
                    }
                }
            }
            return(newProxy ?? proxy);
        }
Ejemplo n.º 3
0
        public MainController(AuthorizeNet.Environment iEnvironment,
                              string iCurrencyCode,
                              string iTerminalID,
                              bool iSkipSignature,
                              bool iShowReceipt,
                              string iDeviceID,
                              string iSessionToken)
        {
            InitializeComponent();
            Application.Current.Exit  += new ExitEventHandler(this.OnApplicationExit);
            this.WindowStartupLocation = WindowStartupLocation.CenterScreen;
            this.sdkEnvironment        = iEnvironment;
            this.currencyCode          = iCurrencyCode;
            this.terminalID            = iTerminalID;
            this.skipSignature         = iSkipSignature;
            this.showReceipt           = iShowReceipt;
            this.sessionToken          = iSessionToken;
            this.deviceID = iDeviceID;

            Debug.Write("Session Token in Constructor" + iSessionToken);
            Random random = new Random();

            this.amount.Text = (random.Next(1, 1000)).ToString();
            this.launcher    = new SdkLauncher(iEnvironment, iCurrencyCode, iTerminalID, iSkipSignature, iShowReceipt);
            this.launcher.setMerchantInfo(merchantName, merchantID);
            this.launcher.enableLogging();
        }
        private static bool _proxySet;                     //= false;

        //static readonly bool UseProxy = AuthorizeNet.Environment.getBooleanProperty(Constants.HttpsUseProxy);
        //static readonly string ProxyHost = AuthorizeNet.Environment.GetProperty(Constants.HttpsProxyHost);
        //static readonly int ProxyPort = AuthorizeNet.Environment.getIntProperty(Constants.HttpsProxyPort);

        private static Uri GetPostUrl(AuthorizeNet.Environment env)
        {
            var postUrl = new Uri(env.XmlBaseUrl + "/xml/v1/request.api");

            Logger.LogDebug("Creating PostRequest Url: '{0}'", postUrl);

            return(postUrl);
        }
Ejemplo n.º 5
0
        private static Uri GetPostUrl(AuthorizeNet.Environment env)
        {
            var postUrl = new Uri(env.getXmlBaseUrl() + "/xml/v1/request.api");

            Logger.debug(string.Format("Creating PostRequest Url: '{0}'", postUrl));

            return(postUrl);
        }
Ejemplo n.º 6
0
        protected static TS ExecuteTestRequestWithFailure <TQ, TS, TT>(TQ request, AuthorizeNet.Environment execEnvironment = null)
            where TQ : ANetApiRequest
            where TS : ANetApiResponse
            where TT : ApiOperationBase <TQ, TS>
        {
            TS response = ExecuteTestRequest <TQ, TS, TT>(false, request, execEnvironment);

            return(response);
        }
Ejemplo n.º 7
0
        public void Execute(AuthorizeNet.Environment environment = null)
        {
            BeforeExecute();

            if (Guid.Empty == this.RequestId)
            {
                this.RequestId = Guid.NewGuid();
            }

            //Logger.debug(string.Format(CultureInfo.InvariantCulture, "Executing Request:'{0}'", XmlUtility.GetXml(GetApiRequest())));

            if (null == environment)
            {
                environment = ApiOperationBase <ANetApiRequest, ANetApiResponse> .RunEnvironment;
            }
            if (null == environment)
            {
                throw new ArgumentException(NullEnvironmentErrorMessage);
            }

            var httpApiResponse = HttpUtility.PostData <TQ, TS>(environment, GetApiRequest(), this.RequestId);

            if (null != httpApiResponse)
            {
                Logger.debug(string.Format(CultureInfo.InvariantCulture, "Received Response:'{0}' for request:'{1}'", httpApiResponse, GetApiRequest()));
                if (httpApiResponse.GetType() == _responseClass)
                {
                    var response = (TS)httpApiResponse;
                    SetApiResponse(response);
                    Logger.debug(string.Format(CultureInfo.InvariantCulture, "Setting response: '{0}'", response));
                }
                else if (httpApiResponse.GetType() == typeof(AuthorizeNet.Api.Controllers.Bases.ErrorResponse))
                {
                    SetErrorResponse(httpApiResponse);
                    Logger.debug(string.Format(CultureInfo.InvariantCulture, "Received ErrorResponse:'{0}'", httpApiResponse));
                }
                else
                {
                    SetErrorResponse(httpApiResponse);
                    Logger.error(string.Format(CultureInfo.InvariantCulture, "Invalid response:'{0}'", httpApiResponse));
                }
                Logger.debug(string.Format("Response obtained: {0}", GetApiResponse()));
                SetResultStatus();
            }
            else
            {
                Logger.debug(string.Format(CultureInfo.InvariantCulture, "Got a 'null' Response for request:'{0}'\n", GetApiRequest()));
            }
            AfterExecute();
        }
        public void SampleCodeCreateCustomerProfileFromTransaction()
        {
            LogHelper.info(Logger, "Sample createCustomerProfileFromTransaction");
            //var createRequest = new createCustomerProfileFromTransactionRequest();

            //ApiOperationBase<ANetApiRequest, ANetApiResponse>.MerchantAuthentication = CustomMerchantAuthenticationType;
            //ApiOperationBase<ANetApiRequest, ANetApiResponse>.RunEnvironment = TestEnvironment;

            //setup transaction to use
            var transactionId = GetTransactionId();
            //createRequest.refId = "11111111"; //request.RequestId;
            //createRequest.transId = transactionId.ToString(CultureInfo.InvariantCulture); // "60038686958"; // request.TransactionCode;
            //createRequest.merchantAuthentication = CustomMerchantAuthenticationType;
            var apiRequest = new APICore.createCustomerProfileFromTransactionRequest();

            apiRequest.refId = "11111111"; // request.RequestId;
            apiRequest.merchantAuthentication = new APICore.merchantAuthenticationType
            {
                name            = UnitTestData.GetPropertyFromNames(AuthorizeNet.Util.Constants.EnvApiLoginid, AuthorizeNet.Util.Constants.PropApiLoginid),
                ItemElementName = APICore.ItemChoiceType.transactionKey,
                Item            = UnitTestData.GetPropertyFromNames(AuthorizeNet.Util.Constants.EnvTransactionKey, AuthorizeNet.Util.Constants.PropTransactionKey),
            };
            apiRequest.transId = transactionId.ToString();
            AuthorizeNet.Environment environment = AuthorizeNet.Environment.SANDBOX;
            var transactionRequest = new CreateCustomerProfilePaymentFromTransaction();
            var createResponse     = (APICore.createCustomerProfileResponse)transactionRequest.CreateProfileFromTransaction(TestEnvironment, apiRequest);

            //validate
            Assert.NotNull(createResponse);
            Assert.NotNull(createResponse.messages);
            Assert.AreEqual(messageTypeEnum.Ok, createResponse.messages.resultCode);
            Assert.NotNull(createResponse.customerProfileId);
            Assert.NotNull(createResponse.customerPaymentProfileIdList);
            Assert.AreNotEqual(0, createResponse.customerPaymentProfileIdList.Length);

            long customerProfileId;

            long.TryParse(createResponse.customerProfileId, out customerProfileId);
            Assert.AreNotEqual(0, customerProfileId);

            long customerPaymentProfileId;

            long.TryParse(createResponse.customerPaymentProfileIdList[0], out customerPaymentProfileId);
            Assert.AreNotEqual(0, customerPaymentProfileId);
            //if shipping profile is added, shipping profile id will be retrieved too
        }
Ejemplo n.º 9
0
        public async Task ExecuteAsync(AuthorizeNet.Environment environment = null)
        {
            BeforeExecute();

            if (null == environment)
            {
                environment = ApiOperationBase <ANetApiRequest, ANetApiResponse> .RunEnvironment;
            }
            if (null == environment)
            {
                throw new ArgumentException(NullEnvironmentErrorMessage);
            }

            var httpApiResponse = await HttpUtility.PostDataAsync <TQ, TS>(environment, GetApiRequest()).ConfigureAwait(false);

            if (null != httpApiResponse)
            {
                Logger.LogDebug("Received Response:'{0}' for request:'{1}'", httpApiResponse, GetApiRequest());
                if (httpApiResponse.GetType() == _responseClass)
                {
                    var response = (TS)httpApiResponse;
                    SetApiResponse(response);
                    Logger.LogDebug("Setting response: '{0}'", response);
                }
                else if (httpApiResponse.GetType() == typeof(ErrorResponse))
                {
                    SetErrorResponse(httpApiResponse);
                    Logger.LogDebug("Received ErrorResponse:'{0}'", httpApiResponse);
                }
                else
                {
                    SetErrorResponse(httpApiResponse);
                    Logger.LogError("Invalid response:'{0}'", httpApiResponse);
                }
                Logger.LogDebug("Response obtained: {0}", GetApiResponse());
                SetResultStatus();
            }
            else
            {
                Logger.LogDebug("Got a 'null' Response for request:'{0}'\n", GetApiRequest());
            }
            AfterExecute();
        }
Ejemplo n.º 10
0
        private static TS ExecuteTestRequest <TQ, TS, TT>(bool successExpected, TQ request, AuthorizeNet.Environment execEnvironment = null)
            where TQ : ANetApiRequest
            where TS : ANetApiResponse
            where TT : ApiOperationBase <TQ, TS>
        {
            LogHelper.debug(Logger, "Created {0} Request: '{1}'", request.GetType(), request);

            TS response   = null;
            TT controller = null;

            _errorResponse = null;
            var controllerClass = typeof(TT);

            try {
                var parameters       = new object[] { request };
                var controllerObject = Activator.CreateInstance(controllerClass, parameters);
                if (controllerObject is TT)
                {
                    controller = (TT)controllerObject;
                }
                if (null != controller)
                {
                    ANetApiResponse baseResponse = controller.ExecuteWithApiResponse(execEnvironment);
                    LogHelper.info(Logger, "{0} ResultCode: {1}", controllerClass, controller.GetResultCode());
                    LogHelper.info(Logger, "{0} Results:    {1}", controllerClass, controller.GetResults());
                    response = (TS)baseResponse;
                }
                else
                {
                    LogHelper.error(Logger, "Unable to instantiate Controller: '{0}'", controllerClass);
                }
            } catch (Exception e) {
                LogHelper.error(Logger, "Exception : '{0}' during {1}", e.Message, controllerClass);
            }
            if (successExpected)
            {
                ProcessFailureResult <TQ, TS, TT>(true, controller, response);
                ValidateSuccess <TQ, TS, TT>(controller, response);
            }
            else
            {
                ValidateFailure <TQ, TS, TT>(controller, response);
            }
            if (null == response && null != controller && null != controller.GetErrorResponse())
            {
                _errorResponse = controller.GetErrorResponse();
            }

            return(response);
        }
Ejemplo n.º 11
0
 public TS ExecuteWithApiResponse(AuthorizeNet.Environment environment = null)
 {
     Execute(environment);
     return(GetApiResponse());
 }
Ejemplo n.º 12
0
 public void Execute(AuthorizeNet.Environment environment = null)
 {
     AsyncUtil.RunSync(() => ExecuteAsync(environment));
 }
Ejemplo n.º 13
0
        public static ANetApiResponse PostData <TQ, TS>(AuthorizeNet.Environment env, TQ request)
            where TQ : ANetApiRequest
            where TS : ANetApiResponse
        {
            ANetApiResponse response = null;

            if (null == request)
            {
                throw new ArgumentNullException("request");
            }
            Logger.info(string.Format("MerchantInfo->LoginId/TransactionKey: '{0}':'{1}'->{2}",
                                      request.merchantAuthentication.name, request.merchantAuthentication.ItemElementName, request.merchantAuthentication.Item));

            var postUrl    = GetPostUrl(env);
            var webRequest = (HttpWebRequest)WebRequest.Create(postUrl);

            webRequest.Method      = "POST";
            webRequest.ContentType = "text/xml";
            webRequest.KeepAlive   = true;
            webRequest.Proxy       = SetProxyIfRequested(webRequest.Proxy);

            var requestType = typeof(TQ);

            var serializer = new XmlSerializer(requestType);

            using (var writer = new XmlTextWriter(webRequest.GetRequestStream(), Encoding.UTF8))
            {
                serializer.Serialize(writer, request);
            }
            // Get the response
            using (var webResponse = webRequest.GetResponse())
            {
                Logger.info(string.Format("Received Response: '{0}'", webResponse));

                var responseType = typeof(TS);
                var deSerializer = new XmlSerializer(responseType);
                using (var stream = webResponse.GetResponseStream())
                {
                    Logger.info(string.Format("Deserializing Response from Stream: '{0}'", stream));

                    if (null != stream)
                    {
                        var deSerializedObject = deSerializer.Deserialize(stream);
                        //if error response
                        if (deSerializedObject is ErrorResponse)
                        {
                            response = deSerializedObject as ErrorResponse;
                        }
                        else
                        {
                            //actual response of type expected
                            if (deSerializedObject is TS)
                            {
                                response = deSerializedObject as TS;
                            }
                            else if (deSerializedObject is ANetApiResponse) //generic response
                            {
                                response = deSerializedObject as ANetApiResponse;
                            }
                        }
                    }
                }
            }

            return(response);
        }
Ejemplo n.º 14
0
        private void OnPayClicked(object context, RoutedEventArgs state)
        {
            this.btnPay.IsEnabled            = false;
            this.progressBar.IsIndeterminate = true;
            string username = this.txtUsername.Text;
            string password = this.txtPassword.Password;
            string url      = null;

            this.skipSignatureValue = this.skipSignature.IsChecked ?? false;
            this.showReceiptValue   = this.showReceipt.IsChecked ?? false;
            string environment = "PROD";

            if (this.sandBox.IsChecked == true)
            {
                environment         = "SANDBOX";
                this.sdkEnvironment = AuthorizeNet.Environment.SANDBOX;
            }
            else if (this.custom.IsChecked == true)
            {
                XmlTextReader reader = new XmlTextReader("Env.xml");

                Stack <string> stack = new Stack <string>();
                Dictionary <string, string> keyValue = new Dictionary <string, string>();

                while (reader.Read())
                {
                    switch (reader.NodeType)
                    {
                    case XmlNodeType.Element:     // The node is an element.
                        Debug.Write("<" + reader.Name);
                        keyValue.Add(reader.Name, "");
                        stack.Push(reader.Name);
                        while (reader.MoveToNextAttribute())     // Read the attributes.
                        {
                            Console.Write(" " + reader.Name + "='" + reader.Value + "'");
                        }
                        Debug.WriteLine(">");
                        break;

                    case XmlNodeType.Text:     //Display the text in each element.
                        Debug.WriteLine(reader.Value);
                        string node = stack.Pop();
                        keyValue[node] = reader.Value;
                        break;

                    case XmlNodeType.EndElement:     //Display the end of the element.
                        Debug.Write("</" + reader.Name);
                        Debug.WriteLine(">");
                        break;
                    }
                }

                username    = keyValue["username"];
                password    = keyValue["password"];
                environment = "CUSTOM";
                url         = keyValue["url"];
                AuthorizeNet.Environment.createEnvironment(url, url, url);
                this.sdkEnvironment = AuthorizeNet.Environment.CUSTOM;
            }

            if (String.IsNullOrWhiteSpace(username))
            {
                MessageBox.Show("You must specify a username.", "Input Error", MessageBoxButton.OK);
                return;
            }

            if (String.IsNullOrWhiteSpace(password))
            {
                MessageBox.Show("You must specify a password.", "Input Error", MessageBoxButton.OK);
                return;
            }

            List <object> arguments = new List <object>();

            arguments.Add(username);
            arguments.Add(password);
            arguments.Add("123456789WINSDK");

            string[] workerArguments = new string[] { username, password, "123456789WINSDK", environment };
            backgroundWorkerLogin.RunWorkerAsync(workerArguments);
        }
Ejemplo n.º 15
0
        public async Task <TS> ExecuteWithApiResponseAsync(AuthorizeNet.Environment environment = null)
        {
            await ExecuteAsync(environment).ConfigureAwait(false);

            return(GetApiResponse());
        }
Ejemplo n.º 16
0
        public static ANetApiResponse PostData <TQ, TS>(AuthorizeNet.Environment env, TQ request)
            where TQ : ANetApiRequest
            where TS : ANetApiResponse
        {
            ANetApiResponse response = null;

            if (null == request)
            {
                throw new ArgumentNullException("request");
            }
            Logger.debug(string.Format("MerchantInfo->LoginId/TransactionKey: '{0}':'{1}'->{2}",
                                       request.merchantAuthentication.name, request.merchantAuthentication.ItemElementName, request.merchantAuthentication.Item));

            var postUrl    = GetPostUrl(env);
            var webRequest = (HttpWebRequest)WebRequest.Create(postUrl);

            webRequest.Method      = "POST";
            webRequest.ContentType = "text/xml";
            webRequest.KeepAlive   = true;
            webRequest.Proxy       = SetProxyIfRequested(webRequest.Proxy);

            //set the http connection timeout
            var httpConnectionTimeout = AuthorizeNet.Environment.getIntProperty(Constants.HttpConnectionTimeout);

            webRequest.Timeout = (httpConnectionTimeout != 0 ? httpConnectionTimeout : Constants.HttpConnectionDefaultTimeout);

            //set the time out to read/write from stream
            var httpReadWriteTimeout = AuthorizeNet.Environment.getIntProperty(Constants.HttpReadWriteTimeout);

            webRequest.ReadWriteTimeout = (httpReadWriteTimeout != 0 ? httpReadWriteTimeout : Constants.HttpReadWriteDefaultTimeout);

            var requestType = typeof(TQ);
            var serializer  = new XmlSerializer(requestType);

            using (var writer = new XmlTextWriter(webRequest.GetRequestStream(), Encoding.UTF8))
            {
                serializer.Serialize(writer, request);
            }

            // Get the response
            String responseAsString = null;

            Logger.debug(string.Format("Retreiving Response from Url: '{0}'", postUrl));
            using (var webResponse = webRequest.GetResponse())
            {
                Logger.debug(string.Format("Received Response: '{0}'", webResponse));

                using (var responseStream = webResponse.GetResponseStream())
                {
                    if (null != responseStream)
                    {
                        using (var reader = new StreamReader(responseStream))
                        {
                            responseAsString = reader.ReadToEnd();
                        }
                        Logger.debug(string.Format("Response from Stream: '{0}'", responseAsString));
                    }
                }
            }
            if (null != responseAsString)
            {
                using (var memoryStreamForResponseAsString = new MemoryStream(Encoding.UTF8.GetBytes(responseAsString)))
                {
                    var responseType = typeof(TS);
                    var deSerializer = new XmlSerializer(responseType);

                    Object deSerializedObject;
                    try
                    {
                        // try deserializing to the expected response type
                        deSerializedObject = deSerializer.Deserialize(memoryStreamForResponseAsString);
                    }
                    catch (Exception)
                    {
                        // probably a bad response, try if this is an error response
                        memoryStreamForResponseAsString.Seek(0, SeekOrigin.Begin); //start from beginning of stream
                        var genericDeserializer = new XmlSerializer(typeof(ANetApiResponse));
                        deSerializedObject = genericDeserializer.Deserialize(memoryStreamForResponseAsString);
                    }

                    //if error response
                    if (deSerializedObject is ErrorResponse)
                    {
                        response = deSerializedObject as ErrorResponse;
                    }
                    else
                    {
                        //actual response of type expected
                        if (deSerializedObject is TS)
                        {
                            response = deSerializedObject as TS;
                        }
                        else if (deSerializedObject is ANetApiResponse) //generic response
                        {
                            response = deSerializedObject as ANetApiResponse;
                        }
                    }
                }
            }

            return(response);
        }
Ejemplo n.º 17
0
        public static ANetApiResponse PostData <TQ, TS>(AuthorizeNet.Environment env, TQ request)
            where TQ : ANetApiRequest
            where TS : ANetApiResponse
        {
            ANetApiResponse response = null;

            if (null == request)
            {
                throw new ArgumentNullException("request");
            }
            Logger.debug(string.Format("MerchantInfo->LoginId/TransactionKey: '{0}':'{1}'->{2}",
                                       request.merchantAuthentication.name, request.merchantAuthentication.ItemElementName, request.merchantAuthentication.Item));

            var postUrl    = GetPostUrl(env);
            var webRequest = (HttpWebRequest)WebRequest.Create(postUrl);

            webRequest.Method                = "POST";
            webRequest.ContentType           = "text/xml";
            webRequest.Headers["Connection"] = "keep-alive";
            webRequest.Proxy = SetProxyIfRequested(webRequest.Proxy);

            /* HACK: No timeout properties are available on WebRequest in .NET Core
             * //set the http connection timeout
             * var httpConnectionTimeout = AuthorizeNet.Environment.getIntProperty(Constants.HttpConnectionTimeout);
             * webRequest.Timeout = (httpConnectionTimeout != 0 ? httpConnectionTimeout : Constants.HttpConnectionDefaultTimeout);
             *
             * //set the time out to read/write from stream
             * var httpReadWriteTimeout = AuthorizeNet.Environment.getIntProperty(Constants.HttpReadWriteTimeout);
             * webRequest.ReadWriteTimeout = (httpReadWriteTimeout != 0 ? httpReadWriteTimeout : Constants.HttpReadWriteDefaultTimeout);
             */

            var requestType = typeof(TQ);
            var serializer  = new XmlSerializer(requestType);

            using (var writer = XmlWriter.Create(HttpUtility.GetRequestStreamAsync(webRequest).Result, new XmlWriterSettings {
                Encoding = Encoding.UTF8
            }))
            {
                serializer.Serialize(writer, request);
            }

            // Get the response
            String responseAsString = null;

            Logger.debug(string.Format("Retreiving Response from Url: '{0}'", postUrl));
            using (var webResponse = HttpUtility.GetResponseAsync(webRequest).Result)
            {
                Logger.debug(string.Format("Received Response: '{0}'", webResponse));

                using (var responseStream = webResponse.GetResponseStream())
                {
                    if (null != responseStream)
                    {
                        var result = new StringBuilder();

                        using (var reader = new StreamReader(responseStream))
                        {
                            while (!reader.EndOfStream)
                            {
                                result.Append((char)reader.Read());

                                if (result.Length >= MaxResponseLength)
                                {
                                    throw new Exception("response is too long.");
                                }
                            }

                            responseAsString = result.Length > 0 ? result.ToString() : null;
                        }
                        Logger.debug(string.Format("Response from Stream: '{0}'", responseAsString));
                    }
                }
            }
            if (null != responseAsString)
            {
                using (var memoryStreamForResponseAsString = new MemoryStream(Encoding.UTF8.GetBytes(responseAsString)))
                {
                    var responseType = typeof(TS);
                    var deSerializer = new XmlSerializer(responseType);

                    Object deSerializedObject;
                    try
                    {
                        // try deserializing to the expected response type
                        deSerializedObject = deSerializer.Deserialize(memoryStreamForResponseAsString);
                    }
                    catch (Exception)
                    {
                        // probably a bad response, try if this is an error response
                        memoryStreamForResponseAsString.Seek(0, SeekOrigin.Begin); //start from beginning of stream
                        var genericDeserializer = new XmlSerializer(typeof(ANetApiResponse));
                        deSerializedObject = genericDeserializer.Deserialize(memoryStreamForResponseAsString);
                    }

                    //if error response
                    if (deSerializedObject is ErrorResponse)
                    {
                        response = deSerializedObject as ErrorResponse;
                    }
                    else
                    {
                        //actual response of type expected
                        if (deSerializedObject is TS)
                        {
                            response = deSerializedObject as TS;
                        }
                        else if (deSerializedObject is ANetApiResponse) //generic response
                        {
                            response = deSerializedObject as ANetApiResponse;
                        }
                    }
                }
            }

            return(response);
        }