Exemplo n.º 1
0
 /// <summary>
 /// Tests the connection to USFT
 /// </summary>
 /// <param name="AsAccount">(Optional) If this parameter is included, the method will be run on behalf of the specified child Account.</param>
 /// <returns>True if the /Test method completes successfully</returns>
 /// <exception cref="RestException">Contains details of an unsuccessful request</exception>
 public bool TestConnection(Account AsAccount = null)
 {
     using (HttpWebResponse response = AttemptRequest(uriPath_Test + AppendAccount(AsAccount), verb_Read))
     {
         if (response.StatusCode == HttpStatusCode.OK)
         {
             return(true);
         }
         else
         {
             throw RestException.Create(response);
         }
     }
 }
Exemplo n.º 2
0
 /// <summary>
 /// Send a custom request to the API
 /// </summary>
 /// <typeparam name="T">Type of the object you expect in return</typeparam>
 /// <param name="Path">Path of the API call, eg: "/Test"</param>
 /// <param name="Method">HTTP Verb to use, eg: "GET", "POST", etc.</param>
 /// <param name="BodyContent">Object to submit in the request body, usually for Creating or Updating records</param>
 /// <returns>Object returned by the database</returns>
 /// <exception cref="RestException">A RestException containing the information returned by the server for an unsuccessful request</exception>
 private T RetrieveResponse <T>(string Path, string Method = "GET", object BodyContent = null, bool DoAuthentication = true)
 {
     using (HttpWebResponse response = AttemptRequest(Path, Method, BodyContent, DoAuthentication))
     {
         if (response.StatusCode == HttpStatusCode.OK)
         {
             StreamReader reader  = new StreamReader(response.GetResponseStream());
             string       content = reader.ReadToEnd();
             T            ret     = JsonConvert.DeserializeObject <T>(content);
             return(ret);
         }
         else
         {
             throw RestException.Create(response);
         }
     }
 }
Exemplo n.º 3
0
        /// <summary>
        /// Create a new RestException from an unsuccessful HttpWebResponse.
        /// </summary>
        /// <param name="UnsuccessfulResponse">The HttpWebResponse that failed to return successfully.</param>
        /// <returns>A RestException with Message determined by the HttpWebResponse info.</returns>
        public static RestException Create(HttpWebResponse UnsuccessfulResponse)
        {
            StreamReader  reader  = new StreamReader(UnsuccessfulResponse.GetResponseStream());
            string        content = reader.ReadToEnd();
            RestException ret     = new RestException();

            try
            {
                UnsuccessfulBody body = JsonConvert.DeserializeObject <UnsuccessfulBody>(content);
                ret = new RestException(string.Format("{0} returned {1}: {2}", UnsuccessfulResponse.ResponseUri.PathAndQuery, UnsuccessfulResponse.StatusCode, body.Message));
            }
            catch (Exception exc)
            {
                ret = new RestException(string.Format("{0} returned {1}", UnsuccessfulResponse.ResponseUri, UnsuccessfulResponse.StatusCode), exc);
            }
            finally
            {
                ret.UnsuccessfulResponse = UnsuccessfulResponse;
            }
            return(ret);
        }
Exemplo n.º 4
0
        private HttpWebResponse AttemptRequest(string Path, string Method, string PostString, bool DoAuthentication, DateTime?dateTimeOverride = null)
        {
            string address = uriBase + Path;

            Uri uri = new Uri(address);

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);

            if (Proxy != null)
            {
                request.Proxy = Proxy;
            }

            if (DoAuthentication)
            {
                string AuthString;
                if (Authentication == AuthenticationMode.USFT)
                {
                    // Building the http Date header is a little tricky.
                    // HttpWebRequest insists on formatting the string itself, because incorrectly formatted values are very common.
                    DateTime d;
                    if (dateTimeOverride.HasValue)
                    {
                        d = dateTimeOverride.Value;
                    }
                    else
                    {
                        d = DateTime.Now;
                    }
                    request.Date = d;

                    // So, we let it do so then ask how it decided to format that.
                    // The REST service will always use the literal string sent to the server, rather than rely on one date format or another.
                    string datestring = request.Headers["Date"];

                    // Everything else is cake.
                    string hash = Security.GenerateHash(ApiKey, HashDataPrefix + uri.AbsolutePath + datestring);
                    AuthString = string.Format("{0}{1}:{2}", auth_Prefix_USFT, Username, hash);
                }
                else if (Authentication == AuthenticationMode.Basic)
                {
                    AuthString = "Basic " +
                                 Convert.ToBase64String(
                        Encoding.ASCII.GetBytes(string.Format("{0}:{1}", Username, ApiKey)));
                }
                else
                {
                    throw new Exception("Unknown AuthenticationMode");
                }
                request.Headers.Add(HttpRequestHeader.Authorization, AuthString);
            }

            request.Method = Method;
            request.ServicePoint.Expect100Continue = false;

            if (!string.IsNullOrEmpty(PostString))
            {
                byte[] postBytes = Encoding.ASCII.GetBytes(PostString);

                request.ContentType   = "application/json";
                request.ContentLength = postBytes.Length;

                Stream postStream = request.GetRequestStream();
                postStream.Write(postBytes, 0, postBytes.Length);
                postStream.Flush();
            }


            try
            {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                return(response);
            }
            catch (WebException exc)
            {
                if (exc.Response != null)
                {
                    throw RestException.Create((HttpWebResponse)exc.Response);
                }
                else
                {
                    throw new RestException("No response generated", exc);
                }
            }
            catch (Exception exc)
            {
                throw new RestException(
                          "Unexpected exception encountered while attempting HttpWebRequest.GetResponse()", exc);
            }
        }