public async void RetryStreamException() { try { // Arrange. using (var tokenSource = new CancellationTokenSource()) using (var _hc = Setup(tokenSource)) { var pingTask = new Pipelines.TaskStep() { Enabled = true, Reference = new Pipelines.TaskStepDefinitionReference() { Name = "Ping", Version = "0.1.1", Id = Guid.NewGuid() } }; var pingVersion = new TaskVersion(pingTask.Reference.Version); Exception expectedException = new System.Net.Http.HttpRequestException("simulated network error"); _taskServer .Setup(x => x.GetTaskContentZipAsync(It.IsAny <Guid>(), It.IsAny <TaskVersion>(), It.IsAny <CancellationToken>())) .Returns((Guid taskId, TaskVersion taskVersion, CancellationToken token) => { return(Task.FromResult <Stream>(new ExceptionStream())); }); var tasks = new List <Pipelines.TaskStep>(new Pipelines.TaskStep[] { pingTask }); //Act Exception actualException = null; try { await _taskManager.DownloadAsync(_ec.Object, tasks); } catch (Exception ex) { actualException = ex; } //Assert //verify task completed in less than 2sec and it is in failed state state Assert.Equal("NotImplementedException", actualException.GetType().Name); //assert download was invoked 3 times, because we retry on task download _taskServer .Verify(x => x.GetTaskContentZipAsync(It.IsAny <Guid>(), It.IsAny <TaskVersion>(), It.IsAny <CancellationToken>()), Times.Exactly(3)); //see if the task.json was not downloaded Assert.Equal( 0, Directory.GetFiles(_hc.GetDirectory(WellKnownDirectory.Tasks), "*", SearchOption.AllDirectories).Length); } } finally { Teardown(); } }
protected override async void OnUserStreamHttpError(System.Net.Http.HttpRequestException e) { await InsertStreamInTimeLineAsync(new NotificationRow(new Tweet { user = new User { name = "システム", screen_name = "system" }, text = "ストリームコネクションに失敗しました" }, "システムメッセージ", Setting, NotificationType.System, this.Account.UserInfomation.screen_name, rowActionCallback)); }
public async void BubblesNetworkException() { try { // Arrange. Setup(); var pingTask = new Pipelines.TaskStep() { Enabled = true, Reference = new Pipelines.TaskStepDefinitionReference() { Name = "Ping", Version = "0.1.1", Id = Guid.NewGuid() } }; var pingVersion = new TaskVersion(pingTask.Reference.Version); Exception expectedException = new System.Net.Http.HttpRequestException("simulated network error"); _taskServer .Setup(x => x.GetTaskContentZipAsync(It.IsAny <Guid>(), It.IsAny <TaskVersion>(), _ec.Object.CancellationToken)) .Returns((Guid taskId, TaskVersion taskVersion, CancellationToken token) => { throw expectedException; }); var tasks = new List <Pipelines.TaskStep>(new Pipelines.TaskStep[] { pingTask }); //Act Exception actualException = null; try { await _taskManager.DownloadAsync(_ec.Object, tasks); } catch (Exception ex) { actualException = ex; } //Assert //verify task completed in less than 2sec and it is in failed state state Assert.Equal(expectedException, actualException); //see if the task.json was not downloaded Assert.Equal( 0, Directory.GetFiles(_hc.GetDirectory(WellKnownDirectory.Tasks), "*", SearchOption.AllDirectories).Length); } finally { Teardown(); } }
public static void ShowHttpExceptionMessage(System.Net.Http.HttpRequestException e) { if (e.Message.IndexOfAny(new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' }) != -1) { ShowMessage($"服务器错误: {e.Message.Replace("Response status code does not indicate success: ", string.Empty)}"); } else if (e.Message == "An error occurred while sending the request.") { ShowMessage("无法连接网络。"); } else { ShowMessage($"请检查网络连接。 {e.Message}"); } }
public async System.Threading.Tasks.Task <T> SendRequestAsync <T>(string requestMethod, string target, string jsonBody, int timeoutSeconds = 60) { System.Net.Http.HttpResponseMessage httpResponseMessage = await SendAsync(requestMethod, target, jsonBody, timeoutSeconds); System.Net.Http.HttpContent requestContent = httpResponseMessage.Content; string resultContent = requestContent.ReadAsStringAsync().Result; #if DEBUG try { string tempDirectory = System.IO.Path.GetTempPath(); string targetFilename = string.Format("hrworks-dbg-{0}.json", target); string tempFilepath = System.IO.Path.Combine(tempDirectory, targetFilename); string tmpContent = resultContent; try { Newtonsoft.Json.Linq.JObject jsonResult = Newtonsoft.Json.Linq.JObject.Parse(tmpContent); tmpContent = jsonResult.ToString(Newtonsoft.Json.Formatting.Indented); } catch (Exception ex) { System.Console.WriteLine(ex.Message); } System.IO.File.WriteAllText(tempFilepath, tmpContent); } catch (Exception ex) { System.Console.WriteLine(ex.Message); } #endif try { httpResponseMessage.EnsureSuccessStatusCode(); } catch (Exception ex) { System.Net.Http.HttpRequestException httpRequestException = new System.Net.Http.HttpRequestException(resultContent, ex); throw httpRequestException; } System.Threading.Tasks.Task <T> typedResponse = System.Threading.Tasks.Task.Factory.StartNew(() => Newtonsoft.Json.JsonConvert.DeserializeObject <T>(resultContent)); return(await typedResponse); }
public async Task DeleteDeploymentPolicy() { using (var session = await StartSession()) { var client = await session.GetClient(ApiPortals.SOC); DeploymentPolicy newPolicy = new DeploymentPolicy() { name = "TestPolicy", description = "TestPolicyDescription", isActive = false, appliesToSandbox = true, appliesToPublished = true, objectType = "Applications", customPropertyName = "DevelopmentTeamAlias", customPropertyDisplayName = "Development Team Alias", policyApplicability = "Must", policyCondition = "ContainsAny", priority = 1 }; var response = client.CreateDeploymentPolicy(newPolicy).Result; Assert.NotNull(response); Assert.Equal("TestPolicy", response.name); var policyDeletion = client.DeleteDeploymentPolicy(response.id.Value).Result; if (policyDeletion) { try { var task = client.GetDeploymentPolicy(response.id.Value); task.Wait(); } catch (System.AggregateException ex) { System.Net.Http.HttpRequestException innerEx = (System.Net.Http.HttpRequestException)ex.InnerException; Assert.IsType <System.Net.Http.HttpRequestException>(innerEx); Assert.Contains("404 (Not Found)", innerEx.Message); } } } }
private bool IsAuthRelatedException(Exception ex) { // In observation, we have seen either an HttpRequestException directly, or // a FatalProtocolException wrapping an HttpRequestException when we are not able // to auth against the NuGet feed. System.Net.Http.HttpRequestException httpRequestException = null; if (ex is System.Net.Http.HttpRequestException) { httpRequestException = ex as System.Net.Http.HttpRequestException; } else if (ex is FatalProtocolException && ex.InnerException is System.Net.Http.HttpRequestException) { httpRequestException = ex.InnerException as System.Net.Http.HttpRequestException; } if (httpRequestException != null && (httpRequestException.Message.Contains("401") || httpRequestException.Message.Contains("403"))) { return(true); } return(false); }
protected abstract void AssertHttpRequestException(System.Net.Http.HttpRequestException e);
private async Task doFetch(TaskCompletionSource <HttpResponseMessage> tcs, HttpRequestMessage request, CancellationToken cancellationToken) { try { var requestObject = new JSObject(); if (request.Properties.TryGetValue("WebAssemblyFetchOptions", out var fetchOoptionsValue) && fetchOoptionsValue is IDictionary <string, object> fetchOptions) { foreach (var item in fetchOptions) { requestObject.SetObjectProperty(item.Key, item.Value); } } requestObject.SetObjectProperty("method", request.Method.Method); // We need to check for body content if (request.Content != null) { if (request.Content is StringContent) { requestObject.SetObjectProperty("body", await request.Content.ReadAsStringAsync()); } else { // 2.1.801 seems to have a problem with the line // using (var uint8Buffer = Uint8Array.From(await request.Content.ReadAsByteArrayAsync ())) // so we split it up into two lines. var byteAsync = await request.Content.ReadAsByteArrayAsync(); using (var uint8Buffer = Uint8Array.From(byteAsync)) { requestObject.SetObjectProperty("body", uint8Buffer); } } } // Process headers // Cors has it's own restrictions on headers. // https://developer.mozilla.org/en-US/docs/Web/API/Headers using (var jsHeaders = new HostObject("Headers")) { if (request.Headers != null) { foreach (var header in request.Headers) { foreach (var value in header.Value) { jsHeaders.Invoke("append", header.Key, value); } } } if (request.Content?.Headers != null) { foreach (var header in request.Content.Headers) { foreach (var value in header.Value) { jsHeaders.Invoke("append", header.Key, value); } } } requestObject.SetObjectProperty("headers", jsHeaders); } WasmHttpReadStream wasmHttpReadStream = null; JSObject abortController = new HostObject("AbortController"); JSObject signal = (JSObject)abortController.GetObjectProperty("signal"); requestObject.SetObjectProperty("signal", signal); signal.Dispose(); CancellationTokenSource abortCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); CancellationTokenRegistration abortRegistration = abortCts.Token.Register((Action)(() => { if (abortController.JSHandle != -1) { abortController.Invoke("abort"); abortController?.Dispose(); } wasmHttpReadStream?.Dispose(); })); var args = new Runtime.InteropServices.JavaScript.Array(); args.Push(request.RequestUri.ToString()); args.Push(requestObject); requestObject.Dispose(); var response = fetch.Invoke("apply", window, args) as Task <object>; args.Dispose(); if (response == null) { throw new Exception("Internal error marshalling the response Promise from `fetch`."); } var t = await response; var status = new WasmFetchResponse((JSObject)t, abortController, abortCts, abortRegistration); //Console.WriteLine($"bodyUsed: {status.IsBodyUsed}"); //Console.WriteLine($"ok: {status.IsOK}"); //Console.WriteLine($"redirected: {status.IsRedirected}"); //Console.WriteLine($"status: {status.Status}"); //Console.WriteLine($"statusText: {status.StatusText}"); //Console.WriteLine($"type: {status.ResponseType}"); //Console.WriteLine($"url: {status.Url}"); HttpResponseMessage httpresponse = new HttpResponseMessage((HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), status.Status.ToString())); var streamingEnabled = request.Properties.TryGetValue("WebAssemblyEnableStreamingResponse", out var streamingEnabledValue) && (bool)streamingEnabledValue; httpresponse.Content = StreamingSupported && streamingEnabled ? new StreamContent(wasmHttpReadStream = new WasmHttpReadStream(status)) : (HttpContent) new WasmHttpContent(status); // Fill the response headers // CORS will only allow access to certain headers. // If a request is made for a resource on another origin which returns the CORs headers, then the type is cors. // cors and basic responses are almost identical except that a cors response restricts the headers you can view to // `Cache-Control`, `Content-Language`, `Content-Type`, `Expires`, `Last-Modified`, and `Pragma`. // View more information https://developers.google.com/web/updates/2015/03/introduction-to-fetch#response_types // // Note: Some of the headers may not even be valid header types in .NET thus we use TryAddWithoutValidation using (var respHeaders = (JSObject)status.Headers) { if (respHeaders != null) { using (var entriesIterator = (JSObject)respHeaders.Invoke("entries")) { JSObject nextResult = null; try { nextResult = (JSObject)entriesIterator.Invoke("next"); while (!(bool)nextResult.GetObjectProperty("done")) { using (var resultValue = (Runtime.InteropServices.JavaScript.Array)nextResult.GetObjectProperty("value")) { var name = (string)resultValue [0]; var value = (string)resultValue [1]; if (!httpresponse.Headers.TryAddWithoutValidation(name, value)) { if (httpresponse.Content != null) { if (!httpresponse.Content.Headers.TryAddWithoutValidation(name, value)) { Console.WriteLine($"Warning: Can not add response header for name: {name} value: {value}"); } } } } nextResult?.Dispose(); nextResult = (JSObject)entriesIterator.Invoke("next"); } } finally { nextResult?.Dispose(); } } } } tcs.SetResult(httpresponse); } catch (JSException jsExc) { var httpExc = new System.Net.Http.HttpRequestException(jsExc.Message); tcs.SetException(httpExc); } catch (Exception exception) { tcs.SetException(exception); } }
protected ImgurException ToImgurException(HttpRequestException From) { return(new ImgurException("Network Error: " + From.Message, From)); }
public async void BubblesNetworkException() { try { // Arrange. Setup(); var pingTask = new TaskInstance() { Enabled = true, Name = "Ping", Version = "0.1.1", Id = Guid.NewGuid() }; var pingVersion = new TaskVersion(pingTask.Version); Exception expectedException = new System.Net.Http.HttpRequestException("simulated network error"); _taskServer .Setup(x => x.GetTaskContentZipAsync(It.IsAny<Guid>(), It.IsAny<TaskVersion>(), _ec.Object.CancellationToken)) .Returns((Guid taskId, TaskVersion taskVersion, CancellationToken token) => { throw expectedException; }); var tasks = new List<TaskInstance>(new TaskInstance[] { pingTask }); //Act Exception actualException = null; try { await _taskManager.DownloadAsync(_ec.Object, tasks); } catch (Exception ex) { actualException = ex; } //Assert //verify task completed in less than 2sec and it is in failed state state Assert.Equal(expectedException, actualException); //see if the task.json was not downloaded Assert.Equal( 0, Directory.GetFiles(IOUtil.GetTasksPath(_hc), "*", SearchOption.AllDirectories).Length); } finally { Teardown(); } }