Example #1
0
        public IResult <TResult> Execute <TResult>(TCredentials credentials, ICommand <TResult> command)
        {
            string result;

            var uri = this.GetFullUri(command);

            uri = this.AlterUri(credentials, command, uri);
            var hwr = (HttpWebRequest)WebRequest.Create(uri);

            hwr.Method = this.GetVerb(command.Verb);

            if (!string.IsNullOrEmpty(command.ContentType))
            {
                hwr.ContentType = command.ContentType;
            }

            this.AddHeader(credentials, command, hwr);

            command.AddHeaders((key, value) => hwr.Headers.Add(key, value));

            //GS - POST off the request

            //hwr.ContentType = "application/x-www-form-urlencoded";

            if (command.Verb == CommandVerb.Post)
            {
                Stream requestStream = hwr.GetRequestStream();
                byte[] bodyBytes     = new ASCIIEncoding().GetBytes(this.GetPost(command));

                requestStream.Write(bodyBytes, 0, bodyBytes.Length);
                requestStream.Flush();
                requestStream.Close();
            }
            else
            {
                if (!string.IsNullOrEmpty(this.GetPost(command)))
                {
                    throw new InvalidOperationException("Cannot send command with GET verb and POST parameters");
                }
            }

            //GS - Allow us a reasonable timeout in case
            //Twitter's busy
            hwr.Timeout = 3 * 60 * 1000;

            WebResponse webResponse;

            try {
                webResponse = hwr.GetResponse();
                //GS - Do something with the return here...
            } catch (WebException e) {
                webResponse = e.Response;
            }

            var response = webResponse as HttpWebResponse;

            using (var responseStream = new StreamReader(response.GetResponseStream())) {
                result = responseStream.ReadToEnd();
            }

            Error   error           = null;
            TResult formattedResult = default(TResult);
            var     statusCode      = (int)response.StatusCode;

            if (statusCode == 500 || statusCode == 403 || statusCode == 401)
            {
                throw new ApiErrorException(new Result <Error> {
                    Raw   = result,
                    Typed = command.FormatError(result, response.ContentType),
                });
            }
            else
            {
                formattedResult = command.FormatResult(result, response.ContentType);
            }

            return(new Result <TResult> {
                Raw = result,
                Typed = formattedResult,
            });
        }