/// <summary> /// Asynchronously download an XML and deserializes it into the specified type. /// </summary> /// <typeparam name="T">The inner type to deserialize</typeparam> /// <param name="url">The url to query</param> /// <param name="acceptEncoded">if set to <c>true</c> accept encoded response.</param> /// <param name="postData">The post data.</param> /// <param name="transform">The XSL transform to apply, may be null.</param> internal static async Task <CCPAPIResult <T> > DownloadAPIResultAsync <T>(Uri url, bool acceptEncoded = false, string postData = null, XslCompiledTransform transform = null) { DownloadResult <IXPathNavigable> asyncResult = await HttpWebClientService.DownloadXmlAsync(url, HttpMethod.Post, acceptEncoded, postData); CCPAPIResult <T> result; try { // Was there an HTTP error ? result = asyncResult.Error != null ? new CCPAPIResult <T>(asyncResult.Error) : DeserializeAPIResultCore <T>(asyncResult.Result, transform); // We got the result return(result); } catch (Exception e) { result = new CCPAPIResult <T>(HttpWebClientServiceException.Exception(url, e)); ExceptionHandler.LogException(e, false); EveMonClient.Trace( $"Method: DownloadAPIResultAsync, url: {url.AbsoluteUri}, postdata: {postData}, type: {typeof(T).Name}", false); } return(result); }
/// <summary> /// Handles the Click event of the SaveButton control. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> private async void SaveButton_Click(object sender, EventArgs e) { IXPathNavigable result = null; // Get the raw xml document to use when saving if (m_url != m_defaultUri) { APIProvider provider = EveMonClient.APIProviders.CurrentProvider; Uri nUrl = provider.GetMethodUrl((Enum)ApiTesterUIHelper.SelectedItem); string postData = m_url.Query.Replace("?", String.Empty); try { result = HttpWebClientService.DownloadXml(nUrl, HttpMethod.Post, provider.SupportsCompressedResponse, postData).Result; } catch (HttpWebClientServiceException ex) { ExceptionHandler.LogException(ex, false); } } if (result == null) { return; } string filename = Path.GetFileNameWithoutExtension(WebBrowser.Url.AbsoluteUri); await ApiTesterUIHelper.SaveDocumentAsync(filename, result); }
/// <summary> /// Tracks the event. /// </summary> /// <param name="type">The type.</param> /// <param name="category">The category.</param> /// <param name="action">The action.</param> private static void TrackEvent(Type type, string category, string action) { InitEvent(type, category, action); if (NetworkMonitor.IsNetworkAvailable) { DownloadResult <Image> result = HttpWebClientService.DownloadImage(new Uri(NetworkConstants.GoogleAnalyticsUrl), HttpMethod.Post, postdata: BuildQueryString()); if (!EveMonClient.IsDebugBuild) { return; } EveMonClient.Trace($"({category} - {action})"); if (result.Error != null) { EveMonClient.Trace($"{result.Error.Message}"); } return; } // Reschedule later otherwise Dispatcher.Schedule(TimeSpan.FromMinutes(1), () => TrackEvent(type, category, action)); if (EveMonClient.IsDebugBuild) { EveMonClient.Trace($"in {TimeSpan.FromMinutes(1)}"); } }
/// <summary> /// Scans for prices. /// </summary> /// <returns></returns> private static IEnumerable <MineralPrice> GetPrices(IMineralParser parser) { string content = String.Empty; try { content = HttpWebClientService.DownloadString(parser.URL).Result; } catch (HttpWebClientServiceException ex) { ExceptionHandler.LogException(ex, false); } // Scan for prices MatchCollection mc = parser.Tokenizer.Matches(content); return(mc.Cast <Match>().Select(match => { int typeID; string name = Int32.TryParse(match.Groups["name"].Value, out typeID) ? StaticItems.GetItemByID(typeID).Name : match.Groups["name"].Value; return new MineralPrice { Name = name, Price = Decimal.Parse(match.Groups["price"].Value, NumberStyles.Currency, CultureInfo.InvariantCulture) }; })); }
/// <summary> /// Tracks the event. /// </summary> /// <param name="type">The type.</param> /// <param name="category">The category.</param> /// <param name="action">The action.</param> private static void TrackEvent(Type type, string category, string action) { InitEvent(type, category, action); if (NetworkMonitor.IsNetworkAvailable) { var result = HttpWebClientService.DownloadImage(new Uri(NetworkConstants. GoogleAnalyticsUrl), new RequestParams(BuildQueryString())); if (EveMonClient.IsDebugBuild) { // Trace the error (if any) and event category EveMonClient.Trace($"({category} - {action})"); if (result.Error != null) { EveMonClient.Trace($"{result.Error.Message}"); } } } else { // Reschedule later Dispatcher.Schedule(TimeSpan.FromMinutes(1), () => TrackEvent(type, category, action)); if (EveMonClient.IsDebugBuild) { EveMonClient.Trace($"in {TimeSpan.FromMinutes(1)}"); } } }
/// <summary> /// Asynchronously download an XML and deserializes it into the specified type. /// </summary> /// <typeparam name="T">The inner type to deserialize</typeparam> /// <param name="url">The url to query</param> /// <param name="param">The request parameters. If null, defaults will be used.</param> /// <param name="transform">The XSL transform to apply, may be null.</param> internal static async Task <CCPAPIResult <T> > DownloadAPIResultAsync <T>(Uri url, RequestParams param = null, XslCompiledTransform transform = null) { var asyncResult = await HttpWebClientService.DownloadXmlAsync(url, param); CCPAPIResult <T> result; try { // Was there an HTTP error ? result = (asyncResult.Error != null) ? new CCPAPIResult <T>(asyncResult.Error) : DeserializeAPIResultCore <T>(asyncResult.Result, transform); // We got the result return(result); } catch (Exception e) { result = new CCPAPIResult <T>(HttpWebClientServiceException.Exception(url, e)); ExceptionHandler.LogException(e, false); EveMonClient.Trace($"Method: DownloadAPIResultAsync, url: {url.AbsoluteUri}, postdata: {param?.Content}, type: {typeof(T).Name}", false); } return(result); }
/// <summary> /// Asynchronously downloads an image from the provided url. /// </summary> /// <param name="url">The URL.</param> /// <param name="useCache">if set to <c>true</c> [use cache].</param> public static async Task <Image> GetImageAsync(Uri url, bool useCache = true) { DownloadResult <Image> result; // Cache not to be used ? if (!useCache) { result = await HttpWebClientService.DownloadImageAsync(url).ConfigureAwait(false); return(GetImage(result)); } Image image = GetImageFromCache(GetCacheName(url)); if (image != null) { return(image); } // Downloads the image and adds it to cache result = await HttpWebClientService.DownloadImageAsync(url).ConfigureAwait(false); image = GetImage(result); if (image != null) { await AddImageToCacheAsync(image, GetCacheName(url)).ConfigureAwait(false); } return(image); }
/// <summary> /// Synchronously download an XML and deserializes it into the specified type. /// </summary> /// <typeparam name="T">The inner type to deserialize</typeparam> /// <param name="url">The url to query</param> /// <param name="acceptEncoded">if set to <c>true</c> accept encoded response.</param> /// <param name="postData">The post data.</param> /// <param name="transform">The XSL transform to apply, may be null.</param> internal static CCPAPIResult <T> DownloadAPIResult <T>(Uri url, bool acceptEncoded = false, string postData = null, XslCompiledTransform transform = null) { CCPAPIResult <T> result; try { DownloadResult <IXPathNavigable> apiResult = HttpWebClientService.DownloadXmlAsync(url, HttpMethod.Post, acceptEncoded, postData).Result; // Was there an HTTP error ? result = apiResult.Error != null ? new CCPAPIResult <T>(apiResult.Error) : DeserializeAPIResultCore <T>(apiResult.Result, transform); } catch (Exception e) { ExceptionHandler.LogException(e, true); result = new CCPAPIResult <T>(Enumerations.CCPAPI.CCPAPIErrors.Http, e.Message); EveMonClient.Trace( $"Method: DownloadAPIResult, url: {url.AbsoluteUri}, postdata: {postData}, type: {typeof(T).Name}", false); } // Returns return(result); }
/// <summary> /// Asynchronously downloads a JSON object from a JSON stream. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="url">The URL.</param> /// <param name="param">The request parameters. If null, defaults will be used.</param> /// <returns></returns> public static async Task <JsonResult <T> > DownloadJsonAsync <T>(Uri url, RequestParams param = null) where T : class { JsonResult <T> result; try { var asyncResult = await HttpWebClientService.DownloadStreamAsync <T>(url, ParseJSONObject <T>, param); var error = asyncResult.Error; T data; // Was there an HTTP error? if (error != null) { result = new JsonResult <T>(error); } else if ((data = asyncResult.Result) == default(T) && !asyncResult.Response. IsNotModifiedResponse) { // This will become a json error result = new JsonResult <T>(new InvalidOperationException( "null JSON response")); } else { result = new JsonResult <T>(asyncResult.Response, data); } } catch (InvalidOperationException e) { result = new JsonResult <T>(e); ExceptionHandler.LogException(e, true); } catch (InvalidDataContractException e) { result = new JsonResult <T>(e); ExceptionHandler.LogException(e, true); } catch (SerializationException e) { // For deserializing non-errors result = new JsonResult <T>(e); ExceptionHandler.LogException(e, true); } catch (APIException e) { int code; // Error code was converted to a string to match APIException if (!e.ErrorCode.TryParseInv(out code)) { code = 0; } result = new JsonResult <T>(new ResponseParams(code), e.Message); ExceptionHandler.LogException(e, true); } return(result); }
/// <summary> /// Initializes a new instance of the <see cref="DataUpdateDownloadControl"/> class. /// </summary> /// <param name="datafile">The datafile.</param> internal DataUpdateDownloadControl(SerializableDatafile datafile) { InitializeComponent(); m_datafile = datafile; m_label.Text = $"{datafile.Name}"; m_progressLabel.Text = @"Downloading update..."; m_tempFilename = Path.Combine(EveMonClient.EVEMonDataDir, $"{datafile.Name}.tmp"); WebClient = HttpWebClientService.GetWebClient(); }
/// <summary> /// Asynchronously downloads a JSON object from a JSON stream. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="url">The URL.</param> /// <param name="token">The ESI token.</param> /// <param name="acceptEncoded">if set to <c>true</c> [accept encoded].</param> /// <param name="postData">The post data.</param> /// <returns></returns> public static async Task <JsonResult <T> > DownloadJsonAsync <T>(Uri url, string token, bool acceptEncoded = false, string postData = null, string postContentType = null) where T : class { // Create POST data body HttpPostData content = null; if (postData != null) { content = new HttpPostData(postData, contentType: postContentType); } JsonResult <T> result; try { DownloadResult <T> asyncResult = await HttpWebClientService.DownloadStreamAsync <T>( url, ParseJSONObject <T>, acceptEncoded, content, token); var error = asyncResult.Error; T data; // Was there an HTTP error? if (error != null) { result = new JsonResult <T>(error); } else if ((data = asyncResult.Result) == default(T)) { // This will become a json error result = new JsonResult <T>(new InvalidOperationException("null JSON response")); } else { result = new JsonResult <T>(asyncResult.ResponseCode, data) { CurrentTime = asyncResult.ServerTime } }; } catch (InvalidOperationException e) { result = new JsonResult <T>(e); ExceptionHandler.LogException(e, true); } catch (InvalidDataContractException e) { result = new JsonResult <T>(e); ExceptionHandler.LogException(e, true); } return(result); }
/// <summary> /// Gets the loadout by type ID. /// </summary> /// <param name="id">The id.</param> public override async Task GetLoadoutByIDAsync(long id) { // Quit if query is pending if (s_queryPending) { return; } Uri url = new Uri(NetworkConstants.OsmiumBaseUrl + string.Format( CultureConstants.InvariantCulture, NetworkConstants.OsmiumLoadoutDetails, id)); s_queryPending = true; OnLoadoutDownloaded(await HttpWebClientService.DownloadStringAsync(url)); }
/// <summary> /// Asynchronously gets the external parser. /// </summary> private static void GetExternalParserAsync() { if (s_queryPending) { return; } Uri url = new Uri(NetworkConstants.BitBucketWikiBase + NetworkConstants. ExternalEveNotificationTextParser); s_queryPending = true; HttpWebClientService.DownloadStringAsync(url).ContinueWith(task => { OnDownloaded(task.Result); }); }
/// <summary> /// Begins the download. /// </summary> private void BeginDownload() { Uri url = new Uri($"{m_datafile.Address}/{m_datafile.Name}"); string urlValidationError; if (!HttpWebClientService.IsValidURL(url, out urlValidationError)) { return; } if (File.Exists(m_tempFilename)) { FileHelper.DeleteFile(m_tempFilename); } try { using (WebClient) { WebClient.DownloadFileCompleted += DownloadCompleted; WebClient.DownloadProgressChanged += ProgressChanged; try { WebClient.DownloadFileAsync(url, m_tempFilename); } catch (WebException ex) { throw HttpWebClientServiceException.HttpWebClientException(url, ex); } catch (Exception ex) { throw HttpWebClientServiceException.Exception(url, ex); } } } catch (Exception ex) { ExceptionHandler.LogRethrowException(ex); throw; } }
/// <summary> /// Retrieves a token from the server with the specified authentication data. /// </summary> /// <param name="data">The POST data, either an auth code or a refresh token.</param> /// <param name="callback">A callback to receive the new token.</param> /// <param name="isJWT">true if a JWT response is expected, or false if a straight JSON response is expected.</param> private void FetchToken(string data, Action <AccessResponse> callback, bool isJWT) { var obtained = DateTime.UtcNow; var url = new Uri(NetworkConstants.SSOBaseV2 + NetworkConstants.SSOToken); var rp = new RequestParams() { Content = data, Method = HttpMethod.Post }; if (!string.IsNullOrEmpty(m_secret)) { // Non-PKCE rp.Authentication = GetBasicAuthHeader(); } HttpWebClientService.DownloadStringAsync(url, rp).ContinueWith((result) => { AccessResponse response = null; DownloadResult <string> taskResult; string encodedToken; // It must be completed or failed if ContinueWith is reached if (result.IsFaulted) { ExceptionHandler.LogException(result.Exception, true); } else if ((taskResult = result.Result) != null) { // Log HTTP error if it occurred if (taskResult.Error != null) { ExceptionHandler.LogException(taskResult.Error, true); } else if (!string.IsNullOrEmpty(encodedToken = taskResult.Result)) { // For some reason the JWT token is not returned according to the ESI // spec response = TokenFromString(encodedToken, false, obtained); } } Dispatcher.Invoke(() => callback?.Invoke(response)); }); }
/// <summary> /// Tracks the event asynchronously. /// </summary> /// <param name="type">The type.</param> /// <param name="category">The category.</param> /// <param name="action">The action.</param> private static void TrackEventAsync(Type type, string category, string action) { InitEvent(type, category, action); // Sent notification if (NetworkMonitor.IsNetworkAvailable) { HttpWebClientService.DownloadImageAsync(new Uri(NetworkConstants.GoogleAnalyticsUrl), new RequestParams(BuildQueryString())).ContinueWith(task => { if (EveMonClient.IsDebugBuild) { EveMonClient.Trace($"GAnalyticsTracker.TrackEventAsync - ({category} - {action})", printMethod: false); if (task.Result.Error != null) { EveMonClient.Trace($"GAnalyticsTracker.TrackEventAsync - {task.Result.Error.Message}", printMethod: false); } else { EveMonClient.Trace($"GAnalyticsTracker.TrackEventAsync - in {TimeSpan.FromDays(1)}", printMethod: false); } } Dispatcher.Schedule(TimeSpan.FromDays(1), () => TrackStart(type, DailyStartText)); }, EveMonClient.CurrentSynchronizationContext); } else { // Reschedule later Dispatcher.Schedule(TimeSpan.FromMinutes(1), () => TrackEventAsync(type, category, action)); if (EveMonClient.IsDebugBuild) { EveMonClient.Trace($"GAnalyticsTracker.TrackEventAsync - in {TimeSpan.FromMinutes(1)}", printMethod: false); } } }
/// <summary> /// Asynchronously download an object from a JSON stream. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="url">The URL.</param> /// <param name="acceptEncoded">if set to <c>true</c> [accept encoded].</param> /// <param name="postData">The post data.</param> /// <returns></returns> public static async Task <DownloadResult <T> > DownloadJsonAsync <T>(Uri url, bool acceptEncoded = false, string postData = null) where T : class { DownloadResult <String> asyncResult = await HttpWebClientService.DownloadStringAsync(url, HttpMethod.Post, acceptEncoded, postData); T result = null; HttpWebClientServiceException error = null; // Was there an HTTP error ?? if (asyncResult.Error != null) { error = asyncResult.Error; } else { // No http error, let's try to deserialize try { // Deserialize result = new JavaScriptSerializer().Deserialize <T>(asyncResult.Result); } catch (ArgumentException exc) { // An error occurred during the deserialization ExceptionHandler.LogException(exc, true); error = new HttpWebClientServiceException(exc.InnerException?.Message ?? exc.Message); } catch (InvalidOperationException exc) { // An error occurred during the deserialization ExceptionHandler.LogException(exc, true); error = new HttpWebClientServiceException(exc.InnerException?.Message ?? exc.Message); } } return(new DownloadResult <T>(result, error)); }
/// <summary> /// Handles the Shown event of the UpdateDownloadForm control. /// </summary> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> protected override void OnShown(EventArgs e) { base.OnShown(e); string urlValidationError; if (!HttpWebClientService.IsValidURL(m_url, out urlValidationError)) { throw new ArgumentException(urlValidationError); } try { using (m_client = HttpWebClientService.GetWebClient()) { m_client.DownloadFileCompleted += DownloadCompleted; m_client.DownloadProgressChanged += ProgressChanged; try { m_client.DownloadFileAsync(m_url, m_fileName); } catch (WebException ex) { throw HttpWebClientServiceException.HttpWebClientException(m_url, ex); } catch (Exception ex) { throw HttpWebClientServiceException.Exception(m_url, ex); } } } catch (Exception ex) { ExceptionHandler.LogRethrowException(ex); throw; } }
/// <summary> /// Asynchronously download an object from an XML stream. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="url">The url to download from</param> /// <param name="param">The request parameters. If null, defaults will be used.</param> /// <param name="transform">The transform.</param> /// <returns></returns> public static async Task <DownloadResult <T> > DownloadXmlAsync <T>(Uri url, RequestParams param = null, XslCompiledTransform transform = null) where T : class { var asyncResult = await HttpWebClientService.DownloadXmlAsync(url, param); T result = null; HttpWebClientServiceException error = null; // Was there an HTTP error ?? if (asyncResult.Error != null) { error = asyncResult.Error; } else { // No http error, let's try to deserialize try { // Deserialize using (XmlNodeReader reader = new XmlNodeReader((XmlDocument)asyncResult.Result)) { XmlSerializer xs = new XmlSerializer(typeof(T)); if (transform != null) { MemoryStream stream = GetMemoryStream(); using (XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8)) { // Apply the XSL transform writer.Formatting = Formatting.Indented; transform.Transform(reader, writer); writer.Flush(); // Deserialize from the given stream stream.Seek(0, SeekOrigin.Begin); result = (T)xs.Deserialize(stream); } } // Deserialization without transform else { result = (T)xs.Deserialize(reader); } } } // An error occurred during the XSL transform catch (XsltException exc) { ExceptionHandler.LogException(exc, true); error = new HttpWebClientServiceException(exc.GetBaseException().Message); } catch (InvalidOperationException exc) { // An error occurred during the deserialization ExceptionHandler.LogException(exc, true); error = new HttpWebClientServiceException(exc.GetBaseException().Message); } catch (XmlException exc) { ExceptionHandler.LogException(exc, true); error = new HttpWebClientServiceException(exc.GetBaseException().Message); } } return(new DownloadResult <T>(result, error, asyncResult.Response)); }