public static object Consume <T>(RestServiceConsumptionOptions options, ServiceConsumptionContainer resultBag)
        {
            string serviceName = GetServiceName <T>();

            int    retries = 0;
            Object obj     = InnerConsume <T>(options, serviceName, retries++, resultBag);

            if (obj != null && obj.GetType() == typeof(OAuth2InvalidToken))
            {
                GetOAuth2Token.InitializeTokens(options, serviceName);
                return(InnerConsume <T>(options, serviceName, retries, resultBag));
            }

            return(obj);
        }
 public static JObject Consume(RestServiceConsumptionOptions options,
                               ServiceConsumptionContainer resultBag = null)
 {
     return(Consume <object>(options, resultBag) as JObject);
 }
        public static object InnerConsume <T>(RestServiceConsumptionOptions options, string serviceName, int retries,
                                              ServiceConsumptionContainer resultBag)
        {
            OAuth2TokenData currentOAuth2TokenData = null;

            if (options.SecurityType == RestSecurityType.OAuth2)
            {
                currentOAuth2TokenData = GetOAuth2Token.GetAuthToken(options, serviceName, Utilities.Web.GetContext());
            }

            using (var client = GetHttpClient(options, currentOAuth2TokenData))
            {
                switch (options.Verb)
                {
                case RestHTTPVerb.GET:
                    resultBag.HttpResponseMessage = client.GetAsync("").Result;
                    break;

                case RestHTTPVerb.POST:

                    switch (options.PostType)
                    {
                    case PostType.JSON:
                        var jsonSerialized = new Utilities.Serializer <object>().ToJson(options.Data, false, options.IgnoreNullValues);
                        resultBag.HttpResponseMessage = client
                                                        .PostAsync("", new StringContent(jsonSerialized, Encoding.UTF8, "application/json"))
                                                        .Result;

                        if (!resultBag.HttpResponseMessage.IsSuccessStatusCode)
                        {
                            log4net.LogManager.GetLogger(typeof(RestServiceConsumer)).Error(jsonSerialized);
                        }
                        //response = client.PostAsJsonAsync("", options.Data).Result;
                        break;

                    case PostType.XML:
                        var xml         = new zAppDev.DotNet.Framework.Utilities.Serializer <object>().ToXml(options.Data, true);
                        var httpContent = new StringContent(xml, Encoding.UTF8, "application/xml");
                        resultBag.HttpResponseMessage = client.PostAsync("", httpContent).Result;
                        break;

                    default:
                        /*
                         *                                  HttpContent content
                         *                                      = new FormUrlEncodedContent(
                         *                                          ConvertNameValueCollectionToKeyValuePair(
                         *                                              HttpUtility.ParseQueryString(options.Data + "")));
                         *                                  response = client.PostAsync("", content).Result;
                         */
                        resultBag.HttpResponseMessage = client.PostAsync("", PrepareFormData(options)).Result;
                        //response = client.PostAsync("", options.Data).Result;
                        break;
                    }

                    /*var str = JsonConvert.SerializeObject(options.Data);
                     *
                     * var logger = LogManager.GetLogger(typeof (RestServiceConsumer));
                     * if (str == "\"" + options.Data + "\"")
                     * {
                     *
                     * logger.Debug("POSTing as FORM");
                     * logger.DebugFormat("because: {0} == {1}", str, "\"" + options.Data + "\"");
                     *
                     * HttpContent content
                     *  = new FormUrlEncodedContent(
                     *      ConvertNameValueCollectionToKeyValuePair(
                     *          HttpUtility.ParseQueryString(options.Data.ToString())));
                     * response = client.PostAsync("", content).Result;
                     * }
                     * else
                     * {
                     * logger.Debug("POSTing as JSON");
                     *
                     * response = client.PostAsJsonAsync("", options.Data).Result;
                     * }*/

                    break;

                case RestHTTPVerb.PUT:
#if NETFRAMEWORK
                    switch (options.PostType)
                    {
                    case PostType.JSON:
                        resultBag.HttpResponseMessage = client.PutAsJsonAsync("", options.Data).Result;
                        break;

                    case PostType.XML:
                        resultBag.HttpResponseMessage = client.PutAsXmlAsync("", options.Data).Result;
                        break;

                    default:
                        resultBag.HttpResponseMessage = client.PutAsync("", PrepareFormData(options)).Result;

                        break;
                    }
                    break;
#else
                    throw new NotImplementedException("InnerConsume not implement for .Net Core");
#endif
                case RestHTTPVerb.DELETE:
                    resultBag.HttpResponseMessage = client.DeleteAsync("").Result;
                    break;

                default:
                    throw new ApplicationException("Uknown Http Verb: " + options.Verb);
                }

                if (options.SecurityType == RestSecurityType.OAuth2 && resultBag.HttpResponseMessage.StatusCode == HttpStatusCode.Unauthorized && retries == 0)
                {
                    return(new OAuth2InvalidToken());
                }

                if (resultBag.HttpResponseMessage.IsSuccessStatusCode)
                {
                    var setCookieHeader =
                        resultBag.HttpResponseMessage.Headers.FirstOrDefault(a => a.Key?.ToLower() == "set-cookie");
                    if (Utilities.Web.GetContext() != null && setCookieHeader.Value != null && setCookieHeader.Value.Any())
                    {
                        Utilities.Web.GetContext().Items["ServiceAuthCookie"] = setCookieHeader;
                    }

                    options.Type = RestResultType.STRING;

                    string contentType = resultBag.HttpResponseMessage.Content.Headers.ContentType?.ToString()
                                         ??
                                         (resultBag.HttpResponseMessage.Content.Headers.ToList()
                                          .FirstOrDefault(a => a.Key.ToLower() == "content-type")
                                          .Value?.FirstOrDefault() ?? "");

                    if (contentType.Contains("/json"))
                    {
                        options.Type = RestResultType.JSON;
                    }
                    else if (contentType.Contains("/xml"))
                    {
                        options.Type = RestResultType.XML;
                    }

                    var stringResult = resultBag.HttpResponseMessage.Content.ReadAsStringAsync().Result;
                    if (typeof(T) == typeof(string))
                    {
                        return(stringResult);
                    }

                    try
                    {
                        switch (options.Type)
                        {
                        case RestResultType.STRING:
                            return(stringResult);

                        case RestResultType.JSON:
                            return(JsonConvert.DeserializeObject <T>(stringResult));

                        case RestResultType.XML:
                            using (var stringReader = new StringReader(stringResult))
                            {
                                var serializer = new XmlSerializer(typeof(T));
                                return((T)serializer.Deserialize(stringReader));
                            }

                        default:
                            log4net.LogManager.GetLogger(typeof(RestServiceConsumer))
                            .Warn($"Don't know how to convert response to type: {options.Type}");
                            break;
                        }
                    }
                    catch (Exception e)
                    {
                        log4net.LogManager.GetLogger(typeof(RestServiceConsumer))
                        .Error($"Could not deserialize to type: {options.Type}, returning raw string!", e);

                        return(stringResult);
                    }


                    /*switch (options.Type)
                     * {
                     *  case RestResultType.STRING:
                     *      return response.Content.ReadAsStringAsync().Result;
                     *  case RestResultType.JSON:
                     *      object convertedJson;
                     *      var stream = response.Content.ReadAsStreamAsync().Result;
                     *      try
                     *      {
                     *          convertedJson = response.Content.ReadAsAsync<T>().Result;
                     *      }
                     *      catch
                     *      {
                     *          stream.Seek(0, SeekOrigin.Begin);
                     *          convertedJson = response.Content.ReadAsAsync<string>().Result;
                     *      }
                     *      return convertedJson;
                     *  case RestResultType.XML:
                     *      var s = response.Content.ReadAsStringAsync().Result;
                     *      if (typeof (T) == typeof (string))
                     *      {
                     *          return s;
                     *      }
                     *      var stringReader = new StringReader(s);
                     *      var serializer = new XmlSerializer(typeof (T));
                     *      return (T) serializer.Deserialize(stringReader);
                     *
                     * }*/
                    return(default(T));
                }


                throw new ApplicationException($"{(int)resultBag.HttpResponseMessage.StatusCode} ({resultBag.HttpResponseMessage.ReasonPhrase})");
            }
        }