private static string GetNextUrl<T>(PaginatedResults<T> pagenatedResults, string request) { int nextIndex = pagenatedResults.startIndex + pagenatedResults.itemsPerPage; if (pagenatedResults.totalResults <= nextIndex) { return null; } return string.Format("{0}{1}$startIndex={2}", request, request.Contains("?") ? "&" : "?", nextIndex); }
private static List<TConverted> ExecuteRequestAndGetDeserializedResponse<TDeserialize, TConverted>(string accessToken, string requestUrl, DateTime? fromDate, Func<TDeserialize, TConverted> conversionFunc) where TDeserialize : class { string authorizationHeader = string.Format("Bearer {0}", accessToken); string monthPart = !fromDate.HasValue ? string.Empty : string.Format("?{0}", string.Format(config.RequestForDatesPart, fromDate.Value.ToString("dd/MM/yyyy"), DateTime.UtcNow.ToString("dd/MM/yyyy")).Replace('-', '/')); string fullRequest = string.Format("{0}{1}", requestUrl, monthPart); var request = new RestRequest(Method.GET) { Resource = fullRequest }; request.AddHeader("Authorization", authorizationHeader); var client = new RestClient(new Uri(SageConfig.SageBaseUri)); log.Info("Making sage request:{0}", fullRequest); IRestResponse response = client.Execute(request); PaginatedResults<TDeserialize> deserializedResponse = CreateDeserializedItems<TDeserialize>(CleanResponse(response.Content, typeof(TDeserialize).Name)); if (deserializedResponse == null) { log.Error("Sage response deserialization failed"); return new List<TConverted>(); } log.Info("Successfully serialized sage response"); var results = new List<TConverted>(); FillFromDeserializedData(deserializedResponse, results, conversionFunc); string nextUrl = GetNextUrl(deserializedResponse, fullRequest); while (nextUrl != null) { request = new RestRequest(Method.GET) { Resource = nextUrl }; request.AddHeader("Authorization", authorizationHeader); log.Info("Making another sage request:{0}", nextUrl); response = client.Execute(request); deserializedResponse = CreateDeserializedItems<TDeserialize>(CleanResponse(response.Content, typeof(TDeserialize).Name)); if (deserializedResponse == null) { log.Error("Sage response deserialization failed"); return new List<TConverted>(); } FillFromDeserializedData(deserializedResponse, results, conversionFunc); nextUrl = GetNextUrl(deserializedResponse, fullRequest); } log.Info("Finished retreiving sage request"); return results; }
private static void FillFromDeserializedData<TDeserialize, TConverted>(PaginatedResults<TDeserialize> deserializedResponse, List<TConverted> list, Func<TDeserialize, TConverted> conversionFunc) { foreach (var deserializePaymentStatus in deserializedResponse.resources) { TryConvertDeserialized(list, deserializePaymentStatus, conversionFunc); } }