/// <summary>Throws the exception on the thread pool.</summary> /// <param name="exception">The exception to propagate.</param> /// <param name="targetContext"> /// The target context on which to propagate the exception; otherwise, <see langword="null"/> to use the thread /// pool. /// </param> internal static void ThrowAsync(Exception exception, SynchronizationContext targetContext) { if (targetContext != null) { try { targetContext.Post( state => { throw PrepareExceptionForRethrow((Exception)state); }, exception); return; } catch (Exception ex) { exception = new AggregateException(exception, ex); } } #if NET45PLUS Task.Run(() => { throw PrepareExceptionForRethrow(exception); }); #else ThreadPool.QueueUserWorkItem(state => { throw PrepareExceptionForRethrow((Exception)state); }, exception); #endif }
/// <summary> /// Function to log exception except disposed exception. /// </summary> /// <param name="aggregateException">Aggregate Exception</param> private static void LogException(AggregateException aggregateException) { if (aggregateException != null) { aggregateException.Handle((ex) => HandleException(ex)); } }
internal static void ThrowAsync(Exception exception, SynchronizationContext targetContext) { if (targetContext != null) { try { targetContext.Post(delegate(object state) { throw AsyncServices.PrepareExceptionForRethrow((Exception)state); }, exception); return; } catch (Exception ex) { exception = new AggregateException(new Exception[] { exception, ex }); } } ThreadPool.QueueUserWorkItem(delegate(object state) { throw AsyncServices.PrepareExceptionForRethrow((Exception)state); }, exception); }
private void HandleError(AggregateException ae) { if (ae.InnerException != null) { MessageBox.Show("An error occurred while uploading the image to imgur.com. Please try again.", "SnagitImgur", MessageBoxButtons.OK, MessageBoxIcon.Warning); ae.InnerException.ToExceptionless().Submit(); } }
Tuple<string, bool> HandleAggregateException(AggregateException aggregrateException, ReportExceptionEventArgs et) { Tuple<string, bool> handled = null; foreach (var error in aggregrateException.Flatten().InnerExceptions) { if (handled == null || handled.Item1 == null) handled = InternalHandler(error, et); // Does not set the loader to true } return handled; }
public void StartAggregation() { _aggregationTask = AggregateAsync() .ContinueWith(task => { if (!task.IsFaulted) return; Log.ErrorException("An error occured when running background aggregation for " + _name + ", the aggregation has been DISABLED", task.Exception); _aggregateException = task.Exception; }); }
public void HandleFault(AggregateException ex) { Logger.Error(ex.Message, ex); var message = IoC.Get<MessageBoxViewModel>(); message.DisplayName = "Error"; message.Content = new ErrorInfo(); message.DismissAction = () => NavigateToHome(); message.DismissTimeout = 10000; NavigateToScreen(message); }
private static void HandleException(AggregateException ex) { if (ex.InnerExceptions.OfType<TaskCanceledException>() .Any()) { Console.WriteLine("Task was canceled..."); Log.Trace("Task was canceled"); } else { Log.Error(ex, "Task proccessing exception"); } }
public void Unwrap_WhenCalled_ReturnAllExceptionMessages() { //Arrange var ex3 = new Exception("Level 3"); var ex2 = new AggregateException("Level 2", ex3); var ex1 = new Exception("Level 1", ex2); var expected = new[] { ex1, ex2, ex3 }; //Act var result = ex1.Unwrap(); //Assert result.Should().Equal(expected); }
public static TRequest Validate <TRequest>(this TRequest request) where TRequest : class, IRequest { var exception = new AggregateException(request.GetExceptions()); if (exception.InnerExceptions.Count != 0) { throw exception.InnerExceptions.Count == 1 ? exception.InnerExceptions[0] : exception; } return(request); }
/// <summary>Completes the processing of an asynchronous message.</summary> /// <param name="completed">The completed task storing the output data generated for an input message.</param> /// <param name="messageWithId">The originating message</param> private void AsyncCompleteProcessMessageWithTask( Task <IEnumerable <TOutput> > completed, KeyValuePair <TInput, long> messageWithId) { Debug.Assert(completed != null, "A task should have been provided."); Debug.Assert(completed.IsCompleted, "The task should have been in a final state."); switch (completed.Status) { case TaskStatus.RanToCompletion: IEnumerable <TOutput> outputItems = completed.Result; try { // Get the resulting enumerable and persist it. StoreOutputItems(messageWithId, outputItems); } catch (Exception exc) { // Enumerating the user's collection failed. If this exception represents cancellation, // swallow it rather than shutting down the block. if (!Common.IsCooperativeCancellation(exc)) { // The exception was not for cancellation. We must add the exception before declining // and signaling completion, as the exception is part of the operation, and the completion // conditions depend on this. Common.StoreDataflowMessageValueIntoExceptionData(exc, messageWithId.Key); _target.Complete(exc, dropPendingMessages: true, storeExceptionEvenIfAlreadyCompleting: true, unwrapInnerExceptions: false); } } break; case TaskStatus.Faulted: // We must add the exception before declining and signaling completion, as the exception // is part of the operation, and the completion conditions depend on this. AggregateException aggregate = completed.Exception !; Common.StoreDataflowMessageValueIntoExceptionData(aggregate, messageWithId.Key, targetInnerExceptions: true); _target.Complete(aggregate, dropPendingMessages: true, storeExceptionEvenIfAlreadyCompleting: true, unwrapInnerExceptions: true); goto case TaskStatus.Canceled; case TaskStatus.Canceled: StoreOutputItems(messageWithId, null); // notify the reordering buffer and decrement the bounding count break; default: Debug.Assert(false, "The task should have been in a final state."); break; } // Let the target know that one of the asynchronous operations it launched has completed. _target.SignalOneAsyncMessageCompleted(); }
public static Exception Append(this Exception source, Exception ex) { Exception result = null; if (source == null) { result = ex; } else { result = new AggregateException(ex, source); } return(result); }
public void FirstChanceExceptionStatisticsTelemetryModuleWasTrackedReturnsTrueForAggExc() { using (var module = new FirstChanceExceptionStatisticsTelemetryModule()) { module.Initialize(this.configuration); var exception = new Exception(); Assert.False(module.WasExceptionTracked(exception)); var aggExc = new AggregateException(exception); Assert.True(module.WasExceptionTracked(aggExc)); } }
/// <summary> /// Logs the inner exceptions of an AggregateException separately. /// </summary> private static void LogRecursive(ILog log, AggregateException e, string message) { foreach (var innerException in e.InnerExceptions) { if (innerException is AggregateException) { LogRecursive(log, innerException as AggregateException, message); } else { log.Error($"{message}", innerException); } } }
public void Should_rethrow_aggregate_exception_from_inside_delegate__pessimistic_with_full_stacktrace() { var policy = Policy.Timeout(TimeSpan.FromSeconds(10), TimeoutStrategy.Pessimistic); var msg = "Aggregate Exception thrown from the delegate"; // Check to see if nested aggregate exceptions are unwrapped correctly AggregateException exception = new AggregateException(msg, new NotImplementedException()); policy.Invoking(p => p.Execute(() => { Helper_ThrowException(exception); })) .Should().Throw <AggregateException>() .WithMessage(exception.Message) .Where(e => e.InnerException is NotImplementedException) .And.StackTrace.Should().Contain(nameof(Helper_ThrowException)); }
protected DistributedTask(SerializationInfo info, StreamingContext context) { InstanseId = info.GetValue("InstanseId", typeof(object)).ToString(); Id = info.GetValue("Id", typeof(object)).ToString(); Status = (DistributedTaskStatus)info.GetValue("Status", typeof(DistributedTaskStatus)); Exception = (AggregateException)info.GetValue("Exception", typeof(AggregateException)); foreach (var p in info) { if (p.Name.StartsWith("_")) { props[p.Name.TrimStart('_')] = p.Value.ToString(); } } }
private Exception StripException(AggregateException ex) { Logger.Warn($"Stripping AggregateException to RemoteCallException (if possible): {ex}"); var remoteException = ex.InnerExceptions.FirstOrDefault(x => x is RemoteCallException); if (remoteException != null) { throw remoteException; } else { throw ex.InnerException; } }
public void SimpleInnerExceptionTestCase () { var message = "Foo"; var inner = new ApplicationException (message); var ex = new AggregateException (inner); Assert.IsNotNull (ex.InnerException); Assert.IsNotNull (ex.InnerExceptions); Assert.AreEqual (inner, ex.InnerException); Assert.AreEqual (1, ex.InnerExceptions.Count); Assert.AreEqual (inner, ex.InnerExceptions[0]); Assert.AreEqual (message, ex.InnerException.Message); }
public static void ThrowInnerException(AggregateException ex) { ex.Handle((innerEx) => { if (innerEx is AggregateException) { ThrowInnerException((AggregateException)innerEx); return(false); } else { throw innerEx; } }); }
public void StripTargetInvocationExceptionAndAggregateException() { _client.AddWrapperExceptions(typeof(AggregateException)); OutOfMemoryException exception2 = new OutOfMemoryException("Ran out of Int64s"); AggregateException innerWrapper = new AggregateException(_exception, exception2); TargetInvocationException wrapper = new TargetInvocationException(innerWrapper); List <Exception> exceptions = _client.ExposeStripWrapperExceptions(wrapper).ToList(); Assert.AreEqual(2, exceptions.Count); Assert.Contains(_exception, exceptions); Assert.Contains(exception2, exceptions); }
public void StripNestedAggregateExceptions() { OutOfMemoryException exception2 = new OutOfMemoryException("Ran out of Int64s"); NotSupportedException exception3 = new NotSupportedException("Forgot to implement this method"); AggregateException innerWrapper = new AggregateException(_exception, exception2); AggregateException wrapper = new AggregateException(innerWrapper, exception3); List <Exception> exceptions = _client.ExposeStripWrapperExceptions(wrapper).ToList(); Assert.AreEqual(3, exceptions.Count); Assert.IsTrue(exceptions.Contains(_exception)); Assert.IsTrue(exceptions.Contains(exception2)); Assert.IsTrue(exceptions.Contains(exception3)); }
private void LogException(Exception ex) { AggregateException agg = ex as AggregateException; if (agg != null) { foreach (var innerEx in agg.InnerExceptions) { Trace.TraceError(innerEx.ToString()); } } Trace.TraceError(ex.ToString()); }
public async Task GetNsfwSubredditsAsync_WhenCalledAndRedditRateLimitHasNotExceededAndAggregateExceptionOccurs_ReturnsEmptySubredditCollection() { IRedditAccessToken accessToken = CreateRedditAccessToken();; int numberOfSubreddits = _random.Next(1, 10); const bool willExceedRateLimit = false; AggregateException aggregateException = new AggregateException(); IRedditLogic sut = CreateSut(willExceedRateLimit: willExceedRateLimit, exception: aggregateException); IEnumerable <IRedditSubreddit> result = await sut.GetNsfwSubredditsAsync(accessToken, numberOfSubreddits); Assert.IsNotNull(result); Assert.AreEqual(0, result.Count()); }
internal static IProvisioningEvent EventForFailedOperation(AggregateException exception) { HttpStatusCode httpStatus; if (ProvisioningErrorHandling.TryGetHttpStatusCode(exception, out httpStatus)) { return ProvisioningErrorHandling.IsTransientError(exception) ? (IProvisioningEvent)new DiscoveryFailedTransientEvent(exception, httpStatus) : new DiscoveryFailedPermanentEvent(exception, httpStatus); } return ProvisioningErrorHandling.IsTransientError(exception) ? (IProvisioningEvent)new DiscoveryFailedTransientEvent(exception) : new DiscoveryFailedPermanentEvent(exception); }
protected override void beforeEach() { _argumentException = new ArgumentException("Failed"); _exceptionHandler = MockFor <IExceptionHandler>(); _observer = MockFor <IExceptionHandlingObserver>(); _observer.Expect(x => x.RecordHandled(_argumentException)); _exceptionHandler.Expect(x => x.ShouldHandle(_argumentException)).Return(true); _exceptionHandler.Expect(x => x.Handle(_argumentException)); ClassUnderTest.InsideBehavior = new AsyncThrowingBehavior(_argumentException); var testTask = new Task(() => ClassUnderTest.Invoke()); testTask.Start(); _exception = Assert.Throws <AggregateException>(testTask.Wait); }
public async Task Should_propagate_aggregate_operation_cancelled_exception_to_subscriber() { var ex = new AggregateException(new OperationCanceledException()); A.CallTo(() => eventStore.GetEventsAsync(A <Func <StoredEvent, Task> > .Ignored, "^my-stream", position, A <CancellationToken> .Ignored)) .Throws(ex); var sut = new PollingSubscription(eventStore, eventNotifier, eventSubscriber, "^my-stream", position); await WaitAndStopAsync(sut); A.CallTo(() => eventSubscriber.OnErrorAsync(sut, ex)) .MustNotHaveHappened(); }
/// <summary> /// Extracts the first inner exception of type <typeparamref name="TPreferredException"/> /// from the <see cref="AggregateException"/> if one is present. /// </summary> /// <remarks> /// If no <typeparamref name="TPreferredException"/> inner exception is present, this /// method returns the first inner exception. All inner exceptions will be traced, /// including the one returned. The containing <paramref name="aggregateException"/> /// will not be traced unless there are no inner exceptions. /// </remarks> /// <typeparam name="TPreferredException">The preferred type of inner exception to extract. /// Use <c>typeof(Exception)</c> to extract the first exception regardless of type.</typeparam> /// <param name="aggregateException">The <see cref="AggregateException"/> to examine.</param> /// <param name="eventSource">The event source to trace.</param> /// <returns>The extracted exception. It will not be <c>null</c> /// but it may not be of type <typeparamref name="TPreferredException"/>.</returns> public Exception AsError <TPreferredException>(AggregateException aggregateException, string eventSource) { Fx.Assert(aggregateException != null, "aggregateException cannot be null."); // If aggregateException contains any fatal exceptions, return it directly // without tracing it or any inner exceptions. if (Fx.IsFatal(aggregateException)) { return(aggregateException); } // Collapse possibly nested graph into a flat list. // Empty inner exception list is unlikely but possible via public api. ReadOnlyCollection <Exception> innerExceptions = aggregateException.Flatten().InnerExceptions; if (innerExceptions.Count == 0) { return(TraceException(aggregateException, eventSource)); } // Find the first inner exception, giving precedence to TPreferredException Exception favoredException = null; foreach (Exception nextInnerException in innerExceptions) { // AggregateException may wrap TargetInvocationException, so unwrap those as well TargetInvocationException targetInvocationException = nextInnerException as TargetInvocationException; Exception innerException = (targetInvocationException != null && targetInvocationException.InnerException != null) ? targetInvocationException.InnerException : nextInnerException; if (innerException is TPreferredException && favoredException == null) { favoredException = innerException; } // All inner exceptions are traced TraceException <Exception>(innerException, eventSource); } if (favoredException == null) { Fx.Assert(innerExceptions.Count > 0, "InnerException.Count is known to be > 0 here."); favoredException = innerExceptions[0]; } return(favoredException); }
public static void UsingVideoCreateUrl(string id, string token, string url) { try { Console.WriteLine("--Create()-from URL-"); Dictionary <string, object> tokens = new Dictionary <string, object> () { { "url", url }, { "title", "My URL Movie" }, { "description", "Initial URL description" } }; var task = Video.CreateAsync(tokens); task.Wait(); var video = task.Result; Console.WriteLine("Id: " + video["id"] + " Title: " + video["title"]); // Console.WriteLine ("--Delete--"); // // var videoId = (long)video ["id"]; // video.Delete (); // // Console.WriteLine ("--Find after delete: id: "+videoId+"--"); // var video1 = Video.Find (videoId); } catch (VzaarApiException ve) { Console.Write("!!!!!!!!! EXCEPTION !!!!!!!!!"); Console.WriteLine(ve.Message); } catch (Exception e) { Console.Write("!!!!!!!!! EXCEPTION !!!!!!!!!"); Console.WriteLine(e.Message); if (e is AggregateException) { AggregateException ae = (AggregateException)e; var flatten = ae.Flatten(); foreach (var fe in flatten.InnerExceptions) { if (fe is VzaarApiException) { Console.WriteLine(fe.Message); } } } } }
protected IEnumerable <Exception> StripWrapperExceptions(Exception exception) { if (exception != null && _wrapperExceptions.Any(wrapperException => exception.GetType() == wrapperException && (exception.InnerException != null || exception is ReflectionTypeLoadException))) { AggregateException aggregate = exception as AggregateException; if (aggregate != null) { foreach (Exception e in aggregate.InnerExceptions) { foreach (Exception ex in StripWrapperExceptions(e)) { yield return(ex); } } } else { ReflectionTypeLoadException rtle = exception as ReflectionTypeLoadException; if (rtle != null) { int index = 0; foreach (Exception e in rtle.LoaderExceptions) { try { e.Data["Type"] = rtle.Types[index]; } catch { } foreach (Exception ex in StripWrapperExceptions(e)) { yield return(ex); } index++; } } else { foreach (Exception e in StripWrapperExceptions(exception.InnerException)) { yield return(e); } } } } else { yield return(exception); } }
/// <summary> /// トランザクションをコミットする。 /// </summary> /// <returns>処理状態。</returns> public async Task Commit() { if (statusFixed) { return; } statusFixed = true; bool noCommit = true; List <Exception> innerExcepions = null; foreach (var tran in trackingTransactions.Values) { try { tran.Commit(); } catch (Exception e) { // 最初のコミットが失敗したときはTrasactionとしては不整合はないので、単に例外を投げるだけでいい if (noCommit) { throw e; } // すでに1つ以上のコミットを実行してしまった場合は、仕方ないのでできるだけcommitしようとする if (innerExcepions == null) { innerExcepions = new List <Exception>(); } innerExcepions.Add(e); } noCommit = false; } // いくつかのコミットだけ失敗してしまった場合は、内部のexceptionをまとめた上でServerExceptionとする if (innerExcepions != null) { var ae = new AggregateException(innerExcepions); throw new ServerException(ErrorCode.UNKNOWN, "The transaction was broken between databases.", ae); } else { await Task.WhenAll(TrackingEntites.Select(entity => entity.SubmitChanges())); } }
public void Should_serialize_fault_from_serializable_exception() { Exception ex = null; try { throw new Exception("Boom"); } catch (Exception e) { ex = new AggregateException(e); } var fault = new ReceiveFaultEvent(HostMetadataCache.Host, ex, "Foo", Guid.Empty); TestCanSerialize(fault); }
public void SynchronousMethodsCompatibilityHandlerThrowsAggregate() { using BatchClient batchClient = ClientUnitTestCommon.CreateDummyClient(); const string dummyJobId = "Foo"; batchClient.CustomBehaviors.Add(new RequestInterceptor(req => { throw new ArgumentException(); })); batchClient.CustomBehaviors.Add(SynchronousMethodExceptionBehavior.ThrowAggregateException); AggregateException aggregate = Assert.Throws <AggregateException>(() => batchClient.JobOperations.GetJob(dummyJobId)); Assert.IsAssignableFrom <ArgumentException>(aggregate.InnerException); }
private static void ShowExceptions(AggregateException e, int indent) { foreach (var innerException in e.InnerExceptions) { for (var i = 0; i < indent; i++) { Console.Write(" "); } Console.WriteLine(innerException.Message); if (innerException is AggregateException) { ShowExceptions(innerException as AggregateException, indent + 1); } } }
private static Exception GetInnerException(AggregateException aggregateException) { Exception innerExcception = aggregateException; while (aggregateException is AggregateException) { innerExcception = aggregateException.InnerExceptions[0]; aggregateException = innerExcception.As <AggregateException>(); if (aggregateException.IsNull()) { break; } } return(innerExcception); }
public static IEnumerable <Exception> FilterValidExceptions(this AggregateException ae) { var finalList = new List <Exception> { ae }; var asyncExceptions = ae.Flatten().InnerExceptions.Where(x => x.GetType() != typeof(AggregateException)); foreach (var item in asyncExceptions) { var innerExceptionList = GetInnerExceptionList(item); finalList.AddRange(innerExceptionList); } return(finalList); }
public void SimpleInnerExceptionTestCase() { const string Message = "Foo"; var inner = new ApplicationException(Message); var ex = new AggregateException(inner); Assert.IsNotNull(ex.InnerException); Assert.IsNotNull(ex.InnerExceptions); Assert.AreEqual(inner, ex.InnerException); Assert.AreEqual(1, ex.InnerExceptions.Count); Assert.AreEqual(inner, ex.InnerExceptions[0]); Assert.AreEqual(Message, ex.InnerException.Message); Assert.AreEqual(inner, ex.GetBaseException()); }
private static void LogAggregateException(AggregateException e) { foreach (var v in e.InnerExceptions) { if (v is TaskCanceledException) { Console.WriteLine("Task Canceled Exception: Task{0}", (v as TaskCanceledException).Task.Id); } else { Console.WriteLine("Exception: {0}", v.GetType().Name); } } }
public static Task <T> Catch <T>(this Task <T> task) { return(task.ContinueWith <Task <T> >(delegate(Task <T> t) { if (t != null && t.IsFaulted) { AggregateException exception = t.Exception; Trace.TraceError("Catch<T> exception thrown by Task: {0}", new object[] { exception }); } return t; }).Unwrap <T>()); }
/// <summary> /// Handles exceptions from a parallel loop. /// </summary> private static void HandleParallelException(Exception exception) { if (exception != null) { // Nested cancels are propagated as OperationCanceledExceptions. AggregateException innerException = exception.InnerException as AggregateException; if (innerException != null && innerException.InnerException is OperationCanceledException) { throw new OperationCanceledException(Strings.ParallelOperationCanceledExceptionMessage, innerException.InnerException); } throw exception; } }
public void TestAggregateExceptionConverter() { string errorMessage = "BadRequest message"; IEnumerable<Exception> exceptions = new List<Exception>() { new DocumentClientException(errorMessage, innerException: null, statusCode: HttpStatusCode.BadRequest) }; AggregateException ae = new AggregateException(message: "Test AE message", innerExceptions: exceptions); ResponseMessage response = TransportHandler.AggregateExceptionConverter(ae, null); Assert.IsNotNull(response); Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode); Assert.IsTrue(response.ErrorMessage.Contains(errorMessage)); }
public void Start() { m_InstanciedServiceList = new List<object>(); var list = GetServiceTypeList(); System.Diagnostics.Trace.WriteLine(string.Format("{0} services found", list.Count())); m_ServiceList = list.Where(i => !i.Item1).Select(i => Type.GetType(i.Item2)).ToList(); var autoUpdateServiceHostList = list.Where(i => i.Item1).Select(i => i.Item2).ToList(); var failList = new List<Exception>(); StartServices(failList); if (failList.Count > 0) { var failStartException = new AggregateException("Start services failed", failList); throw failStartException; } }
public static String GetMessageAndStackTrace(AggregateException e) { if (e == null) { throw new ArgumentNullException("e", "AggregateException can not be null."); } var sb = new StringBuilder(); foreach (Exception innerException in e.InnerExceptions) { sb.AppendLine(innerException.Message); sb.AppendLine("\t" + innerException.StackTrace); } return sb.ToString(); }
/// <summary>Throws the exception on the ThreadPool.</summary> /// <param name="exception">The exception to propagate.</param> /// <param name="targetContext">The target context on which to propagate the exception. Null to use the ThreadPool.</param> internal static void ThrowAsync(Exception exception, SynchronizationContext targetContext) { // If the user supplied a SynchronizationContext... if (targetContext != null) { try { // Post the throwing of the exception to that context, and return. targetContext.Post(state => { throw PrepareExceptionForRethrow((Exception)state); }, exception); return; } catch (Exception postException) { // If something goes horribly wrong in the Post, we'll // propagate both exceptions on the ThreadPool exception = new AggregateException(exception, postException); } } // Propagate the exception(s) on the ThreadPool ThreadPool.QueueUserWorkItem(state => { throw PrepareExceptionForRethrow((Exception)state); }, exception); }
/// <summary> /// The method that performs the tests /// Depending on the inputs different test code paths will be exercised /// </summary> internal void RealRun() { TaskScheduler tm = TaskScheduler.Default; CreateTask(tm, _taskTree); // wait the whole task tree to be created _countdownEvent.Wait(); Stopwatch sw = Stopwatch.StartNew(); try { switch (_api) { case API.Cancel: _taskTree.CancellationTokenSource.Cancel(); break; case API.Wait: switch (_waitBy) { case WaitBy.None: _taskTree.Task.Wait(); _taskCompleted = true; break; case WaitBy.Millisecond: _taskCompleted = _taskTree.Task.Wait(_waitTimeout); break; case WaitBy.TimeSpan: _taskCompleted = _taskTree.Task.Wait(new TimeSpan(0, 0, 0, 0, _waitTimeout)); break; } break; } } catch (AggregateException exp) { _caughtException = exp.Flatten(); } finally { sw.Stop(); } if (_waitTimeout != -1) { long delta = sw.ElapsedMilliseconds - ((long)_waitTimeout + s_deltaTimeOut); if (delta > 0) { Debug.WriteLine("ElapsedMilliseconds way more than requested Timeout."); Debug.WriteLine("WaitTime= {0} ms, ElapsedTime= {1} ms, Allowed Descrepancy = {2} ms", _waitTimeout, sw.ElapsedMilliseconds, s_deltaTimeOut); Debug.WriteLine("Delta= {0} ms", delta); } else { var delaytask = Task.Delay((int)Math.Abs(delta)); // give delay to allow Context being collected before verification delaytask.Wait(); } } Verify(); _countdownEvent.Dispose(); }
private void UploadFileToBlob( CancellationToken cancellationToken, Uri uri, string localFile, string contentType, string subFolder, FileEncryption fileEncryption, CloudBlobClient client, IRetryPolicy retryPolicy) { //attempt to open the file first so that we throw an exception before getting into the async work using (new FileStream(localFile, FileMode.Open, FileAccess.Read)) { } Exception lastException = null; CloudBlockBlob blob = null; // stats from azurescope show 10 to be an optimal number of transfer threads int numThreads = ParallelTransferThreadCount; var file = new FileInfo(localFile); long fileSize = file.Length; int maxBlockSize = GetBlockSize(fileSize); // Prepare a queue of blocks to be uploaded. Each queue item is a key-value pair where // the 'key' is block id and 'value' is the block length. List<string> blockList; var queue = PreapreUploadQueue(maxBlockSize, fileSize, ref numThreads, out blockList); int exceptionCount = 0; blob = GetCloudBlockBlob(uri, client, subFolder, localFile, contentType); blob.DeleteIfExists(options: new BlobRequestOptions() { RetryPolicy = retryPolicy }); if (cancellationToken.IsCancellationRequested) { TaskCompletedCallback(true, null, BlobTransferType.Upload, localFile, uri); cancellationToken.ThrowIfCancellationRequested(); } var options = new BlobRequestOptions { RetryPolicy = retryPolicy, ServerTimeout = TimeSpan.FromSeconds(90) }; // Launch threads to upload blocks. var tasks = new List<Task>(); long bytesSent = 0; Action action = () => { List<Exception> exceptions = new List<Exception>(); if (_forceSharedAccessSignatureRetry != TimeSpan.Zero) { Thread.Sleep(_forceSharedAccessSignatureRetry); } if (queue.Count > 0) { FileStream fs = null; try { fs = new FileStream(file.FullName, FileMode.Open, FileAccess.Read); KeyValuePair<int, int> blockIdAndLength; while (queue.TryDequeue(out blockIdAndLength)) { cancellationToken.ThrowIfCancellationRequested(); try { var buffer = new byte[blockIdAndLength.Value]; var binaryReader = new BinaryReader(fs); // move the file system reader to the proper position fs.Seek(blockIdAndLength.Key * (long)maxBlockSize, SeekOrigin.Begin); int readSize = binaryReader.Read(buffer, 0, blockIdAndLength.Value); if (fileEncryption != null) { lock (fileEncryption) { using (FileEncryptionTransform encryptor = fileEncryption.GetTransform(file.Name, blockIdAndLength.Key * (long)maxBlockSize)) { encryptor.TransformBlock(buffer, 0, readSize, buffer, 0); } } } using (var ms = new MemoryStream(buffer, 0, blockIdAndLength.Value)) { string blockIdString = Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format(CultureInfo.InvariantCulture, "BlockId{0}", blockIdAndLength.Key.ToString("0000000", CultureInfo.InvariantCulture)))); string blockHash = GetMd5HashFromStream(buffer); if (blob != null) blob.PutBlock(blockIdString, ms, blockHash, options: options); } Interlocked.Add(ref bytesSent, blockIdAndLength.Value); var progress = (int)((double)bytesSent / file.Length * 100); var eArgs = new BlobTransferProgressChangedEventArgs(bytesSent, blockIdAndLength.Value, file.Length, progress, _uploadSpeedCalculator.UpdateCountersAndCalculateSpeed(bytesSent), uri, localFile, null); OnTaskProgressChanged(eArgs); } catch (StorageException ex) { TimeSpan tm; exceptionCount++; exceptions.Add(ex); if (!retryPolicy.ShouldRetry(exceptions.Count, ex.RequestInformation.HttpStatusCode, ex, out tm, new OperationContext())) { lastException = new AggregateException(String.Format(CultureInfo.InvariantCulture, "Received {0} exceptions while uploading. Canceling upload.", exceptions.Count), exceptions); throw lastException; } Thread.Sleep(tm); queue.Enqueue(blockIdAndLength); } catch (IOException ex) { TimeSpan tm; exceptionCount++; exceptions.Add(ex); if (!retryPolicy.ShouldRetry(exceptions.Count, 0, ex, out tm, new OperationContext())) { lastException = new AggregateException(String.Format(CultureInfo.InvariantCulture, "Received {0} exceptions while reading file {1} @ location {2} to be uploaded. Canceling upload.", exceptions.Count, file.Name, blockIdAndLength.Key * (long)maxBlockSize), exceptions); throw lastException; } // dispose existing file stream if (fs != null) { fs.Close(); } Thread.Sleep(tm); // try to reopen the file stream again fs = new FileStream(file.FullName, FileMode.Open, FileAccess.Read); queue.Enqueue(blockIdAndLength); } } } finally { if (fs != null) { fs.Close(); } } } }; for (int idxThread = 0; idxThread < numThreads; idxThread++) { tasks.Add(Task.Factory.StartNew( action, cancellationToken, TaskCreationOptions.AttachedToParent, TaskScheduler.Current)); } if (cancellationToken.IsCancellationRequested) { TaskCompletedCallback(true, lastException, BlobTransferType.Upload, localFile, uri); cancellationToken.ThrowIfCancellationRequested(); } Task.Factory.ContinueWhenAll(tasks.ToArray(), (Task[] result) => { if (result.Any(t => t.IsFaulted)) { return; } blob.PutBlockList(blockList, options: options); }, TaskContinuationOptions.None).Wait(cancellationToken); TaskCompletedCallback(cancellationToken.IsCancellationRequested, lastException, BlobTransferType.Upload, localFile, uri); }
public void Should_persist_and_unwrap_original_exception_in_requestexecutionexception() { // Given var expectedException = new Exception(); var aggregateException = new AggregateException(expectedException); var resolvedRoute = new ResolveResult( new FakeRoute(), DynamicDictionary.Empty, null, null, null); A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute); A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._)) .Returns(TaskHelpers.GetFaultedTask<Response>(aggregateException)); var pipelines = new Pipelines(); pipelines.OnError.AddItemToStartOfPipeline((ctx, exception) => null); engine.RequestPipelinesFactory = (ctx) => pipelines; var request = new Request("GET", "/", "http"); // When var result = this.engine.HandleRequest(request); var returnedException = result.Items["ERROR_EXCEPTION"] as RequestExecutionException; // Then returnedException.InnerException.ShouldBeSameAs(expectedException); }
private static void OnKeepAliveError(AggregateException ex, object state) { ((TraceSource)state).TraceEvent(TraceEventType.Error, 0, "Failed to send keep alive: " + ex.GetBaseException()); }
private static Exception TryUnwrapAggregateException(AggregateException aggregateException) { if (aggregateException == null) return null; if (aggregateException.InnerExceptions.Count == 1) return aggregateException.InnerExceptions[0]; return aggregateException; }
public void Should_persist_and_unwrap_multiple_nested_original_exception_in_requestexecutionexception_with_exceptions_on_multiple_levels() { // Given var expectedException1 = new Exception(); var expectedException2 = new Exception(); var expectedException3 = new Exception(); var expectedException4 = new Exception(); var expectgedInnerExceptions = 4; var exceptionsListInner = new List<Exception>() { expectedException1, expectedException2, expectedException3 }; var expectedExceptionInner = new AggregateException(exceptionsListInner); var exceptionsListOuter = new List<Exception>() { expectedExceptionInner, expectedException4 }; var aggregateExceptionOuter = new AggregateException(exceptionsListOuter); var resolvedRoute = new ResolveResult( new FakeRoute(), DynamicDictionary.Empty, null, null, null); A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute); A.CallTo(() => this.requestDispatcher.Dispatch(context, A<CancellationToken>._)) .Returns(TaskHelpers.GetFaultedTask<Response>(aggregateExceptionOuter)); var pipelines = new Pipelines(); pipelines.OnError.AddItemToStartOfPipeline((ctx, exception) => null); engine.RequestPipelinesFactory = (ctx) => pipelines; var request = new Request("GET", "/", "http"); // When var result = this.engine.HandleRequest(request); var returnedException = result.Items["ERROR_EXCEPTION"] as RequestExecutionException; // Then var returnedInnerException = returnedException.InnerException as AggregateException; returnedInnerException.ShouldBeOfType(typeof(AggregateException)); Assert.Equal(expectgedInnerExceptions, returnedInnerException.InnerExceptions.Count); }
/// <summary> /// Initializes a new instance of the <see cref="UnobservedTaskExceptionEventArgs"/> class /// with the unobserved exception. /// </summary> /// <param name="exception">The Exception that has gone unobserved.</param> public UnobservedTaskExceptionEventArgs(AggregateException exception) { m_exception = exception; }
internal static Exception ConvertAggregateExceptionToCommunicationException(AggregateException ex) { Exception exception = FxTrace.Exception.AsError<WebSocketException>(ex); WebSocketException webSocketException = exception as WebSocketException; if (webSocketException != null && webSocketException.InnerException != null) { HttpListenerException httpListenerException = webSocketException.InnerException as HttpListenerException; if (httpListenerException != null) { return HttpChannelUtilities.CreateCommunicationException(httpListenerException); } } ObjectDisposedException objectDisposedException = exception as ObjectDisposedException; if (objectDisposedException != null) { return new CommunicationObjectAbortedException(exception.Message, exception); } return new CommunicationException(exception.Message, exception); }
public static void AddException(ref AggregateException target, Exception source) { target = ReferenceEquals(target, null) ? new AggregateException(source) : (new AggregateException(source, target)).Flatten(); }
internal UnobservedTaskExceptionEventArgs FireUnobservedEvent (AggregateException e) { UnobservedTaskExceptionEventArgs args = new UnobservedTaskExceptionEventArgs (e); EventHandler<UnobservedTaskExceptionEventArgs> temp = UnobservedTaskException; if (temp == null) return args; temp (this, args); return args; }
private static void OnDisconnectError(AggregateException ex, object state) { ((TraceSource)state).TraceEvent(TraceEventType.Error, 0, "Failed to raise disconnect: " + ex.GetBaseException()); }
void OpenFromAssemblyNames (string url) { var tasks = new List<Task> (); foreach (var definition in definitions.ToArray ()) { var cecilObject = definition.CecilLoader.GetCecilObject (definition.UnresolvedAssembly); if (cecilObject == null) { LoggingService.LogWarning ("Assembly browser: Can't find assembly: " + definition.UnresolvedAssembly.FullAssemblyName + "."); continue; } foreach (var assemblyNameReference in cecilObject.MainModule.AssemblyReferences) { var result = AddReferenceByAssemblyName (assemblyNameReference); if (result == null) { LoggingService.LogWarning ("Assembly browser: Can't find assembly: " + assemblyNameReference.FullName + "."); } else { tasks.Add (result.LoadingTask); } } } if (tasks.Count == 0) { var nav = SearchMember (url); if (nav == null) { LoggingService.LogError ("Assembly browser: Can't find: " + url + "."); } return; }; Task.Factory.ContinueWhenAll (tasks.ToArray (), tarr => { var exceptions = tarr.Where (t => t.IsFaulted).Select (t => t.Exception).ToArray (); if (exceptions != null) { var ex = new AggregateException (exceptions).Flatten (); if (ex.InnerExceptions.Count > 0) { foreach (var inner in ex.InnerExceptions) { LoggingService.LogError ("Error while loading assembly in the browser.", inner); } throw ex; } } if (definitions == null) // disposed return; Application.Invoke (delegate { var nav = SearchMember (url); if (nav == null) { LoggingService.LogError ("Assembly browser: Can't find: " + url + "."); } }); }, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Current); }
private void HandleException(AggregateException exception) { if (exception.InnerException is TrelloUnauthorizedException) messageBus.Publish(new TrelloWasUnauthorizedEvent(exception.InnerException.Message)); else view.ShowErrorMessage(exception.InnerException.Message); }
/// <summary> /// This is called if indexing fails /// </summary> /// <param name="ex">The exception that caused the failure</param> private void IndexFailed(AggregateException ex) { System.Diagnostics.Debug.WriteLine(ex); this.DisposeOfTask(); spIndexingPanel.Visibility = Visibility.Collapsed; if(cboEntityType.SelectedIndex == (int)EntityType.CodeEntity) txtFindName.Text = "Indexing failed. Reason: " + ex.InnerException.Message; }
public void FromException_UnwrapsAggregateException() { var ex = new AggregateException(new IOException(), new ArgumentNullException(), new ArgumentException(), new AggregateException()); var result = TaskMonad.TaskMonad.FromException<TestValue>(ex); Assert.IsNotNull(result); Assert.AreEqual(TaskStatus.Faulted, result.Status); Assert.IsNotNull(result.Exception); CollectionAssert.AreEqual(ex.InnerExceptions, result.Exception.InnerExceptions); }
public void TestWorkCancelledException() { // prepare workAction to throw exception Exception currentException = null; Func<Task> workAction = () => { throw currentException; }; // initialize worker using (var worker = new MockWorker(workAction)) { var finishedEvent = new AutoResetEvent(false); worker.OnWorkFinished += () => { finishedEvent.Set(); }; bool wasError; worker.OnWorkError += e => wasError = true; // start worker worker.Start(); // throw OperationCanceledException wasError = false; currentException = new OperationCanceledException(); worker.NotifyWork(); // verify work finished Assert.IsTrue(finishedEvent.WaitOne(1000)); Assert.IsFalse(wasError); // throw Exception wasError = false; currentException = new Exception(); worker.NotifyWork(); // verify work errored Assert.IsTrue(finishedEvent.WaitOne()); Assert.IsTrue(wasError); // throw AggregateException of all OperationCanceledException wasError = false; currentException = new AggregateException(new OperationCanceledException(), new OperationCanceledException()); worker.NotifyWork(); // verify work finished Assert.IsTrue(finishedEvent.WaitOne()); Assert.IsFalse(wasError); // throw AggregateException of some OperationCanceledException wasError = false; currentException = new AggregateException(new OperationCanceledException(), new Exception()); worker.NotifyWork(); // verify work errored Assert.IsTrue(finishedEvent.WaitOne()); Assert.IsTrue(wasError); } }
// Validates that flattening (incl recursive) works. private static bool RunAggregateException_Flatten() { TestHarness.TestLog("* RunAggregateException_Flatten()"); Exception exceptionA = new Exception("A"); Exception exceptionB = new Exception("B"); Exception exceptionC = new Exception("C"); AggregateException aggExceptionBase = new AggregateException(exceptionA, exceptionB, exceptionC); // Verify flattening one with another. TestHarness.TestLog(" > Flattening (no recursion)..."); AggregateException flattened1 = aggExceptionBase.Flatten(); Exception[] expected1 = new Exception[] { exceptionA, exceptionB, exceptionC }; if (expected1.Length != flattened1.InnerExceptions.Count) { TestHarness.TestLog(" > error: expected count {0} differs from actual {1}", expected1.Length, flattened1.InnerExceptions.Count); return false; } for (int i = 0; i < flattened1.InnerExceptions.Count; i++) { if (expected1[i] != flattened1.InnerExceptions[i]) { TestHarness.TestLog(" > error: inner exception #{0} isn't right:", i); TestHarness.TestLog(" expected: {0}", expected1[i]); TestHarness.TestLog(" found : {0}", flattened1.InnerExceptions[i]); return false; } } // Verify flattening one with another, accounting for recursion. TestHarness.TestLog(" > Flattening (with recursion)..."); AggregateException aggExceptionRecurse = new AggregateException(aggExceptionBase, aggExceptionBase); AggregateException flattened2 = aggExceptionRecurse.Flatten(); Exception[] expected2 = new Exception[] { exceptionA, exceptionB, exceptionC, exceptionA, exceptionB, exceptionC, }; if (expected2.Length != flattened2.InnerExceptions.Count) { TestHarness.TestLog(" > error: expected count {0} differs from actual {1}", expected2.Length, flattened2.InnerExceptions.Count); return false; } for (int i = 0; i < flattened2.InnerExceptions.Count; i++) { if (expected2[i] != flattened2.InnerExceptions[i]) { TestHarness.TestLog(" > error: inner exception #{0} isn't right:", i); TestHarness.TestLog(" expected: {0}", expected2[i]); TestHarness.TestLog(" found : {0}", flattened2.InnerExceptions[i]); return false; } } return true; }