Inheritance: RestSharp.RestRequest
 void CacheData(RestRequestWithCache request, IRestClient restClient, object data)
 {
     if (data != null)
     {
         cache.Set(CacheKey(restClient, request, data.GetType()), data, new CacheItemPolicy());
     }
 }
Exemple #2
0
        public IEnumerable <StoredMessage> GetConversationById(string conversationId)
        {
            var request  = new RestRequestWithCache(String.Format(ConversationEndpoint, conversationId), RestRequestWithCache.CacheStyle.IfNotModified);
            var messages = GetModel <List <StoredMessage> >(request) ?? new List <StoredMessage>();

            return(messages);
        }
        public async Task <IEnumerable <StoredMessage> > GetConversationById(string conversationId)
        {
            var request  = new RestRequestWithCache(string.Format(ConversationEndpoint, conversationId), RestRequestWithCache.CacheStyle.IfNotModified);
            var messages = await GetModel <List <StoredMessage> >(request).ConfigureAwait(false) ?? new List <StoredMessage>();

            return(messages);
        }
Exemple #4
0
        public void RetryMessage(string messageId)
        {
            var url     = string.Format(RetryEndpoint, messageId);
            var request = new RestRequestWithCache(url, Method.POST);

            Execute(request, _ => true);
        }
Exemple #5
0
        public IEnumerable <Endpoint> GetEndpoints()
        {
            var request  = new RestRequestWithCache(EndpointsEndpoint, RestRequestWithCache.CacheStyle.IfNotModified);
            var messages = GetModel <List <Endpoint> >(request);

            return(messages ?? new List <Endpoint>());
        }
        public async Task LoadBody(StoredMessage message)
        {
            var request = new RestRequestWithCache(message.BodyUrl, RestRequestWithCache.CacheStyle.Immutable);

            var baseUrl = message.BodyUrl;

            if (!baseUrl.StartsWith("http"))
            {
                baseUrl = null; // We use the default
            }

            message.Body = await Execute(request, response =>
            {
                var presentationBody = new PresentationBody();

                switch (response.StatusCode)
                {
                case HttpStatusCode.OK:
                    presentationBody.Text = response.Content;
                    break;

                case HttpStatusCode.NoContent:
                    presentationBody.Hint = PresentationHint.NoContent;
                    presentationBody.Text = "Body was too large and not stored. Edit ServiceControl/MaxBodySizeToStore to be larger in the ServiceControl configuration.";
                    break;
                }

                return(presentationBody);
            }, baseUrl).ConfigureAwait(false);
        }
        public async Task <string> GetVersion()
        {
            var request = new RestRequestWithCache(RestRequestWithCache.CacheStyle.Immutable);

            var header = await Execute(request, restResponse => restResponse.Headers.SingleOrDefault(x => x.Name == ServiceControlHeaders.ParticularVersion)).ConfigureAwait(false);

            return(header == null ? null : header.Value.ToString());
        }
        Task <PagedResult <T> > GetPagedResult <T>(RestRequestWithCache request, string url = null) where T : class, new()
        {
            var result = Execute <PagedResult <T>, List <T> >(request, response =>
            {
                string first = null, prev = null, next = null, last = null;
                var links    = (string)response.Headers.FirstOrDefault(header => header.Name == ServiceControlHeaders.Link)?.Value;
                if (links != null)
                {
                    var linksByRel = linkExpression.Matches(links)
                                     .Cast <Match>()
                                     .ToDictionary(match => match.Groups[2].Value, match => match.Groups[1].Value);

                    linksByRel.TryGetValue("first", out first);
                    linksByRel.TryGetValue("prev", out prev);
                    linksByRel.TryGetValue("next", out next);
                    linksByRel.TryGetValue("last", out last);
                }

                var requestQueryParameters = HttpUtility.ParseQueryString(url ?? request.Resource);

                var pageSize = DefaultPageSize;
                var perPage  = requestQueryParameters["per_page"];
                if (perPage != null)
                {
                    pageSize = int.Parse(perPage);
                }

                var pageSizeText = (string)response.Headers.FirstOrDefault(header => header.Name == ServiceControlHeaders.PageSize)?.Value;
                if (pageSizeText != null)
                {
                    pageSize = int.Parse(pageSizeText);
                }

                var currentPage = 1;
                var page        = requestQueryParameters["page"];
                if (page != null)
                {
                    currentPage = int.Parse(page);
                }

                return(new PagedResult <T>
                {
                    CurrentPage = currentPage,
                    Result = response.Data,
                    NextLink = next,
                    PrevLink = prev,
                    LastLink = last,
                    FirstLink = first,
                    TotalCount = int.Parse(response.Headers.First(x => x.Name == ServiceControlHeaders.TotalCount).Value.ToString()),
                    PageSize = pageSize
                });
            },
                                                              url);

            return(result);
        }
Exemple #9
0
        PagedResult <T> GetPagedResult <T>(RestRequestWithCache request) where T : class, new()
        {
            var result = Execute <PagedResult <T>, List <T> >(request, response => new PagedResult <T>
            {
                Result     = response.Data,
                TotalCount = int.Parse(response.Headers.First(x => x.Name == ServiceControlHeaders.TotalCount).Value.ToString())
            });

            return(result);
        }
        public Task RetryMessage(string messageId, string instanceId)
        {
            var url = instanceId != null?
                      string.Format(RetryEndpoint + "?instance_id={1}", messageId, instanceId) :
                          string.Format(RetryEndpoint, messageId);

            var request = new RestRequestWithCache(url, Method.POST);

            return(Execute(request, _ => true));
        }
 public Task <PagedResult <StoredMessage> > GetAuditMessages(string link)
 {
     if (IsAbsoluteUrl(link))
     {
         var request = new RestRequestWithCache("", RestRequestWithCache.CacheStyle.IfNotModified);
         return(GetPagedResult <StoredMessage>(request, link));
     }
     else
     {
         var request = new RestRequestWithCache(link, RestRequestWithCache.CacheStyle.IfNotModified);
         return(GetPagedResult <StoredMessage>(request));
     }
 }
        public async Task <IEnumerable <KeyValuePair <string, string> > > GetMessageData(SagaMessage message)
        {
            var request = new RestRequestWithCache(string.Format(MessageBodyEndpoint, message.MessageId), message.Status == MessageStatus.Successful ? RestRequestWithCache.CacheStyle.Immutable : RestRequestWithCache.CacheStyle.IfNotModified);

            var body = await Execute(request, response => response.Content).ConfigureAwait(false);

            if (body == null)
            {
                return(Enumerable.Empty <KeyValuePair <string, string> >());
            }

            return(body.StartsWith("<?xml") ? GetXmlData(body) : JsonPropertiesHelper.ProcessValues(body));
        }
        void LogRequest(RestRequestWithCache request)
        {
            var resource = request.Resource != null?request.Resource.TrimStart('/') : string.Empty;

            var url = connection.Url != null?connection.Url.TrimEnd('/') : string.Empty;

            LogTo.Information("HTTP {Method} {url:l}/{resource:l} ({CacheSyle})", request.Method, url, resource, request.CacheSyle);

            foreach (var parameter in request.Parameters)
            {
                LogTo.Debug("Request Parameter: {Name} : {Value}",
                            parameter.Name,
                            parameter.Value);
            }
        }
        public async Task <IEnumerable <Endpoint> > GetEndpoints()
        {
            var rootUrls = await GetRootUrls().ConfigureAwait(false);

            var endpointsUrl = rootUrls?.KnownEndpointsUrl ?? rootUrls?.EndpointsUrl ?? DefaultEndpointsEndpoint;

            if (Uri.TryCreate(endpointsUrl, UriKind.Absolute, out var endpointsUri) &&
                Uri.TryCreate(connection.Url, UriKind.Absolute, out var connectionUri))
            {
                endpointsUrl = endpointsUri.PathAndQuery.Replace(connectionUri.PathAndQuery, string.Empty);
            }

            var request   = new RestRequestWithCache(endpointsUrl, RestRequestWithCache.CacheStyle.IfNotModified);
            var endpoints = await GetModel <List <Endpoint> >(request).ConfigureAwait(false);

            return(endpoints ?? new List <Endpoint>());
        }
 Task <T> GetModel <T>(RestRequestWithCache request, bool truncateLargeLists = false)
     where T : class, new() => Execute <T, T>(request, response => response.Data, truncateLargeLists : truncateLargeLists);
        Task <ServiceControlRootUrls> GetRootUrls()
        {
            var request = new RestRequestWithCache("/", RestRequestWithCache.CacheStyle.Immutable);

            return(GetModel <ServiceControlRootUrls>(request));
        }
Exemple #17
0
 T GetModel <T>(RestRequestWithCache request)
     where T : class, new()
 {
     return(Execute <T, T>(request, response => response.Data));
 }
Exemple #18
0
        T Execute <T>(RestRequestWithCache request, Func <IRestResponse, T> selector, string baseUrl = null)
        {
            var cacheStyle = request.CacheSyle;
            var restClient = CreateClient(baseUrl);

            switch (cacheStyle)
            {
            case RestRequestWithCache.CacheStyle.None:
                break;

            case RestRequestWithCache.CacheStyle.Immutable:
                var item = cache.Get(CacheKey <T>(restClient, request));

                if (item != null)
                {
                    return((T)item);
                }

                break;

            case RestRequestWithCache.CacheStyle.IfNotModified:
                var obj = cache.Get(CacheKey <T>(restClient, request));

                if (obj != null)
                {
                    var tuple = (Tuple <string, T>)obj;
                    request.AddHeader("If-None-Match", tuple.Item1);
                }

                break;
            }

            LogRequest(request);

            var response = restClient.Execute(request);

            var data = default(T);

            switch (cacheStyle)
            {
            case RestRequestWithCache.CacheStyle.Immutable:
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    data = ProcessResponse(selector, response);
                    CacheData(request, restClient, data);
                }
                // https://github.com/Particular/FeatureDevelopment/issues/296
                else if (response.StatusCode == HttpStatusCode.NoContent)
                {
                    data = ProcessResponse(selector, response);
                    CacheData(request, restClient, data);
                }

                break;

            case RestRequestWithCache.CacheStyle.IfNotModified:
                switch (response.StatusCode)
                {
                case HttpStatusCode.OK:
                    data = ProcessResponse(selector, response);
                    var etag = response.Headers.FirstOrDefault(h => h.Name == "ETag");
                    if (etag != null)
                    {
                        CacheData(request, restClient, Tuple.Create(etag.Value.ToString(), data));
                    }
                    break;

                case HttpStatusCode.NotModified:
                    LogResponse(response);

                    var obj = cache.Get(CacheKey <T>(restClient, request));

                    if (obj != null)
                    {
                        var tuple = (Tuple <string, T>)obj;
                        data = tuple.Item2;
                    }
                    break;
                }
                break;

            default:
                data = ProcessResponse(selector, response);
                break;
            }

            return(data);
        }
        async Task <T> Execute <T, T2>(RestRequestWithCache request, Func <IRestResponse <T2>, T> selector, string url = null)
            where T : class, new()
            where T2 : class, new()
        {
            var cacheStyle = request.CacheSyle;
            var restClient = CreateClient(url);

            switch (cacheStyle)
            {
            case RestRequestWithCache.CacheStyle.None:
                break;

            case RestRequestWithCache.CacheStyle.Immutable:
                var item = cache.Get(CacheKey <T>(restClient, request));

                if (item != null)
                {
                    return((T)item);
                }

                break;

            case RestRequestWithCache.CacheStyle.IfNotModified:
                var obj = cache.Get(CacheKey <T>(restClient, request));

                if (obj != null)
                {
                    var tuple = (Tuple <string, T>)obj;
                    request.AddHeader("If-None-Match", tuple.Item1);
                }

                break;
            }

            LogRequest(request);

            var response = await restClient.ExecuteTaskAsync <T2>(request).ConfigureAwait(false);

            CleanResponse(response);

            var data = default(T);

            switch (cacheStyle)
            {
            case RestRequestWithCache.CacheStyle.Immutable:
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    data = ProcessResponse(selector, response);
                    CacheData(request, restClient, data);
                }
                break;

            case RestRequestWithCache.CacheStyle.IfNotModified:
                switch (response.StatusCode)
                {
                case HttpStatusCode.OK:
                    data = ProcessResponse(selector, response);
                    var etag = response.Headers.FirstOrDefault(h => h.Name == "ETag");
                    if (etag != null)
                    {
                        CacheData(request, restClient, Tuple.Create(etag.Value.ToString(), data));
                    }
                    break;

                case HttpStatusCode.NotModified:
                    LogResponse(response);

                    var obj = cache.Get(CacheKey <T>(restClient, request));

                    if (obj != null)
                    {
                        var tuple = (Tuple <string, T>)obj;
                        data = tuple.Item2;
                    }
                    break;
                }
                break;

            default:
                data = ProcessResponse(selector, response);
                break;
            }

            return(data);
        }
 Task <T> GetModel <T>(RestRequestWithCache request)
     where T : class, new() => Execute <T, T>(request, response => response.Data);