Пример #1
0
        private static async Task <RestResult <T> > Http <T>(HttpMethod method, string endpoint, object obj = null, object query = null)
        {
            try
            {
                string q = null;

                if (query != null)
                {
                    var properties = from p in query.GetType().GetProperties()
                                     where p.GetValue(query, null) != null
                                     select p.Name + "=" + HttpUtility.UrlEncode(p.GetValue(query, null).ToString());

                    q = string.Join("&", properties.ToArray());
                }

                var request = new HttpRequestMessage(method, API + endpoint + (string.IsNullOrEmpty(q) ? "" : "?" + q));
                if (obj != null)
                {
                    request.Content = new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, "application/json");
                }
                var result = await Client.SendAsync(request);

                if (!result.IsSuccessStatusCode)
                {
                    throw new Exception(result.ReasonPhrase);
                }
                return(RestResult <T> .FromResult(JsonConvert.DeserializeObject <T>(await result.Content.ReadAsStringAsync())));
            }

            catch (Exception e)
            {
                return(RestResult <T> .FromException(e));
            }
        }
Пример #2
0
        private static async Task <RestResult <R> > SyncInherit <T, R>(Task <RestResult <T> > call, Func <T, R> transform)
        {
            var task   = new TaskCompletionSource <RestResult <R> >();
            var result = await call;

            if (result)
            {
                Sync(() => task.SetResult(RestResult <R> .FromResult(transform(result.Data))));
            }
            else
            {
                Sync(() => task.SetResult(RestResult <R> .FromException(result.Exception)));
            }

            return(await task.Task);
        }