RestClient.cs 6.48 KB
using System;
using System.IO;
using System.Net;
using System.Security.Cryptography;
using System.Text;

namespace MoyaAdminLib
{
    public enum HttpVerb
    {
        GET,
        POST,
        PUT,
        DELETE
    }

    public class RestClient
    {
        public string EndPoint { get; set; }
        public HttpVerb Method { get; set; }
        public string ContentType { get; set; }
        public string PostData { get; set; }

        public static string ApiApplicationKey { get; set; }
        public static string ApiUser { get; set; }
        public static string ApiPass { get; set; }
        public static string ApiURL { get; set; }

        public RestClient()
        {
            EndPoint = ApiURL;
            Method = HttpVerb.GET;

            ContentType = "application/json";
            PostData = "";
        }

        public RestClient(string endpoint)
        {
            EndPoint = endpoint;
            Method = HttpVerb.GET;
            ContentType = "application/json";
            PostData = "";
        }

        public RestClient(string endpoint, HttpVerb method)
        {
            EndPoint = endpoint;
            Method = method;
            ContentType = "application/json";
            PostData = "";
        }

        public RestClient(string endpoint, HttpVerb method, string postData)
        {
            EndPoint = endpoint;
            Method = method;
            ContentType = "application/json";
            PostData = postData;
        }

        private static string CalculateSHA1(string text)
        {
            // Convert the input string to a byte array
            var buffer = Encoding.GetEncoding("iso-8859-1").GetBytes(text);

            // In doing your test, you won't want to re-initialize like this every time you test a
            // string.
            var cryptoTransformSha1 = new SHA1CryptoServiceProvider();

            // The replace won't be necessary for your tests so long as you are consistent in what
            // you compare.    
            var hash = BitConverter.ToString(cryptoTransformSha1.ComputeHash(buffer)).Replace("-", "").ToLower();

            return hash;
        }

        private static int ConvertToTimestamp(DateTime value)
        {
            //create Timespan by subtracting the value provided from
            //the Unix Epoch
            var span = (value - new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime());

            //return the total seconds (which is a UNIX timestamp)
            return (int)span.TotalSeconds;
        }

        public static string GetRequestURL(string server, string queryPath, string getparms)
        {
            var timestamp = ConvertToTimestamp(DateTime.Now);

            var hash = CalculateSHA1("/" + queryPath + "+" + ApiApplicationKey + "+" + ApiUser + "+" + timestamp + "+" + ApiPass);

            if (!string.IsNullOrEmpty(getparms))
                getparms = getparms + "&";

            var url = server + "/rest/" + queryPath + "?";
            if (getparms != null)
                url += getparms;

            url += "appkey=" + ApiApplicationKey + "&appuser=" + ApiUser + "&appstamp=" + timestamp + "&appmac=" + hash;

            Console.WriteLine(url);
            return url;
        }

        public static string GetRequestURL(string server, string queryPath)
        {
            return GetRequestURL(server, queryPath, null);
        }

        public string MakeRequest(string queryPath)
        {
            return MakeRequest(queryPath, null);
        }

        public string MakeRequest(string queryPath, string getparms)
        {
            var request = (HttpWebRequest)WebRequest.Create(GetRequestURL(EndPoint, queryPath, getparms));

            request.Method = Method.ToString();
            request.ContentLength = 0;
            request.ContentType = ContentType;

            if (!string.IsNullOrEmpty(PostData) && (Method == HttpVerb.POST || Method == HttpVerb.PUT))
            {
                var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(PostData);
                request.ContentLength = bytes.Length;

                using (var writeStream = request.GetRequestStream())
                {
                    writeStream.Write(bytes, 0, bytes.Length);
                }
            }

            try
            {
                using (var response = (HttpWebResponse)request.GetResponse())
                {
                    var responseValue = string.Empty;

                    if ((int)response.StatusCode < 200 && (int)response.StatusCode >= 300)
                    {
                        throw new MoyaApiException("Request failed", response.StatusCode);
                    }
                    
                    using (var responseStream = response.GetResponseStream())
                    {
                        if (responseStream != null)
                        {
                            using (var reader = new StreamReader(responseStream))
                            {
                                responseValue = reader.ReadToEnd();
                            }
                        }
                    }

                    return responseValue;
                }
            }
            catch (WebException e)
            {
                var errorResponse = e.Response as HttpWebResponse;
                if (errorResponse != null && errorResponse.StatusCode == HttpStatusCode.NotFound)
                {
                    throw new MoyaApiException("Resource not found", HttpStatusCode.NotFound, e);
                }

                if (e.Status == WebExceptionStatus.ConnectFailure)
                {
                    throw;
                }

                var responseStream = e.Response.GetResponseStream();
                if (responseStream != null)
                {
                    var responseValue = StreamToString(responseStream);
                    Console.WriteLine("Response was " + responseValue);
                    throw new WebException(responseValue, e);
                }


                throw;
            }

        }

        /// <summary>
        /// Convert streams from web to string
        /// </summary>
        /// <param name="responseStream">Webresponse stream</param>
        /// <returns>string</returns>
        private string StreamToString(Stream responseStream)
        {
            var reader = new StreamReader(responseStream);
            var responseString = reader.ReadToEnd();
            responseStream.Close();
            reader.Close();
            return responseString;
        }
    }
}