public static LinkHeader AddDataOnLinkHeader <T>(LinkHeader item) { LinkHeader LH = new LinkHeader(); try { using (FacilitiesEntities _dbContext = new FacilitiesEntities()) { var data = _dbContext.CGSLinkHeaders.Where(x => x.Action == item.Action).FirstOrDefault(); if (data != null) { LH.LinkHeaderId = Guid.NewGuid(); LH.CGSLinkHeader = data.CGSLinkHeaderId; LH.Action = data.Action; LH.RandomString = item.RandomString; LH.BeginDate = DateTime.Now; var TimeFrame = data.Timeframe; var endDate = DateTime.Now; endDate = endDate.AddDays(TimeFrame); LH.EndDate = endDate; _dbContext.LinkHeaders.Add(LH); _dbContext.SaveChanges(); } } return(LH); } catch (Exception ex) { return(null); } }
public async Task <WordPressApi> DiscoverApiForSite() { var response = await this.httpClient.GetAsync(this.SiteUri, HttpCompletionOption.ResponseHeadersRead); var headers = response.Headers; var linkHeaders = headers.GetValues("Link"); foreach (var linkHeader in linkHeaders) { try { var header = new LinkHeader(linkHeader); if (header.Relation == WpApiLinkRel) { return(new WordPressApi { ApiRootUri = header.LinkUri }); } } catch (ArgumentException ex) { // log malformed Link header } } // throw exception? return(null); }
/// <summary> /// Accumulates all the elements in a paginated response, then deserializes each element as <c>TElement</c>. /// </summary> /// <param name="response">The first response received after initiating the request.</param> /// <typeparam name="TElement">The model type of the elements returned in the response.</typeparam> /// <returns>The list of deserialized elements.</returns> private async Task <List <TElement> > AccumulateDeserializePages <TElement>(HttpResponseMessage response) { response.AssertSuccess(); var pages = new List <HttpContent> { response.Content }; while (response.Headers.TryGetValues("Link", out IEnumerable <string> linkValues)) { var links = LinkHeader.LinksFromHeader(linkValues.First()); if (links?.NextLink == null) { break; } response = await _client.GetAsync(links.NextLink); response.AssertSuccess(); pages.Add(response.Content); } var accumulated = new List <TElement>(); foreach (var content in pages) { var responseStr = await content.ReadAsStringAsync(); accumulated.AddRange(JsonConvert.DeserializeObject <List <TElement> >(responseStr)); } return(accumulated); }
/// <summary> /// Accumulates all the elements in a paginated response. /// </summary> /// <param name="response">The first response received after initiating the request.</param> /// <returns>The list of JSON elements.</returns> private async Task <List <JToken> > AccumulatePages(HttpResponseMessage response) { response.AssertSuccess(); var pages = new List <HttpContent> { response.Content }; while (response.Headers.TryGetValues("Link", out var linkValues)) { var links = LinkHeader.LinksFromHeader(linkValues.First()); if (links?.NextLink == null) { break; } response = await _client.GetAsync(links.NextLink); response.AssertSuccess(); pages.Add(response.Content); } var accumulated = new List <JToken>(); foreach (var content in pages) { var responseStr = await content.ReadAsStringAsync(); accumulated.AddRange(JToken.Parse(responseStr)); } return(accumulated); }
private async IAsyncEnumerable <TElement> StreamDeserializePages <TElement>(HttpResponseMessage response) { var firstPage = JsonConvert.DeserializeObject <List <TElement> >(await response.AssertSuccess() .Content .ReadAsStringAsync()); foreach (var e in firstPage) { yield return(e); } while (response.Headers.TryGetValues("Link", out IEnumerable <string> linkValues)) { var links = LinkHeader.LinksFromHeader(linkValues.First()); if (links?.NextLink == null) { break; } response = await _client.GetAsync(links.NextLink); var content = response.AssertSuccess().Content; var list = JsonConvert.DeserializeObject <List <TElement> >(await content.ReadAsStringAsync()); foreach (var e in list) { yield return(e); } } }
protected static bool VerifyHeaders(HttpHeaders headers, out Uri hubLocation) { IEnumerable <string> headerValues; if (!headers.TryGetValues("link", out headerValues)) { hubLocation = null; return(false); } var valueList = headerValues.ToList(); var linkHeaders = new List <LinkHeader>(); foreach (var value in valueList) { linkHeaders.AddRange(LinkHeader.Parse(value)); } if (HasRequiredHeaders(linkHeaders)) { var hub = linkHeaders.First(h => h.Relationship.Equals("hub", StringComparison.OrdinalIgnoreCase)); hubLocation = hub.Link; return(true); } hubLocation = null; return(false); }
/// <summary> /// Paginate through the search API /// </summary> /// <typeparam name="T">Result type.</typeparam> /// <param name="request">RestRequest object</param> /// <param name="collecterList">Collection to save results.</param> private void Paginate <T>(RestRequest request, List <T> collecterList) { // send the first request var response = _client.Execute <SearchResultContainer>(request); // collect the results collecterList.AddRange(response.Data.Items as List <T>); // parse the Link Header from the response var linkHeader = new LinkHeader(response.Headers.FirstOrDefault(h => h.Name == "Link")?.Value.ToString()); // we need to remove the query string parameters, because they are included in the returned link headers. request.Parameters.RemoveAll(p => p.Type == ParameterType.QueryString); // paginate through the rest of the links (if any) and collect the results while (linkHeader.Next != null) { // remove the baseUrl from the link string request.Resource = linkHeader.Next.Replace(_client.BaseUrl.ToString(), ""); // execute the request to get issues response = _client.Execute <SearchResultContainer>(request); // collect the results into the issues list collecterList.AddRange(response.Data.Items as List <T>); // update linkHeader URL to the next one linkHeader = new LinkHeader(response.Headers.FirstOrDefault(h => h.Name == "Link")?.Value.ToString()); } }
private void List_OnSelectionChanged(object sender, SelectionChangedEventArgs e) { ExtendedLongListSelector longListSelector = (ExtendedLongListSelector)sender; LinkHeader item = longListSelector.SelectedItem as LinkHeader; if (item == null) { return; } longListSelector.SelectedItem = ((object)null); if (!this._isPicker) { Navigator.Current.NavigateToUserProfile(item.Id, item.User.Name, "", false); } else if (item.Id != AppGlobalStateManager.Current.LoggedInUserId && (this.ViewModel.Managers == null || this.ViewModel.Managers.All <User>((Func <User, bool>)(m => m.id != item.Id)))) { if (!this._isBlockingPicker) { Navigator.Current.NavigateToCommunityManagementManagerAdding(this.ViewModel.CommunityId, this.ViewModel.CommunityType, item.User, true); } else { Navigator.Current.NavigateToCommunityManagementBlockAdding(this.ViewModel.CommunityId, item.User, false); } } else { new GenericInfoUC().ShowAndHideLater(CommonResources.Error, (FrameworkElement)null); } }
public async Task <IEnumerable <GithubRepository> > GetAllReposAsync(string organization, int resultsPerPage) { string cacheKey = $"repos|{organization}|{resultsPerPage}"; var cachedResponse = _cache.Get <List <OrganizationRepository> >(cacheKey); if (cachedResponse != null) { return(cachedResponse); } var results = new List <OrganizationRepository>(); var parsedHeader = new LinkHeader(); var url = $"{_remoteServiceBaseUrl}/orgs/{organization}/repos?page=1&per_page={resultsPerPage}"; do { var response = await _httpClient.GetAsync(url); var linkHeader = new List <string>().AsEnumerable(); response.Headers.TryGetValues("Link", out linkHeader); parsedHeader = linkHeader?.First().FromHeader(); if (response.IsSuccessStatusCode) { var data = await response.Content.ReadAsStringAsync(); results.AddRange(JsonConvert.DeserializeObject <List <OrganizationRepository> >(data)); url = parsedHeader?.NextLink; } } while (parsedHeader?.NextLink != null); _cache.Set(cacheKey, results, DateTimeOffset.Now.AddHours(1)); return(results); }
private void RemoveFromCommunity_OnClicked(object sender, RoutedEventArgs e) { LinkHeader dataContext = ((FrameworkElement)sender).DataContext as LinkHeader; if (dataContext == null || MessageBox.Show(CommonResources.GenericConfirmation, CommonResources.RemovingFromCommunity, (MessageBoxButton)1) != MessageBoxResult.OK) { return; } this.ViewModel.RemoveFromCommunity(dataContext); }
private void Edit_OnClicked(object sender, RoutedEventArgs e) { LinkHeader dataContext = ((FrameworkElement)sender).DataContext as LinkHeader; if (dataContext == null) { return; } this.ViewModel.NavigateToManagerEditing(dataContext); }
private void Block_OnClicked(object sender, RoutedEventArgs e) { LinkHeader dataContext = ((FrameworkElement)sender).DataContext as LinkHeader; if (dataContext == null) { return; } Navigator.Current.NavigateToCommunityManagementBlockAdding(this._communityId, dataContext.User, true); }
private void AddToManagers_OnClicked(object sender, RoutedEventArgs e) { LinkHeader dataContext = ((FrameworkElement)sender).DataContext as LinkHeader; if (dataContext == null) { return; } Navigator.Current.NavigateToCommunityManagementManagerAdding(this.ViewModel.CommunityId, this.ViewModel.CommunityType, dataContext.User, false); }
public void It_can_serialize_round_trip() { const string input = "</v2/colors?page=117&page_size=5>; rel=previous, </v2/colors?page=119&page_size=5>; rel=next, </v2/colors?page=118&page_size=5>; rel=self, </v2/colors?page=0&page_size=5>; rel=first, </v2/colors?page=119&page_size=5>; rel=last"; var sut = LinkHeader.Parse(input); var actual = sut.ToString(); Assert.Equal(input, actual); }
internal void TestDelete(string url, out bool success, out JToken response, out LinkHeader links, params ValueTuple <string, string>[] args) { var r = _client.DeleteAsync(url + BuildDuplicateKeyQueryString(args)).Result; response = JToken.Parse(r.Content.ReadAsStringAsync().Result); success = r.IsSuccessStatusCode; r.Headers.TryGetValues("Link", out var l); links = l?.First().ConvertIfNotNull(LinkHeader.LinksFromHeader); }
private void linksList_OnSelectionChanged(object sender, SelectionChangedEventArgs e) { LinkHeader selectedItem = this.linksList.SelectedItem as LinkHeader; this.linksList.SelectedItem = null; if (selectedItem == null) { return; } Navigator.Current.NavigateToWebUri(selectedItem.Url, false, false); }
private void List_OnSelectionChanged(object sender, SelectionChangedEventArgs e) { LinkHeader selectedItem = this.List.SelectedItem as LinkHeader; if (selectedItem == null) { return; } this.List.SelectedItem = ((object)null); Navigator.Current.NavigateToUserProfile(selectedItem.Id, "", "", false); }
public void parse_no_links_exist_return_null_page_links() { var rsp = new HttpResponseMessage(); var sut = new LinkHeader(); var result = sut.Parse(rsp.Headers); Assert.Null(result.FirstPage); Assert.Null(result.PreviousPage); Assert.Null(result.NextPage); Assert.Null(result.LastPage); }
private void List_OnSelectionChanged(object sender, SelectionChangedEventArgs e) { ExtendedLongListSelector longListSelector = (ExtendedLongListSelector)sender; LinkHeader selectedItem = longListSelector.SelectedItem as LinkHeader; if (selectedItem == null) { return; } longListSelector.SelectedItem = null; Navigator.Current.NavigateToUserProfile(selectedItem.Id, "", "", false); }
private void ContextMenu_OnEditClicked(object sender, RoutedEventArgs e) { MenuItem menuItem = sender as MenuItem; ContextMenu contextMenu = (menuItem != null ? ((FrameworkElement)menuItem).Parent : (DependencyObject)null) as ContextMenu; FrameworkElement frameworkElement = (contextMenu != null ? contextMenu.Owner : (DependencyObject)null) as FrameworkElement; LinkHeader linkHeader = (frameworkElement != null ? frameworkElement.DataContext : (object)null) as LinkHeader; if (linkHeader == null) { return; } Navigator.Current.NavigateToCommunityManagementBlockEditing(this.ViewModel.CommunityId, linkHeader.User, linkHeader.User.ban_info.manager); }
private void ContextMenu_OnDeleteClicked(object sender, RoutedEventArgs e) { MenuItem menuItem = sender as MenuItem; ContextMenu contextMenu = (menuItem != null ? ((FrameworkElement)menuItem).Parent : (DependencyObject)null) as ContextMenu; FrameworkElement frameworkElement = (contextMenu != null ? contextMenu.Owner : (DependencyObject)null) as FrameworkElement; LinkHeader linkHeader = (frameworkElement != null ? frameworkElement.DataContext : (object)null) as LinkHeader; if (linkHeader == null || MessageBox.Show(CommonResources.GenericConfirmation, CommonResources.LinkRemoving, (MessageBoxButton)1) != MessageBoxResult.OK) { return; } this.ViewModel.DeleteLink(linkHeader); }
private void ContextMenu_OnUnblockClicked(object sender, RoutedEventArgs e) { MenuItem menuItem = sender as MenuItem; ContextMenu contextMenu = (menuItem != null ? ((FrameworkElement)menuItem).Parent : (DependencyObject)null) as ContextMenu; FrameworkElement frameworkElement = (contextMenu != null ? contextMenu.Owner : (DependencyObject)null) as FrameworkElement; LinkHeader linkHeader = (frameworkElement != null ? frameworkElement.DataContext : (object)null) as LinkHeader; if (linkHeader == null) { return; } this.ViewModel.UnblockUser(linkHeader); }
public void It_can_parse_link_headers() { const string input = "</v2/colors?page=117&page_size=5>; rel=previous, </v2/colors?page=119&page_size=5>; rel=next, </v2/colors?page=118&page_size=5>; rel=self, </v2/colors?page=0&page_size=5>; rel=first, </v2/colors?page=119&page_size=5>; rel=last"; var actual = LinkHeader.Parse(input); Assert.Collection( actual.Links, next => LinkFact.IsLink(next, "previous", "/v2/colors?page=117&page_size=5"), next => LinkFact.IsLink(next, "next", "/v2/colors?page=119&page_size=5"), next => LinkFact.IsLink(next, "self", "/v2/colors?page=118&page_size=5"), next => LinkFact.IsLink(next, "first", "/v2/colors?page=0&page_size=5"), next => LinkFact.IsLink(next, "last", "/v2/colors?page=119&page_size=5") ); }
private async IAsyncEnumerable <T[]> GetList <T>(string?startUrl, int maxNumber, [EnumeratorCancellation] CancellationToken cancellationToken, Func <T[], Task <T[]> >?processing = null) { var counter = 0; while (!string.IsNullOrEmpty(startUrl)) { if (cancellationToken.IsCancellationRequested || counter > maxNumber) { yield break; } using var request = new HttpRequestMessage(HttpMethod.Get, startUrl); using var httpResponse = await _httpClient.SendAsync(request, cancellationToken /* throws exception on cancellation */); if (httpResponse.IsSuccessStatusCode) { startUrl = null; var links = LinkHeader.LinksFromHeader(httpResponse); if (!string.IsNullOrEmpty(links?.NextLink)) { startUrl = links.NextLink; } await using var stream = await httpResponse.Content.ReadAsStreamAsync(cancellationToken); var responseArray = await JsonSerializer.DeserializeAsync <T[]>(stream, new JsonSerializerOptions { PropertyNameCaseInsensitive = true }, cancellationToken); if (responseArray == null) { LogResponseError("Failed to parse response", httpResponse); yield break; } if (processing != null) { responseArray = await processing(responseArray); } counter += responseArray.Length; yield return(responseArray); } else { LogResponseError("Failed to fetch a page", httpResponse); } } }
public void RemoveInvitation(LinkHeader item) { this.SetInProgress(true, ""); GroupsService.Current.HandleRequest(this.CommunityId, item.Id, false, (Action <BackendResult <int, ResultCode> >)(result => Execute.ExecuteOnUIThread((Action)(() => { if (result.ResultCode == ResultCode.Succeeded) { this.Invitations.Delete(item); } else { GenericInfoUC.ShowBasedOnResult((int)result.ResultCode, "", null); } this.SetInProgress(false, ""); })))); }
public static LinkHeader LinksFromHeader(string linkHeaderStr) { LinkHeader linkHeader = null; if (!string.IsNullOrWhiteSpace(linkHeaderStr)) { string[] linkStrings = linkHeaderStr.Split(','); if (linkStrings != null && linkStrings.Any()) { linkHeader = new LinkHeader(); foreach (string linkString in linkStrings) { var relMatch = Regex.Match(linkString, "(?<=rel=\").+?(?=\")", RegexOptions.IgnoreCase); var linkMatch = Regex.Match(linkString, "(?<=<).+?(?=>)", RegexOptions.IgnoreCase); if (relMatch.Success && linkMatch.Success) { string rel = relMatch.Value.ToUpper(); string link = linkMatch.Value; switch (rel) { case "FIRST": linkHeader.FirstLink = link; break; case "PREV": linkHeader.PrevLink = link; break; case "NEXT": linkHeader.NextLink = link; break; case "LAST": linkHeader.LastLink = link; break; } } } } } return(linkHeader); }
/// <inheritdoc/> public async Task <SearchResults> SearchRepo(SearchOptions searchOption) { string giteaSearchUriString = BuildSearchQuery(searchOption); SearchResults searchResults = null; HttpResponseMessage response = await _httpClient.GetAsync(giteaSearchUriString); if (response.StatusCode == HttpStatusCode.OK) { searchResults = await response.Content.ReadAsAsync <SearchResults>(); if (response.Headers.TryGetValues("X-Total-Count", out IEnumerable <string> countValues)) { searchResults.TotalCount = Convert.ToInt32(countValues.First()); } if (response.Headers.TryGetValues("Link", out IEnumerable <string> linkValues)) { LinkHeader linkHeader = LinkHeader.LinksFromHeader(linkValues.First()); if (!string.IsNullOrEmpty(linkHeader.LastLink)) { Uri linkUri = new Uri(linkHeader.LastLink); string page = HttpUtility.ParseQueryString(linkUri.Query).Get("page"); if (int.TryParse(page, out int lastPage)) { searchResults.TotalPages = lastPage; } } else { searchResults.TotalPages = searchOption.Page; } } if (searchResults.TotalCount > 0 && searchResults.TotalPages == 0) { searchResults.TotalPages = 1; } } else { _logger.LogError("User " + AuthenticationHelper.GetDeveloperUserName(_httpContextAccessor.HttpContext) + " SearchRepository failed with statuscode " + response.StatusCode); } return(searchResults); }
public void parse_link_header_format_changed_return_null_page_links() { var linkHeader = $"{_first},{_prev}"; var rsp = new HttpResponseMessage(); rsp.Headers.Add("link", new List <string> { linkHeader, linkHeader }); var sut = new LinkHeader(); var result = sut.Parse(rsp.Headers); Assert.Null(result.FirstPage); Assert.Null(result.PreviousPage); Assert.Null(result.NextPage); Assert.Null(result.LastPage); }
public void parse_url_delimiter_changed_return_null_page_links() { var linkHeader = $"{_first.Replace(';', ':')}"; var rsp = new HttpResponseMessage(); rsp.Headers.Add("link", new List <string> { linkHeader, linkHeader }); var sut = new LinkHeader(); var result = sut.Parse(rsp.Headers); Assert.Null(result.FirstPage); Assert.Null(result.PreviousPage); Assert.Null(result.NextPage); Assert.Null(result.LastPage); }
public void parse_last_page_contains_first_and_previous_links_parse_out_correctly() { var linkHeader = $"{_first},{_prev}"; var rsp = new HttpResponseMessage(); rsp.Headers.Add("link", new List <string> { linkHeader }); var sut = new LinkHeader(); var result = sut.Parse(rsp.Headers); Assert.Equal(_firstUrl, result.FirstPage); Assert.Equal(_prevUrl, result.PreviousPage); Assert.Null(result.NextPage); Assert.Null(result.LastPage); }