Esempio n. 1
0
        protected virtual void ReadWebResponse(HttpWebResponse response, ReadXmlDelegate readXmlDelegate, ReadXmlListDelegate readXmlListDelegate)
        {
            if (readXmlDelegate == null && readXmlListDelegate == null) return;
            #if (DEBUG)
            Debug.WriteLine("Got Response:");
            Debug.WriteLine("Status code: " + response.StatusCode);

            foreach (var header in response.Headers)
            {
                Debug.WriteLine(header + ": " + response.Headers[header.ToString()]);
            }

            var responseStream = CopyAndClose(response.GetResponseStream());
            var reader = new StreamReader(responseStream);

            string line;
            while ((line = reader.ReadLine()) != null)
            {
                Debug.WriteLine(line);
            }

            responseStream.Position = 0;
            using (var xmlReader = new XmlTextReader(responseStream))
            {
                // Check for pagination
                var records = -1;
                var cursor = string.Empty;
                string start = null;
                string next = null;
                string prev = null;

                if (null != response.Headers["X-Records"])
                {
                    Int32.TryParse(response.Headers["X-Records"], out records);
                }

                var link = response.Headers["Link"];

                if (!link.IsNullOrEmpty())
                {
                    start = link.GetUrlFromLinkHeader("start");
                    next = link.GetUrlFromLinkHeader("next");
                    prev = link.GetUrlFromLinkHeader("prev");
                }

                if (records >= 0)
                    readXmlListDelegate(xmlReader, records, start, next, prev);
                else
                    readXmlDelegate(xmlReader);
            }

            #else

            using(var responseStream = response.GetResponseStream())
            {

                using(var xmlReader = new XmlTextReader(responseStream))
                {
                    // Check for pagination
                    var records = -1;
                    var cursor = string.Empty;
                    string start = null;
                    string next = null;
                    string prev = null;

                    if (null != response.Headers["X-Records"])
                    {
                        Int32.TryParse(response.Headers["X-Records"], out records);
                    }

                    var link = response.Headers["Link"];

                    if (!link.IsNullOrEmpty())
                    {
                        start = link.GetUrlFromLinkHeader("start");
                        next = link.GetUrlFromLinkHeader("next");
                        prev = link.GetUrlFromLinkHeader("prev");
                    }

                    if (records >= 0)
                        readXmlListDelegate(xmlReader, records, start, next, prev);
                    else
                        readXmlDelegate(xmlReader);
                }
            }
            #endif
        }
Esempio n. 2
0
 public HttpStatusCode PerformRequest(HttpRequestMethod method, string urlPath,
     ReadXmlListDelegate readXmlListDelegate)
 {
     return PerformRequest(method, urlPath, null, null, readXmlListDelegate);
 }
Esempio n. 3
0
        protected virtual HttpStatusCode PerformRequest(HttpRequestMethod method, string urlPath,
            WriteXmlDelegate writeXmlDelegate, ReadXmlDelegate readXmlDelegate, ReadXmlListDelegate readXmlListDelegate)
        {
            var url = Settings.GetServerUri(urlPath);
            #if (DEBUG)
            Console.WriteLine("Requesting " + method + " " + url);
            #endif
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Accept = "application/xml";      // Tells the server to return XML instead of HTML
            request.ContentType = "application/xml; charset=utf-8"; // The request is an XML document
            request.SendChunked = false;             // Send it all as one request
            request.UserAgent = Settings.UserAgent;
            request.Headers.Add(HttpRequestHeader.Authorization, Settings.AuthorizationHeaderValue);
            request.Method = method.ToString().ToUpper();

            Debug.WriteLine(String.Format("Recurly: Requesting {0} {1}", request.Method, request.RequestUri));

            if ((method == HttpRequestMethod.Post || method == HttpRequestMethod.Put) && (writeXmlDelegate != null))
            {
                // 60 second timeout -- some payment gateways (e.g. PayPal) can take a while to respond
                request.Timeout = 60000;

                // Write POST/PUT body
                using (var requestStream = request.GetRequestStream())
                {
                    WritePostParameters(requestStream, writeXmlDelegate);
                }
            }
            else
            {
                request.ContentLength = 0;
            }

            try
            {
                using (var response = (HttpWebResponse)request.GetResponse())
                {

                    ReadWebResponse(response, readXmlDelegate, readXmlListDelegate);
                    return response.StatusCode;

                }
            }
            catch (WebException ex)
            {
                if (ex.Response == null) throw;

                var response = (HttpWebResponse)ex.Response;
                var statusCode = response.StatusCode;
                Error[] errors;

                Debug.WriteLine(String.Format("Recurly Library Received: {0} - {1}", (int)statusCode, statusCode));

                switch (response.StatusCode)
                {
                    case HttpStatusCode.OK:
                    case HttpStatusCode.Accepted:
                    case HttpStatusCode.Created:
                    case HttpStatusCode.NoContent:
                        ReadWebResponse(response, readXmlDelegate, readXmlListDelegate);

                        return HttpStatusCode.NoContent;

                    case HttpStatusCode.NotFound:
                        errors = Error.ReadResponseAndParseErrors(response);
                        if (errors.Length > 0)
                            throw new NotFoundException(errors[0].Message, errors);
                        throw new NotFoundException("The requested object was not found.", errors);

                    case HttpStatusCode.Unauthorized:
                    case HttpStatusCode.Forbidden:
                        errors = Error.ReadResponseAndParseErrors(response);
                        throw new InvalidCredentialsException(errors);

                    case HttpStatusCode.PreconditionFailed:
                        errors = Error.ReadResponseAndParseErrors(response);
                        throw new ValidationException(errors);

                    case HttpStatusCode.ServiceUnavailable:
                        throw new TemporarilyUnavailableException();

                    case HttpStatusCode.InternalServerError:
                        errors = Error.ReadResponseAndParseErrors(response);
                        throw new ServerException(errors);
                }

                if ((int)statusCode == ValidationException.HttpStatusCode) // Unprocessable Entity
                {
                    errors = Error.ReadResponseAndParseErrors(response);
                    if (errors.Length > 0) Debug.WriteLine(errors[0].ToString());
                    else Debug.WriteLine("Client Error: " + response.ToString());
                    throw new ValidationException(errors);
                }

                throw;
            }
        }
Esempio n. 4
0
        protected virtual void ReadWebResponse(HttpWebResponse response, ReadXmlDelegate readXmlDelegate, ReadXmlListDelegate readXmlListDelegate, ReadResponseDelegate responseDelegate)
        {
            if (readXmlDelegate == null && readXmlListDelegate == null && responseDelegate == null)
            {
                return;
            }
#if (DEBUG)
            Console.WriteLine("Got Response:");
            Console.WriteLine("Status code: " + response.StatusCode);

            foreach (var header in response.Headers)
            {
                Console.WriteLine(header + ": " + response.Headers[header.ToString()]);
            }
#endif
            var responseStream = CopyAndClose(response.GetResponseStream());
            var reader         = new StreamReader(responseStream);

#if (DEBUG)
            string line;
            while ((line = reader.ReadLine()) != null)
            {
                Console.WriteLine(line);
            }
#endif
            if (responseDelegate != null)
            {
                responseDelegate(response);
                return;
            }

            responseStream.Position = 0;
            using (var xmlReader = Client.BuildXmlTextReader(responseStream))
            {
                // Check for pagination
                var    cursor = string.Empty;
                string start  = null;
                string next   = null;
                string prev   = null;

                var link = response.Headers["Link"];

                if (!link.IsNullOrEmpty())
                {
                    start = link.GetUrlFromLinkHeader("start");
                    next  = link.GetUrlFromLinkHeader("next");
                    prev  = link.GetUrlFromLinkHeader("prev");
                    readXmlListDelegate(xmlReader, start, next, prev);
                }
                else if (readXmlListDelegate != null)
                {
                    readXmlListDelegate(xmlReader, start, next, prev);
                }
                else if (response.StatusCode != HttpStatusCode.NoContent)
                {
                    readXmlDelegate(xmlReader);
                }
            }
        }
Esempio n. 5
0
        protected virtual HttpStatusCode PerformRequest(HttpRequestMethod method, string urlPath,
                                                        WriteXmlDelegate writeXmlDelegate, ReadXmlDelegate readXmlDelegate, ReadXmlListDelegate readXmlListDelegate, ReadResponseDelegate reseponseDelegate)
        {
            var url = Settings.GetServerUri(urlPath);

#if (DEBUG)
            Console.WriteLine("Requesting " + method + " " + url);
#endif
            var request = (HttpWebRequest)WebRequest.Create(url);

            if (!request.RequestUri.Host.EndsWith(Settings.ValidDomain))
            {
                throw new RecurlyException("Domain " + request.RequestUri.Host + " is not a valid Recurly domain");
            }

            request.Accept      = "application/xml";                // Tells the server to return XML instead of HTML
            request.ContentType = "application/xml; charset=utf-8"; // The request is an XML document
            request.SendChunked = false;                            // Send it all as one request
            request.UserAgent   = Settings.UserAgent;
            request.Headers.Add(HttpRequestHeader.Authorization, Settings.AuthorizationHeaderValue);
            request.Headers.Add("X-Api-Version", Settings.RecurlyApiVersion);
            request.Method = method.ToString().ToUpper();

            Console.WriteLine(String.Format("Recurly: Requesting {0} {1}", request.Method, request.RequestUri));

            if ((method == HttpRequestMethod.Post || method == HttpRequestMethod.Put) && (writeXmlDelegate != null))
            {
                // 60 second timeout -- some payment gateways (e.g. PayPal) can take a while to respond
                request.Timeout = 60000;

                // Write POST/PUT body
                using (var requestStream = request.GetRequestStream())
                {
                    WritePostParameters(requestStream, writeXmlDelegate);
                }
            }
            else
            {
                request.ContentLength = 0;
            }

            try
            {
                using (var response = (HttpWebResponse)request.GetResponse())
                {
                    ReadWebResponse(response, readXmlDelegate, readXmlListDelegate, reseponseDelegate);
                    return(response.StatusCode);
                }
            }
            catch (WebException ex)
            {
                if (ex.Response == null)
                {
                    throw;
                }

                var    response   = (HttpWebResponse)ex.Response;
                var    statusCode = response.StatusCode;
                Errors errors;

                Console.WriteLine(String.Format("Recurly Library Received: {0} - {1}", (int)statusCode, statusCode));

                switch (response.StatusCode)
                {
                case HttpStatusCode.OK:
                case HttpStatusCode.Accepted:
                case HttpStatusCode.Created:
                case HttpStatusCode.NoContent:
                    ReadWebResponse(response, readXmlDelegate, readXmlListDelegate, reseponseDelegate);

                    return(HttpStatusCode.NoContent);

                case HttpStatusCode.NotFound:
                    errors = Errors.ReadResponseAndParseErrors(response);
                    if (errors.ValidationErrors.HasAny())
                    {
                        throw new NotFoundException(errors.ValidationErrors[0].Message, errors);
                    }
                    throw new NotFoundException("The requested object was not found.", errors);

                case HttpStatusCode.Unauthorized:
                case HttpStatusCode.Forbidden:
                    errors = Errors.ReadResponseAndParseErrors(response);
                    throw new InvalidCredentialsException(errors);

                case HttpStatusCode.BadRequest:
                case HttpStatusCode.PreconditionFailed:
                    errors = Errors.ReadResponseAndParseErrors(response);
                    throw new ValidationException(errors);

                case HttpStatusCode.ServiceUnavailable:
                    throw new TemporarilyUnavailableException();

                case HttpStatusCode.InternalServerError:
                    errors = Errors.ReadResponseAndParseErrors(response);
                    throw new ServerException(errors);
                }

                if ((int)statusCode == ValidationException.HttpStatusCode) // Unprocessable Entity
                {
                    errors = Errors.ReadResponseAndParseErrors(response);
                    if (errors.ValidationErrors.HasAny())
                    {
                        Console.WriteLine(errors.ValidationErrors[0].ToString());
                    }
                    else
                    {
                        Console.WriteLine("Client Error: " + response.ToString());
                    }
                    throw new ValidationException(errors);
                }

                throw;
            }
        }
Esempio n. 6
0
 public HttpStatusCode PerformRequest(HttpRequestMethod method, string urlPath,
                                      ReadXmlListDelegate readXmlListDelegate)
 {
     return(PerformRequest(method, urlPath, null, null, readXmlListDelegate, null));
 }
Esempio n. 7
0
        protected virtual void ReadWebResponse(HttpWebResponse response, ReadXmlDelegate readXmlDelegate, ReadXmlListDelegate readXmlListDelegate)
        {
            if (readXmlDelegate == null && readXmlListDelegate == null)
            {
                return;
            }
#if (DEBUG)
            Debug.WriteLine("Got Response:");
            Debug.WriteLine("Status code: " + response.StatusCode);

            foreach (var header in response.Headers)
            {
                Debug.WriteLine(header + ": " + response.Headers[header.ToString()]);
            }

            var responseStream = CopyAndClose(response.GetResponseStream());
            var reader         = new StreamReader(responseStream);

            string line;
            while ((line = reader.ReadLine()) != null)
            {
                Debug.WriteLine(line);
            }

            responseStream.Position = 0;
            using (var xmlReader = new XmlTextReader(responseStream))
            {
                // Check for pagination
                var    records = -1;
                var    cursor  = string.Empty;
                string start   = null;
                string next    = null;
                string prev    = null;

                if (null != response.Headers["X-Records"])
                {
                    Int32.TryParse(response.Headers["X-Records"], out records);
                }

                var link = response.Headers["Link"];

                if (!link.IsNullOrEmpty())
                {
                    start = link.GetUrlFromLinkHeader("start");
                    next  = link.GetUrlFromLinkHeader("next");
                    prev  = link.GetUrlFromLinkHeader("prev");
                }

                if (records >= 0)
                {
                    readXmlListDelegate(xmlReader, records, start, next, prev);
                }
                else
                {
                    readXmlDelegate(xmlReader);
                }
            }
#else
            using (var responseStream = response.GetResponseStream())
            {
                using (var xmlReader = new XmlTextReader(responseStream))
                {
                    // Check for pagination
                    var    records = -1;
                    var    cursor  = string.Empty;
                    string start   = null;
                    string next    = null;
                    string prev    = null;

                    if (null != response.Headers["X-Records"])
                    {
                        Int32.TryParse(response.Headers["X-Records"], out records);
                    }

                    var link = response.Headers["Link"];

                    if (!link.IsNullOrEmpty())
                    {
                        start = link.GetUrlFromLinkHeader("start");
                        next  = link.GetUrlFromLinkHeader("next");
                        prev  = link.GetUrlFromLinkHeader("prev");
                    }

                    if (records >= 0)
                    {
                        readXmlListDelegate(xmlReader, records, start, next, prev);
                    }
                    else if (response.StatusCode != HttpStatusCode.NoContent)
                    {
                        readXmlDelegate(xmlReader);
                    }
                }
            }
#endif
        }
Esempio n. 8
0
        private static void ReadWebResponse(HttpWebResponse response, ReadXmlDelegate readXmlDelegate, ReadXmlListDelegate readXmlListDelegate)
        {
            if (readXmlDelegate != null || readXmlListDelegate != null)
            {
            #if (DEBUG)
                MemoryStream responseStream = CopyAndClose(response.GetResponseStream());
                System.Diagnostics.Debug.WriteLine("Got Response:");

                StreamReader reader = new StreamReader(responseStream);

                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    Console.WriteLine(line);
                }

                responseStream.Position = 0;
                using (XmlTextReader xmlReader = new XmlTextReader(responseStream))
                {
                    // Check for pagination
                    int records = -1;
                    string cursor = string.Empty;

                    if (null != response.Headers["X-Records"])
                    {
                        Int32.TryParse(response.Headers["X-Records"], out records);
                    }

                    if (null != response.Headers["Link"])
                    {
                        var regex = new Regex("<([^>]+)>; rel=\"next\"");
                        var match = regex.Match(response.Headers["Link"]);

                        if (match.Success)
                        {
                            Uri u = new Uri(match.Groups[1].Value);
                            NameValueCollection queryString = HttpUtility.ParseQueryString(u.Query);
                            if (null != queryString["cursor"])
                                cursor = queryString["cursor"];
                        }

                    }

                    if (records >= 0)
                        readXmlListDelegate(xmlReader, records, cursor);
                    else
                        readXmlDelegate(xmlReader);
                }

            #else

                using (Stream responseStream = response.GetResponseStream())
                {

                    using (XmlTextReader xmlReader = new XmlTextReader(responseStream))
                    {
                         // Check for pagination
                    int records = 0;
                    string cursor = string.Empty;

                    if (null != response.Headers["X-Records"])
                    {
                        Int32.TryParse(response.Headers["X-Records"], out records);
                    }

                    if (null != response.Headers["Link"])
                    {
                        var regex = new Regex("<([^>]+)>; rel=\"next\"");
                        var match = regex.Match(response.Headers["Link"]);

                        if (match.Success)
                        {
                           Uri u = new Uri(match.Groups[1].Value);
                            NameValueCollection queryString = HttpUtility.ParseQueryString(u.Query);
                            if (null != queryString["cursor"])
                                cursor = queryString["cursor"];
                        }

                    }

                    if (records > 0 )
                        readXmlListDelegate(xmlReader, records, cursor);
                    else
                        readXmlDelegate(xmlReader);
                    }
                }
            #endif
            }
        }