public static async Task <string> GetStringAsync(string url) { try { using (HttpClient httpclient = new HttpClient()) { var httpResponse = await httpclient.GetAsync(new Uri(url)); if (!httpResponse.IsSuccessStatusCode) { throw new ServiceException("Faild to fetch the Photos From the server"); } return(await httpResponse.Content.ReadAsStringAsync()); } } catch (UnauthorizedAccessException) { throw new ServiceException("Unauthorized Access app doesn't has permession to access internet"); } catch (OperationCanceledException) { throw new ServiceException("Call Time out"); } catch (COMException ex) { var error = WebError.GetStatus(ex.HResult); string msg = "network error " + Enum.GetName(typeof(WebErrorStatus), error); throw new ServiceException(msg); } catch (Exception) { throw new ServiceException("Operation error please try again"); } }
public Result FilterMovies(int MovieGenreID, int ResetInd) { Result sr = new Result(); try { if (ResetInd == 0) { MELib.Movies.MovieList MovieList = MELib.Movies.MovieList.GetMovieList(MovieGenreID); sr.Data = MovieList; } else { MELib.Movies.MovieList MovieList = MELib.Movies.MovieList.GetMovieList(); sr.Data = MovieList; } sr.Success = true; } catch (Exception e) { WebError.LogError(e, "Page: LatestReleases.aspx | Method: FilterMovies", $"(int MovieGenreID, ({MovieGenreID})"); sr.Data = e.InnerException; sr.ErrorText = "Could not filter movies by category."; sr.Success = false; } return(sr); }
static public bool HandleException(Exception exception, TextBox outputField, MainPage rootPage) { SyndicationErrorStatus status = SyndicationError.GetStatus(exception.HResult); if (status != SyndicationErrorStatus.Unknown) { outputField.Text += "The response content is not valid. " + "Please make sure to use a URI that points to an Atom feed.\r\n"; } else { WebErrorStatus webError = WebError.GetStatus(exception.HResult); if (webError == WebErrorStatus.Unauthorized) { outputField.Text += "Incorrect username or password.\r\n"; } else if (webError == WebErrorStatus.Unknown) { // Neither a syndication nor a web error. return(false); } } rootPage.NotifyUser(exception.Message, NotifyType.ErrorMessage); return(true); }
private static IEnumerator GetRoutine(string url, WebRequestCompleted onComplete) { using (UnityWebRequest webRequest = UnityWebRequest.Get(url)) { webRequest.timeout = 30; yield return(webRequest.SendWebRequest()); if (webRequest.isNetworkError) { onComplete?.Invoke(webRequest, null, true, webRequest.error); } else if (webRequest.responseCode >= 400) { try { WebError err = JsonUtility.FromJson <WebError>(webRequest.downloadHandler.text); onComplete?.Invoke(webRequest, null, true, $"ERROR {err.status}: {err.type}\n{err.msg}"); } catch { onComplete?.Invoke(webRequest, null, true, "ERROR " + webRequest.error); } } else { onComplete?.Invoke(webRequest, webRequest.downloadHandler.text, false, null); } } }
/// <summary> /// Play preinstalled recording button click handler /// </summary> /// <param name="sender">Sender object</param> /// <param name="args">Event arguments</param> private async void LoadButton_Click(object sender, RoutedEventArgs e) { SenseRecording recording = null; WebErrorStatus exceptionDetail = new WebErrorStatus(); try { recording = await SenseRecording.LoadFromUriAsync(new Uri("https://github.com/Microsoft/steps/raw/master/Steps/Simulations/short%20walk.txt")); } catch (Exception ex) { exceptionDetail = WebError.GetStatus(ex.GetBaseException().HResult); } if (exceptionDetail == WebErrorStatus.HostNameNotResolved) { MessageDialog dialog = new MessageDialog("Check your network connection. Host name could not be resolved.", "Information"); await dialog.ShowAsync(); } if (recording != null) { _stepCounter = await StepCounterSimulator.GetDefaultAsync(recording); MessageDialog dialog = new MessageDialog( "Recorded sensor type: " + recording.Type.ToString() + "\r\nDescription: " + recording.Description + "\r\nRecording date: " + recording.StartTime.ToString() + "\r\nDuration: " + recording.Duration.ToString(), "Recording info" ); await dialog.ShowAsync(); } }
private static async Task <TResult> GetAsync <TResult>( Uri uri, Func <HttpResponseMessage, Task <TResult> > readResponseContent, CancellationToken ct, bool noCache) { ct.ThrowIfCancellationRequested(); using (var request = new HttpRequestMessage(HttpMethod.Get, uri)) { if (noCache) { request.Headers.IfModifiedSince = DateTimeOffset.Now; } return(await RetryHelper.RunWithDelayAsync( async() => { HttpResponseMessage response = await Client.SendAsync(request, ct).ConfigureAwait(false); response.EnsureSuccessStatusCode(); return await readResponseContent(response).WithCancellation(ct).ConfigureAwait(false); }, ct, ex => WebError.GetStatus(ex.HResult) == WebErrorStatus.CannotConnect && !NetworkInfo.IsNetworkAvailable).ConfigureAwait(false)); } }
public void didFailLoadingWithError(WebView WebView, uint identifier, WebError error, IWebDataSource dataSource) { IWebURLResponse resp = null; resources.TryGetValue(identifier, out resp); if (resp != null) ResourceFailedLoading(resources[identifier], error); }
private static async Task <TResult> PostAsync <TResult>( Uri uri, HttpContent content, Func <HttpResponseMessage, Task <TResult> > readResponseContent, CancellationToken ct, Action <HttpRequestMessage> requestAction = null) { ct.ThrowIfCancellationRequested(); ValidationHelper.ArgumentNotNull(content, nameof(content)); return(await RetryHelper.RunWithDelayAsync( async() => { using (var request = new HttpRequestMessage(HttpMethod.Post, uri)) { request.Content = content; requestAction?.Invoke(request); HttpResponseMessage response = await Client.SendAsync(request, ct).ConfigureAwait(false); response.EnsureSuccessStatusCode(); return await readResponseContent(response).WithCancellation(ct).ConfigureAwait(false); } }, ct, ex => WebError.GetStatus(ex.HResult) == WebErrorStatus.CannotConnect && !NetworkInfo.IsNetworkAvailable).ConfigureAwait(false)); }
private async Task <bool> ValidateApplicationUsage() { // Hanu Epoch time. DateTime lastValidationTime = new DateTime(2011, 11, 4); DateTime now = DateTime.Now; var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings; if (localSettings.Values["ValidationTime"] != null) { // This is not the first use. lastValidationTime = DateTime.Parse(localSettings.Values["ValidationTime"].ToString()); } TimeSpan interval = now.Subtract(lastValidationTime); if (interval.Days > 7) { // Validate again try { using (HttpClient hc = new HttpClient()) { Uri address = new Uri("http://apps.ayansh.com/HanuGCM/Validate.php"); var values = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("blogurl", _blogURL), }; HttpFormUrlEncodedContent postContent = new HttpFormUrlEncodedContent(values); HttpResponseMessage response = await hc.PostAsync(address, postContent).AsTask(); string response_text = await response.Content.ReadAsStringAsync(); if (response_text.Equals("Success")) { // Set Validation time as now localSettings.Values["ValidationTime"] = now.ToString(); return(true); } else { return(false); } } } catch (Exception e) { WebErrorStatus error = WebError.GetStatus(e.GetBaseException().HResult); System.Diagnostics.Debug.WriteLine(e.Message); System.Diagnostics.Debug.WriteLine(error.ToString()); return(false); } } return(true); }
private async void GetFeed_Click(object sender, RoutedEventArgs e) { outputField.Text = ""; // By default 'FeedUri' is disabled and URI validation is not required. When enabling the text box // validating the URI is required since it was received from an untrusted source (user input). // The URI is validated by calling Uri.TryCreate() that will return 'false' for strings that are not valid URIs. // Note that when enabling the text box users may provide URIs to machines on the intrAnet that require // the "Home or Work Networking" capability. Uri uri; if (!Uri.TryCreate(FeedUri.Text.Trim(), UriKind.Absolute, out uri)) { rootPage.NotifyUser("Error: Invalid URI.", NotifyType.ErrorMessage); return; } SyndicationClient client = new SyndicationClient(); client.BypassCacheOnRetrieve = true; // Although most HTTP servers do not require User-Agent header, others will reject the request or return // a different response if this header is missing. Use SetRequestHeader() to add custom headers. client.SetRequestHeader("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"); rootPage.NotifyUser("Downloading feed...", NotifyType.StatusMessage); outputField.Text = "Downloading feed: " + uri.ToString() + "\r\n"; try { currentFeed = await client.RetrieveFeedAsync(uri); rootPage.NotifyUser("Feed download complete.", NotifyType.StatusMessage); DisplayFeed(); } catch (Exception ex) { SyndicationErrorStatus status = SyndicationError.GetStatus(ex.HResult); if (status == SyndicationErrorStatus.InvalidXml) { outputField.Text += "An invalid XML exception was thrown. " + "Please make sure to use a URI that points to a RSS or Atom feed."; } if (status == SyndicationErrorStatus.Unknown) { WebErrorStatus webError = WebError.GetStatus(ex.HResult); if (webError == WebErrorStatus.Unknown) { // Neither a syndication nor a web error. Rethrow. throw; } } rootPage.NotifyUser(ex.Message, NotifyType.ErrorMessage); } }
private string GetErrorMessageFromWebException(Exception exception) { var webErrorStatus = WebError.GetStatus(exception.HResult); if (webErrorStatus == WebErrorStatus.CannotConnect) { return("Please check your internet connection."); } return(exception.Message); }
public void didFailLoadingWithError(WebView WebView, uint identifier, WebError error, IWebDataSource dataSource) { IWebURLResponse resp = null; resources.TryGetValue(identifier, out resp); if (resp != null) { ResourceFailedLoading(resources[identifier], error); } }
public static string HttpClientExceptionHandler(int code, Exception ex) { WebErrorStatus error = WebError.GetStatus(code); if (error == WebErrorStatus.CannotConnect || error == WebErrorStatus.CertificateCommonNameIsIncorrect || error == WebErrorStatus.CertificateContainsErrors || error == WebErrorStatus.CertificateExpired || error == WebErrorStatus.CertificateIsInvalid || error == WebErrorStatus.CertificateRevoked) { return("Error establishing a secure connection. This is usually caused by antivirus, firewall or VPN software, or problems with your ISP."); } else if (error == WebErrorStatus.Timeout) { return("The connection to AnkiWeb timed out. Please check your network connection and try again."); } else if (error == WebErrorStatus.InternalServerError) { return("AnkiWeb encountered an error. Please try again in a few minutes, and if the problem persists, please file a bug report."); } else if (error == WebErrorStatus.NotImplemented) { return("Please upgrade to the latest version of Anki."); } else if (error == WebErrorStatus.BadGateway) { return("AnkiWeb is under maintenance. Please try again in a few minutes."); } else if (error == WebErrorStatus.ServiceUnavailable) { return("AnkiWeb is too busy at the moment. Please try again in a few minutes."); } else if (error == WebErrorStatus.GatewayTimeout) { return("504 gateway timeout error received. Please try temporarily disabling your antivirus."); } else if (error == WebErrorStatus.Conflict) { return("Only one client can access AnkiWeb at a time. If a previous sync failed, please try again in a few minutes."); } else if (error == WebErrorStatus.ProxyAuthenticationRequired) { return("Proxy authentication required."); } else if (error == WebErrorStatus.RequestEntityTooLarge) { return("Your collection or a media file is too large to sync."); } else { return(String.Format("Error Code: {0:X}! {1}", ex.HResult, ex.Message)); } }
public void didFailProvisionalLoadWithError(WebView webView, WebError error, IWebFrame frame) { var uri = error.failingURL(); var description = error.localizedDescription(); if (uri.Trim() != string.Empty) { throw new Exception(uri + Environment.NewLine + description != null ? description : string.Empty); } }
internal static void DisplayWebError(MainPage rootPage, Exception exception) { WebErrorStatus webErrorStatus = WebError.GetStatus(exception.HResult); if (webErrorStatus == WebErrorStatus.Unknown) { rootPage.NotifyUser("Unknown Error: " + exception.Message, NotifyType.ErrorMessage); } else { rootPage.NotifyUser("Web Error: " + webErrorStatus, NotifyType.ErrorMessage); } }
private void HandleException(IJsExecutable callback, object state, WebException e) { var error = new WebError(e); if (callback != null) { callback.ExecuteCallback(_scriptEngine.Visitor, state, new WebRequestArgs(error)); } else { LogManager.Logger.Error(error.Message, false); } }
private async Task <HttpResponseMessage> SendInternalAsync(HttpMethod httpMethod, Uri uri, IHttpContent content) { var request = new HttpRequestMessage(httpMethod, uri); if (content != null) { request.Content = content; } Logger.Info($"Sending {httpMethod} request to {uri} {(content != null ? "\n" + content : "")}"); var stopwatch = new Stopwatch(); stopwatch.Start(); HttpResponseMessage response; try { response = await HttpClient.SendRequestAsync(request).AsTask().ConfigureAwait(false); } catch (Exception e) { stopwatch.Stop(); var status = WebError.GetStatus(e.HResult); Logger.Error($"Caught exception in {stopwatch.ElapsedMilliseconds}ms while sending request to {uri}:\n${status}"); if (!NetworkHelper.Instance.ConnectionInformation.IsInternetAvailable) { throw new NoInternetException(status); } throw new NetworkException(status); } stopwatch.Stop(); var success = response.IsSuccessStatusCode; if (!success) { var responeText = await response.Content.ReadAsStringAsync().AsTask().ConfigureAwait(false); Logger.Error($"Server responded with error code in {stopwatch.ElapsedMilliseconds}ms {uri} {response.StatusCode}:\n{responeText}"); throw new ServerException((int)response.StatusCode, responeText); } Logger.Info($"Got response from {uri} in {stopwatch.ElapsedMilliseconds}ms with status code: {response.StatusCode}"); return(response); }
public async Task <FeedDto> RetrieveFeedAsync(Uri uri) { try { var feed = await client.RetrieveFeedAsync(uri).AsTask().ConfigureAwait(false); return(new FeedDto(feed.Title.Text, feed.Items.Select(x => new FeedItemDto( x.ItemUri ?? x.Links.FirstOrDefault()?.Uri, x.PublishedDate.UtcDateTime > new DateTime(1601, 1, 2) ? x.PublishedDate : x.LastUpdatedTime, // 1601 is used when PublishedDate is not set RemoveHtmlTags(x.Title.Text), RemoveHtmlTags(x.Summary?.Text) )).ToArray() )); } catch (Exception ex) when(WebError.GetStatus(ex.HResult) == WebErrorStatus.NotModified) { throw new SyndicationServiceException(SyndicationServiceError.NotModified, ex); } }
/// <summary>Creates the specified source.</summary> /// <param name="source">The source.</param> /// <param name="message">The message.</param> /// <param name="error">The error.</param> /// <param name="code">The code.</param> /// <returns></returns> public static WebMessage Create(string source, string message, WebError error = WebError.None, HttpStatusCode code = 0) { if (code == 0) { switch (error) { case WebError.None: code = HttpStatusCode.OK; break; case WebError.Redirect: code = HttpStatusCode.RedirectKeepVerb; break; case WebError.NotFound: code = HttpStatusCode.NotFound; break; case WebError.MissingRights: code = HttpStatusCode.Forbidden; break; case WebError.InternalServerError: code = HttpStatusCode.InternalServerError; break; case WebError.InvalidTransactionKey: case WebError.SessionRequired: case WebError.AuthenticationRequired: code = HttpStatusCode.Unauthorized; break; case WebError.RequestingTooFast: code = (HttpStatusCode)429; break; default: code = HttpStatusCode.BadRequest; break; } } if (code == 0) { code = error == WebError.None ? HttpStatusCode.OK : HttpStatusCode.BadRequest; } return(new WebMessage() { Code = code, Error = error, Content = message, Source = source, }); }
public void didFailLoadWithError(WebView WebView, WebError error, webFrame forFrame) { DidFailLoadWithError(WebView, error, forFrame); }
public void didFailProvisionalLoadWithError(WebView WebView, WebError error, webFrame frame) { DidFailProvisionalLoadWithError(WebView, error, frame); }
internal void NotifyDidFailWithError(WebDownload download, WebError error) { // Todo }
void resourcesLoadDelegate_PluginFailed(WebView sender, WebError error) { if (webView == sender) { PluginFailed(this, new PluginFailedErrorEventArgs(error.localizedDescription())); } }
private void downloadDelegate_DidFailWithError(WebDownload download, WebError error) { downloads[download].NotifyDidFailWithError(download, error); }
/// <summary>Adds a result message.</summary> /// <param name="source">The source.</param> /// <param name="error">The error.</param> /// <param name="message">The message.</param> /// <param name="args">The arguments.</param> public void AddMessage(string source, WebError error, string message, params object[] args) { AddMessage(WebMessage.Create(source, string.Format(message, args), error: error)); }
public void plugInFailedWithError(WebView WebView, WebError error, IWebDataSource dataSource) { throw new NotImplementedException(); }
public void didFailWithError(WebDownload download, WebError error) { DidFailWithError(download, error); }
public void didFailLoadingWithError(WebView WebView, uint identifier, WebError error, IWebDataSource dataSource) { throw new NotImplementedException(); }
public void unableToImplementPolicyWithError(WebView WebView, WebError error, webFrame frame) { }
public void plugInFailedWithError(WebView WebView, WebError error, IWebDataSource dataSource) { PluginFailed(WebView, error); }
void resourcesLoadDelegate_ResourceFailedLoading(IWebURLResponse res, WebError error) { resourceIntercepter.ResFailed(res, error.localizedDescription()); }
public WebRequestArgs(WebError error) : base(error.Message) { Error = error; Success = false; }
/// <summary>Adds a result message.</summary> /// <param name="source">The source.</param> /// <param name="error">The error.</param> /// <param name="code">The code.</param> /// <param name="message">The message.</param> /// <param name="args">The arguments.</param> public void AddMessage(string source, WebError error, HttpStatusCode code, string message, params object[] args) { AddMessage(WebMessage.Create(source, string.Format(message, args), error: error, code: code)); }
/// <summary>Adds a result message.</summary> /// <param name="method">The method.</param> /// <param name="error">The error.</param> /// <param name="code">The code.</param> /// <param name="message">The message.</param> /// <param name="args">The arguments.</param> public void AddMessage(WebServerMethod method, WebError error, HttpStatusCode code, string message, params object[] args) { AddMessage(WebMessage.Create(method, string.Format(message, args), error: error, code: code)); }
/// <summary>Adds a result message.</summary> /// <param name="method">The method.</param> /// <param name="error">The error.</param> /// <param name="message">The message.</param> /// <param name="args">The arguments.</param> public void AddMessage(WebServerMethod method, WebError error, string message, params object[] args) { AddMessage(WebMessage.Create(method, string.Format(message, args), error: error)); }