public async Task <JObject> GetTokensAsync(string username, string password, string tenantId) { var res = await SharedHttpClient.SendAsync( new HttpRequestMessage(HttpMethod.Post, this._endpoint + "/tokens") { Headers = { Accept = { new MediaTypeWithQualityHeaderValue("application/json") }, }, Content = CreateJsonContent(new { auth = new { passwordCredentials = new { username, password }, tenantId, } }), } ).ConfigureAwait(false); using (res) { if (!res.IsSuccessStatusCode && string.Equals(res.Content?.Headers.ContentType?.MediaType, "application/json", StringComparison.OrdinalIgnoreCase)) { // エラーレスポンス throw new ConoHaApiException(await res.Content.ReadAsStringAsync().ConfigureAwait(false)); } var s = await res.EnsureSuccessStatusCode().Content .ReadAsStringAsync().ConfigureAwait(false); return(JObject.Parse(s)); } }
private static async Task <CatalogIndex> DownloadIndex() { var catalogIndexUrl = await GetCatalogIndexUrlAsync(NuGetIndexUrl); string indexString = await SharedHttpClient.GetStringAsync(catalogIndexUrl); Log.Information($"Fetched catalog index {catalogIndexUrl}"); var index = JsonConvert.DeserializeObject <CatalogIndex>(indexString); return(index); }
/// <summary> /// Pushes flight data to CloudAhoy /// </summary> /// <param name="s">The KML or GPX stream</param> /// <param name="le">The parent flight (for metadata)</param> public async Task <bool> PutStream(Stream s, LogbookEntryCore le) { if (s == null) { throw new ArgumentNullException(nameof(s)); } if (le == null) { throw new ArgumentNullException(nameof(le)); } using (MultipartFormDataContent form = new MultipartFormDataContent()) { using (StringContent sc = new StringContent(JsonConvert.SerializeObject(new CloudAhoyPostFileMetaData(le)))) { form.Add(sc, "METADATA"); using (StreamContent streamContent = new StreamContent(s)) { form.Add(streamContent, "IMPORT", "data.gpx"); string szResult = (string)await SharedHttpClient.GetResponseForAuthenticatedUri(new Uri(FlightsEndpoint), AuthState.AccessToken, form, (response) => { string result = string.Empty; try { result = response.Content.ReadAsStringAsync().Result; response.EnsureSuccessStatusCode(); return(result); } catch (HttpRequestException ex) { throw new MyFlightbookException(ex.Message + " " + response.ReasonPhrase + " " + TextFromHTML(result), ex); } }); } } } return(true); }
private async Task <HttpResponseMessage> SendRequestAsync(HttpMethod method, string requestUri, HttpContent content) { var req = new HttpRequestMessage(method, requestUri) { Headers = { Accept = { new MediaTypeWithQualityHeaderValue("application/json") }, }, Content = content, }; req.Headers.TryAddWithoutValidation("X-Auth-Token", this._token); var res = await SharedHttpClient.SendAsync(req).ConfigureAwait(false); if (!res.IsSuccessStatusCode && string.Equals(res.Content?.Headers.ContentType?.MediaType, "application/json", StringComparison.OrdinalIgnoreCase)) { // エラーレスポンス using (res) throw new ConoHaApiException(await res.Content.ReadAsStringAsync().ConfigureAwait(false)); } return(res.EnsureSuccessStatusCode()); }
private static async Task <CatalogPage> DownloadPage(CatalogPageIdentifier pageId) { var pageString = await SharedHttpClient.GetStringAsync(pageId.Url); return(JsonConvert.DeserializeObject <CatalogPage>(pageString)); }
/// <summary> /// Retrieves flights from cloudahoy /// </summary> /// <param name="szUserName">User for whome the flights are being retrieved</param> /// <param name="dtEnd">End date for date range</param> /// <param name="dtStart">Start date for date range</param> /// <exception cref="HttpRequestException"></exception> /// <returns></returns> public async Task <CloudAhoyFlightCollection> GetFlights(string szUserName, DateTime?dtStart, DateTime?dtEnd) { if (dtStart.HasValue && dtEnd.HasValue && dtEnd.Value.CompareTo(dtStart.Value) <= 0) { throw new MyFlightbookValidationException("Invalid date range"); } string szResult = string.Empty; UriBuilder builder = new UriBuilder(FlightsEndpoint); NameValueCollection nvc = HttpUtility.ParseQueryString(builder.Query); if (dtStart.HasValue) { nvc["start"] = (new DateTime(dtStart.Value.Year, dtStart.Value.Month, dtStart.Value.Day, 0, 0, 0, DateTimeKind.Utc)).UnixSeconds().ToString(CultureInfo.InvariantCulture); } if (dtEnd.HasValue) { nvc["end"] = (new DateTime(dtEnd.Value.Year, dtEnd.Value.Month, dtEnd.Value.Day, 23, 59, 59, DateTimeKind.Utc)).UnixSeconds().ToString(CultureInfo.InvariantCulture); } CloudAhoyFlightCollection lstResult = new CloudAhoyFlightCollection(); for (int iPage = 1; iPage < 20; iPage++) { nvc["page"] = iPage.ToString(CultureInfo.InvariantCulture); builder.Query = nvc.ToString(); bool fHasMore = false; IEnumerable <CloudAhoyFlight> flights = (IEnumerable <CloudAhoyFlight>) await SharedHttpClient.GetResponseForAuthenticatedUri(builder.Uri, AuthState.AccessToken, HttpMethod.Get, (response) => { try { fHasMore = false; if (response.Headers.TryGetValues("ca-has-more", out IEnumerable <string> values)) { fHasMore = Convert.ToBoolean(values.First(), CultureInfo.InvariantCulture); } szResult = response.Content.ReadAsStringAsync().Result; response.EnsureSuccessStatusCode(); CloudAhoyFlight[] rgFlights = JsonConvert.DeserializeObject <CloudAhoyFlight[]>(szResult, new JsonSerializerSettings() { DefaultValueHandling = DefaultValueHandling.Ignore }); if (szUserName != null) { foreach (CloudAhoyFlight caf in rgFlights) { caf.UserName = szUserName; } } return(rgFlights); } catch (HttpRequestException) { throw new MyFlightbookException(response.ReasonPhrase + " " + TextFromHTML(szResult)); } }); lstResult.AddRange(flights); if (!fHasMore) { break; // don't go infnite loop! } } return(lstResult); }
private static async Task <PackageDetails> DownloadPackageDetails(CatalogPackage package) { var pageString = await SharedHttpClient.GetStringAsync(package.Url); return(JsonConvert.DeserializeObject <PackageDetails>(pageString)); }
/// <summary> /// Returns flights from Leon /// </summary> /// <param name="szUserName">Username</param> /// <param name="dtStart">Starting date</param> /// <param name="dtEnd">Ending date</param> /// <returns>An enumerable of LeonFlightEntry objects</returns> /// <exception cref="ArgumentNullException"></exception> /// <exception cref="MyFlightbookValidationException"></exception> /// <exception cref="InvalidOperationException"></exception> /// <exception cref="MyFlightbookException"></exception> public async Task <IEnumerable <LeonFlightEntry> > GetFlights(string szUserName, DateTime?dtStart, DateTime?dtEnd) { if (szUserName == null) { throw new ArgumentNullException(nameof(szUserName)); } if (dtStart.HasValue && dtEnd.HasValue && dtEnd.Value.CompareTo(dtStart.Value) <= 0) { throw new MyFlightbookValidationException("Invalid date range"); } if (AuthState == null) { throw new InvalidOperationException("No valid authstate for Leon operation"); } UriBuilder builder = new UriBuilder(FlightsEndpoint); NameValueCollection nvc = HttpUtility.ParseQueryString(builder.Query); LeonQuery lq = new LeonQuery(dtStart, dtEnd); Profile profile = Profile.GetUser(szUserName); // hack: Leon's refresh endpoint is NOT the same as the authorization token, so we can't simply call refresh if (!CheckAccessToken() && !String.IsNullOrEmpty(AuthState.RefreshToken)) { HttpWebRequest hr = (HttpWebRequest)WebRequest.Create(new Uri(RefreshEndpoint)); hr.Method = "POST"; hr.ContentType = "application/x-www-form-urlencoded"; string szPostData = "refresh_token=" + AuthState.RefreshToken; byte[] rgbData = Encoding.UTF8.GetBytes(szPostData); hr.ContentLength = rgbData.Length; using (Stream s = hr.GetRequestStream()) { s.Write(rgbData, 0, rgbData.Length); } using (WebResponse response = hr.GetResponse()) { using (StreamReader sr = new StreamReader(response.GetResponseStream())) { AuthState.AccessToken = sr.ReadToEnd(); AuthState.AccessTokenExpirationUtc = DateTime.UtcNow.AddMinutes(29);// good for 30 minutes actually profile.SetPreferenceForKey(TokenPrefKey, AuthState); } } } string szResult = string.Empty; Dictionary <string, object> d = new Dictionary <string, object>() { { "query", lq.ToString() } }; string szD = JsonConvert.SerializeObject(d); using (StringContent sc = new StringContent(szD, Encoding.UTF8, "application/json")) { return((IEnumerable <LeonFlightEntry>) await SharedHttpClient.GetResponseForAuthenticatedUri(builder.Uri, AuthState.AccessToken, sc, (response) => { try { szResult = response.Content.ReadAsStringAsync().Result; response.EnsureSuccessStatusCode(); IEnumerable <LeonFlightEntry> flights = LeonFlightEntry.FromLeonRootJSON(szResult); // set the username for each of these. foreach (LeonFlightEntry entry in flights) { entry.Username = szUserName; } return flights; } catch (HttpRequestException ex) { if (response == null) { throw new MyFlightbookException("Unknown error in LeonClient GetFlights", ex); } else { throw new MyFlightbookException("Error in LeonClient GetFlights: " + response.ReasonPhrase, ex); } } })); } }