Example #1
0
        private T RunRequest <T, Model>(string api, HttpMethodType method, HttpContent content = null) where T : IResponseBase <Model> where Model : class
        {
            var result = Activator.CreateInstance <T>();

            try
            {
                using (var client = new HttpClient())
                {
                    client.SetBasicAuthentication(GetAPIKey(_site), DEFAULT_PASSWORD);
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    var uri = new UriBuilder(new Uri(new Uri(GetEndpoint(_site)), api));

                    HttpResponseMessage httpResponse;

                    switch (method)
                    {
                    case HttpMethodType.Get:
                        httpResponse = client.GetAsync(uri.Uri).Result;
                        break;

                    case HttpMethodType.Post:
                        if (content != null)
                        {
                            httpResponse = client.PostAsync(uri.Uri, content).Result;
                        }
                        else
                        {
                            //todo: create ChargifyException
                            throw new Exception("POST HTTP Content header is missing.");
                        }
                        break;

                    case HttpMethodType.Put:
                        if (content != null)
                        {
                            httpResponse = client.PutAsync(uri.Uri, content).Result;
                        }
                        else
                        {
                            //todo: create ChargifyException
                            throw new Exception("PUT HTTP Content header is missing.");
                        }
                        break;

                    case HttpMethodType.Delete:
                        httpResponse = client.DeleteAsync(uri.Uri).Result;
                        break;

                    default:
                        //todo: create ChargifyException
                        throw new Exception("Invalid Http method");
                    }

                    var response = HttpClientUtils.ParseResponse <Model>(httpResponse);
                    result.IsError = response.IsError;
                    result.Message = response.Message;
                    result.Model   = response.Model;
                }
            }
            catch (Exception ex)
            {
                //todo: logger
                result.IsError = true;
                result.Message = ex.Message;
                throw;
            }
            return(result);
        }