コード例 #1
0
ファイル: Action.cs プロジェクト: ZXeno/Andromeda
        protected void ResetCancelToken(string actionName, OperationCanceledException e)
        {
            ResultConsole.AddConsoleLine($"Operation {actionName} canceled.");
            Logger.LogMessage($"Operation {actionName} canceled by user request. {e.Message}");

            ResetCancelToken();
        }
コード例 #2
0
 public void TypePropertiesAreCorrect()
 {
     Assert.AreEqual(typeof(OperationCanceledException).GetClassName(), "Bridge.OperationCanceledException", "Name");
     object d = new OperationCanceledException();
     Assert.True(d is OperationCanceledException, "is OperationCanceledException");
     Assert.True(d is Exception, "is Exception");
 }
    public void SetNext() {
        var r = new DiscardRedundantWorkThrottle();
        var ax = new ArgumentException();
        var cx = new OperationCanceledException();

        // results are propagated
        var n = 0;
        r.SetNextToAction(() => n++).AssertRanToCompletion();
        n.AssertEquals(1);
        r.SetNextToFunction(() => 2).AssertRanToCompletion().AssertEquals(2);
        r.SetNextToAsyncFunction(Tasks.RanToCompletion).AssertRanToCompletion();
        r.SetNextToAsyncFunction(() => Task.FromResult(3)).AssertRanToCompletion().AssertEquals(3);

        // faulted tasks are propagated
        r.SetNextToAsyncFunction(() => Tasks.Faulted(ax)).AssertFailed<ArgumentException>();
        r.SetNextToAsyncFunction(() => Tasks.Faulted<int>(ax)).AssertFailed<ArgumentException>();

        // cancelled tasks are propagated
        r.SetNextToAsyncFunction(Tasks.Cancelled).AssertCancelled();
        r.SetNextToAsyncFunction(Tasks.Cancelled<int>).AssertCancelled();

        // thrown cancellation exceptions indicate cancellation
        r.SetNextToAsyncFunction(() => { throw cx; }).AssertCancelled();
        r.SetNextToAsyncFunction<int>(() => { throw cx; }).AssertCancelled();
        r.SetNextToAction(() => { throw cx; }).AssertCancelled();
        r.SetNextToFunction<int>(() => { throw cx; }).AssertCancelled();

        // thrown exceptions are propagated
        r.SetNextToAsyncFunction(() => { throw ax; }).AssertFailed<ArgumentException>();
        r.SetNextToAsyncFunction<int>(() => { throw ax; }).AssertFailed<ArgumentException>();
        r.SetNextToAction(() => { throw ax; }).AssertFailed<ArgumentException>();
        r.SetNextToFunction<int>(() => { throw ax; }).AssertFailed<ArgumentException>();
    }
コード例 #4
0
 public void MessageOnlyConstructorWorks()
 {
     var ex = new OperationCanceledException("Some message");
     Assert.True((object)ex is OperationCanceledException, "is OperationCanceledException");
     Assert.AreEqual(ex.Message, "Some message", "Message");
     Assert.True(ReferenceEquals(ex.CancellationToken, CancellationToken.None), "CancellationToken");
     Assert.Null(ex.InnerException, "InnerException");
 }
コード例 #5
0
 public void CancellationTokenOnlyConstructorWorks()
 {
     var ct = new CancellationToken();
     var ex = new OperationCanceledException(ct);
     Assert.True((object)ex is OperationCanceledException, "is OperationCanceledException");
     Assert.AreEqual(ex.Message, "Operation was canceled.", "Message");
     Assert.True(ReferenceEquals(ex.CancellationToken, ct), "CancellationToken");
     Assert.Null(ex.InnerException, "InnerException");
 }
コード例 #6
0
 private static void HandleCanceledOperations(CancellationToken cancellationToken, TaskCompletionSource<HttpResponseMessage> tcs, OperationCanceledException e)
 {
     if (cancellationToken.IsCancellationRequested && e.CancellationToken == cancellationToken) {
         tcs.TrySetCanceled();
     }
     else {
         tcs.TrySetException(e);
     }
 }
コード例 #7
0
 public void MessageAndInnerExceptionAndCancellationTokenConstructorWorks()
 {
     var ct = new CancellationToken();
     var innerException = new Exception();
     var ex = new OperationCanceledException("Some message", innerException, ct);
     Assert.True((object)ex is OperationCanceledException, "is OperationCanceledException");
     Assert.AreEqual(ex.Message, "Some message", "Message");
     Assert.True(ReferenceEquals(ex.CancellationToken, ct), "CancellationToken");
     Assert.True(ReferenceEquals(ex.InnerException, innerException), "InnerException");
 }
コード例 #8
0
        public static void BasicConstructors()
        {
            CancellationToken ct1 = new CancellationTokenSource().Token;
            OperationCanceledException ex1 = new OperationCanceledException(ct1);
            Assert.Equal(ct1, ex1.CancellationToken);

            CancellationToken ct2 = new CancellationTokenSource().Token;
            OperationCanceledException ex2 = new OperationCanceledException("message", ct2);
            Assert.Equal(ct2, ex2.CancellationToken);

            CancellationToken ct3 = new CancellationTokenSource().Token;
            OperationCanceledException ex3 = new OperationCanceledException("message", new Exception("inner"), ct3);
            Assert.Equal(ct3, ex3.CancellationToken);
        }
コード例 #9
0
        public static bool OperationCanceledException_Basics()
        {
            TestHarness.TestLog("* OperationCanceledExceptionTests.OperationCanceledException_Basics()");
            bool passed = true;

#if !PFX_LEGACY_3_5
            CancellationToken ct1 = new CancellationTokenSource().Token;
            OperationCanceledException ex1 = new OperationCanceledException(ct1);
            passed &= TestHarnessAssert.AreEqual(ct1, OCEHelper.ExtractCT(ex1), "The exception should have the CancellationToken baked in.");

            CancellationToken ct2 = new CancellationTokenSource().Token;
            OperationCanceledException ex2 = new OperationCanceledException("message", ct2);
            passed &= TestHarnessAssert.AreEqual(ct2, OCEHelper.ExtractCT(ex2), "The exception should have the CancellationToken baked in.");

            CancellationToken ct3 = new CancellationTokenSource().Token;
            OperationCanceledException ex3 = new OperationCanceledException("message", new Exception("inner"), ct3);
            passed &= TestHarnessAssert.AreEqual(ct3, OCEHelper.ExtractCT(ex3), "The exception should have the CancellationToken baked in.");
#endif
            return passed;
        }
コード例 #10
0
 private bool NotOurShutdownToken(OperationCanceledException oce)
 {
     return(oce.CancellationToken == _shutdownToken);
 }
 public void SetException(Exception exception)
 {
     _canceledException = exception as OperationCanceledException;
 }
コード例 #12
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SpotifyHttpClientTimeoutException" /> class.
 /// </summary>
 /// <param name="clientType">The client type.</param>
 /// <param name="innerException">
 /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified.
 /// </param>
 public SpotifyHttpClientTimeoutException(Type clientType, OperationCanceledException innerException)
     : base("The operation has been canceled due to the HttpClient timeout. See inner exception for details.", clientType, innerException)
 {
 }
コード例 #13
0
        /// <summary>
        /// Throws the cancellation exception.
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <param name="exception">The exception.</param>
        /// <returns>Exception.</returns>
        private Exception GetCancellationException(string url, CancellationToken cancellationToken, OperationCanceledException exception)
        {
            // If the HttpClient's timeout is reached, it will cancel the Task internally
            if (!cancellationToken.IsCancellationRequested)
            {
                var msg = string.Format("Connection to {0} timed out", url);

                _logger.Error(msg);

                // Throw an HttpException so that the caller doesn't think it was cancelled by user code
                return(new HttpException(msg, exception)
                {
                    IsTimedOut = true
                });
            }

            return(exception);
        }
コード例 #14
0
ファイル: TaskAwaiterTests.cs プロジェクト: noahfalk/corefx
        public static void AsyncTaskAwaiterTests_CTandOCE()
        {
            // Test that CancellationToken is correctly flowed through await
            {
                var amb = AsyncTaskMethodBuilder.Create();
                var cts = new CancellationTokenSource();
                var oce = new OperationCanceledException(cts.Token);
                amb.SetException(oce);
                try
                {
                    amb.Task.GetAwaiter().GetResult();
                    Assert.True(false, string.Format("     > FAILURE. Faulted task's GetResult should have thrown."));
                }
                catch (OperationCanceledException oceToCheck)
                {
                    Assert.True(oceToCheck.CancellationToken == cts.Token, "     > FAILURE. The tasks token should have equaled the provided token.");
                }
                catch (Exception exc)
                {
                    Assert.True(false, string.Format("     > FAILURE. Exception an OCE rather than a " + exc.GetType()));
                }
            }

            // Test that original OCE is propagated through await
            {
                var tasks = new List<Task>();

                var cts = new CancellationTokenSource();
                var oce = new OperationCanceledException(cts.Token);

                // A Task that throws an exception to cancel
                var b = new Barrier(2);
                Task<int> t2 = Task<int>.Factory.StartNew(() =>
                {
                    b.SignalAndWait();
                    b.SignalAndWait();
                    throw oce;
                }, cts.Token);
                Task t1 = t2;
                b.SignalAndWait(); // make sure task is started before we cancel
                cts.Cancel();
                b.SignalAndWait(); // release task to complete
                tasks.Add(t2);

                // A WhenAll Task
                tasks.Add(Task.WhenAll(t1));
                tasks.Add(Task.WhenAll(t1, Task.FromResult(42)));
                tasks.Add(Task.WhenAll(Task.FromResult(42), t1));
                tasks.Add(Task.WhenAll(t1, t1, t1));

                // A WhenAll Task<int[]>
                tasks.Add(Task.WhenAll(t2));
                tasks.Add(Task.WhenAll(t2, Task.FromResult(42)));
                tasks.Add(Task.WhenAll(Task.FromResult(42), t2));
                tasks.Add(Task.WhenAll(t2, t2, t2));

                // A Task.Run Task and Task<int>
                tasks.Add(Task.Run(() => t1));
                tasks.Add(Task.Run(() => t2));

                // A FromAsync Task and Task<int>
                tasks.Add(Task.Factory.FromAsync(t1, new Action<IAsyncResult>(ar => { throw oce; })));
                tasks.Add(Task<int>.Factory.FromAsync(t2, new Func<IAsyncResult, int>(ar => { throw oce; })));

                // Test each kind of task
                foreach (var task in tasks)
                {
                    ((IAsyncResult)task).AsyncWaitHandle.WaitOne();
                    try
                    {
                        if (task is Task<int>)
                        {
                            ((Task<int>)task).GetAwaiter().GetResult();
                        }
                        else if (task is Task<int[]>)
                        {
                            ((Task<int[]>)task).GetAwaiter().GetResult();
                        }
                        else
                        {
                            task.GetAwaiter().GetResult();
                        }
                        Assert.True(false, "     > FAILURE. Expected an OCE to be thrown.");
                    }
                    catch (Exception exc)
                    {
                        Assert.True(
                           Object.ReferenceEquals(oce, exc),
                           "     > FAILURE. The thrown exception was not the original instance.");
                    }
                }
            }
        }
コード例 #15
0
ファイル: WorkCoordinator.cs プロジェクト: GloryChou/roslyn
 private bool NotOurShutdownToken(OperationCanceledException oce)
 {
     return oce.CancellationToken == _shutdownToken;
 }
コード例 #16
0
ファイル: fromasync.cs プロジェクト: wzchua/docs
        static void Main()
        {
            WebDataDownloader downloader = new WebDataDownloader();

            string[] addresses = { "http://www.msnbc.com",   "http://www.yahoo.com",
                                   "http://www.nytimes.com", "http://www.washingtonpost.com",
                                   "http://www.latimes.com", "http://www.newsday.com" };
            CancellationTokenSource cts = new CancellationTokenSource();

            // Create a UI thread from which to cancel the entire operation
            Task.Factory.StartNew(() =>
            {
                Console.WriteLine("Press c to cancel");
                if (Console.ReadKey().KeyChar == 'c')
                {
                    cts.Cancel();
                }
            });

            // Using a neutral search term that is sure to get some hits.
            Task <string[]> webTask = downloader.GetWordCounts(addresses, "the", cts.Token);

            // Do some other work here unless the method has already completed.
            if (!webTask.IsCompleted)
            {
                // Simulate some work.
                Thread.SpinWait(5000000);
            }

            string[] results = null;
            try
            {
                results = webTask.Result;
            }
            catch (AggregateException e)
            {
                foreach (var ex in e.InnerExceptions)
                {
                    OperationCanceledException oce = ex as OperationCanceledException;
                    if (oce != null)
                    {
                        if (oce.CancellationToken == cts.Token)
                        {
                            Console.WriteLine("Operation canceled by user.");
                        }
                    }
                    else
                    {
                        Console.WriteLine(ex.Message);
                    }
                }
            }
            finally
            {
                cts.Dispose();
            }
            if (results != null)
            {
                foreach (var item in results)
                {
                    Console.WriteLine(item);
                }
            }
            Console.ReadKey();
        }
コード例 #17
0
            public override void DidCompleteWithError (NSUrlSession session, NSUrlSessionTask task, NSError error)
            {
                var data = getResponseForTask(task);
                data.IsCompleted = true;

                if (error != null) {
                    var ex = default(Exception);
                    if (error.Description.StartsWith("cancel", StringComparison.OrdinalIgnoreCase)) {
                        ex = new OperationCanceledException();
                    } else {
                        ex = new WebException(error.LocalizedDescription);
                    }

                    data.FutureResponse.TrySetException(ex);
                    data.ResponseBody.SetException(ex);
                    return;
                }

                data.ResponseBody.Complete();
                lock (This.inflightRequests) {
                    This.inflightRequests.Remove(task);
                }
            }
コード例 #18
0
 public Exception HandleCancellation(OperationCanceledException exception)
 {
     // TODO
     throw new NotImplementedException("need to implement how cancellation is handled");
 }
コード例 #19
0
        /// <summary>
        /// Executes the operation asynchronously.
        /// </summary>
        /// <param name="executionToken">The execution token.</param>
        /// <param name="implementation">The implementation that handles processing the result of the command.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <param name="state">User supplied state.</param>
        /// <returns>
        /// Task.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// executionToken;executionToken is null.
        /// or
        /// implementation;implementation is null.
        /// </exception>
        protected override async Task <int?> ExecuteAsync(CommandExecutionToken <NpgsqlCommand, NpgsqlParameter> executionToken, CommandImplementationAsync <NpgsqlCommand> implementation, CancellationToken cancellationToken, object state)
        {
            if (executionToken == null)
            {
                throw new ArgumentNullException("executionToken", "executionToken is null.");
            }
            if (implementation == null)
            {
                throw new ArgumentNullException("implementation", "implementation is null.");
            }

            var startTime = DateTimeOffset.Now;

            OnExecutionStarted(executionToken, startTime, state);

            try
            {
                using (var cmd = new NpgsqlCommand())
                {
                    cmd.Connection  = m_Connection;
                    cmd.Transaction = m_Transaction;
                    if (DefaultCommandTimeout.HasValue)
                    {
                        cmd.CommandTimeout = (int)DefaultCommandTimeout.Value.TotalSeconds;
                    }
                    cmd.CommandText = executionToken.CommandText;
                    cmd.CommandType = executionToken.CommandType;
                    foreach (var param in executionToken.Parameters)
                    {
                        cmd.Parameters.Add(param);
                    }

                    int?rows;
                    if (((PostgreSqlCommandExecutionToken)executionToken).DereferenceCursors)
                    {
                        rows = await DereferenceCursorsAsync(cmd, implementation).ConfigureAwait(false);
                    }
                    else
                    {
                        rows = await implementation(cmd).ConfigureAwait(false);
                    }

                    executionToken.RaiseCommandExecuted(cmd, rows);
                    OnExecutionFinished(executionToken, startTime, DateTimeOffset.Now, rows, state);
                    return(rows);
                }
            }
            catch (Exception ex)
            {
                if (cancellationToken.IsCancellationRequested) //convert Exception into a OperationCanceledException
                {
                    var ex2 = new OperationCanceledException("Operation was canceled.", ex, cancellationToken);
                    OnExecutionCanceled(executionToken, startTime, DateTimeOffset.Now, state);
                    throw ex2;
                }
                else
                {
                    OnExecutionError(executionToken, startTime, DateTimeOffset.Now, ex, state);
                    throw;
                }
            }
        }
コード例 #20
0
        public static void AlreadyCanceled(Action <ParallelQuery <int> > query)
        {
            ParallelQuery <int> s = Enumerables <int> .ThrowOnEnumeration(new ShouldNotBeInvokedException(), 2).AsParallel().WithCancellation(new CancellationToken(canceled: true));

            OperationCanceledException oce = Assert.Throws <OperationCanceledException>(() => query(s));
        }
コード例 #21
0
 public void TryCancel(OperationCanceledException exception)
 {
     _createRequestTcs.TrySetCanceled(exception);
     _responseTcs.TrySetCanceled(exception);
 }
コード例 #22
0
ファイル: MigrateCommand.cs プロジェクト: x-strong/Roslynator
 protected virtual void OperationCanceled(OperationCanceledException ex)
 {
     WriteLine("Operation was canceled.", Verbosity.Quiet);
 }
コード例 #23
0
        public static void RunAsyncAdditionalBehaviorsTests_NegativeCases2()
        {
            // Running tasks with exceptions.
            {
                var twa1 = Task.Run(() => { throw new Exception("uh oh"); });
                var twa2 = Task.Factory.StartNew(() => { throw new Exception("uh oh"); });
                var tasks = new Task[]
                    {
                        Task.Run(() => { throw new Exception("uh oh"); }),
                        Task.Factory.StartNew<int>(() => { throw new Exception("uh oh"); }),
                        Task.WhenAll(Task.Run(() => { throw new Exception("uh oh"); }), Task.Run(() => { throw new Exception("uh oh"); })),
                        Task.WhenAll<int>(Task.Run(new Func<int>(() => { throw new Exception("uh oh"); })), Task.Run(new Func<int>(() => { throw new Exception("uh oh"); }))),
                        Task.WhenAny(twa1, twa2).Unwrap(),
                        Task.WhenAny<int>(Task.Run(new Func<Task<int>>(() => { throw new Exception("uh oh"); }))).Unwrap(),
                        Task.Factory.StartNew(() => Task.Factory.StartNew(() => { throw new Exception("uh oh"); })).Unwrap(),
                        Task.Factory.StartNew<Task<int>>(() => Task.Factory.StartNew<int>(() => { throw new Exception("uh oh"); })).Unwrap(),
                        Task.Run(() => Task.Run(() => { throw new Exception("uh oh"); })),
                        Task.Run(() => Task.Run(new Func<int>(() => { throw new Exception("uh oh"); }))),
                        Task.Run(new Func<Task>(() => { throw new Exception("uh oh"); })),
                        Task.Run(new Func<Task<int>>(() => { throw new Exception("uh oh"); }))
                    };

                for (int i = 0; i < tasks.Length; i++)
                {
                    var task = tasks[i];
                    Assert.True(ValidateFaultedTask(task), "     > FAILURE. Task " + i + " didn't fault with the right stack trace.");
                }

                ((IAsyncResult)twa1).AsyncWaitHandle.WaitOne();
                ((IAsyncResult)twa2).AsyncWaitHandle.WaitOne();
                Exception ignored = twa1.Exception;
                ignored = twa2.Exception;
            }

            // Test that OCEs don't result in the unobserved event firing
            {
                var cts = new CancellationTokenSource();
                var oce = new OperationCanceledException(cts.Token);

                // A Task that throws an exception to cancel
                var b = new Barrier(2);
                Task t1 = Task.Factory.StartNew(() =>
                {
                    b.SignalAndWait();
                    b.SignalAndWait();
                    throw oce;
                }, cts.Token);
                b.SignalAndWait(); // make sure task is started before we cancel
                cts.Cancel();
                b.SignalAndWait(); // release task to complete

                // This test may be run concurrently with other tests in the suite, 
                // which can be problematic as TaskScheduler.UnobservedTaskException
                // is global state.  The handler is carefully written to be non-problematic
                // if it happens to be set during the execution of another test that has 
                // an unobserved exception.
                EventHandler<UnobservedTaskExceptionEventArgs> handler = 
                    (s, e) => Assert.DoesNotContain(oce, e.Exception.InnerExceptions);
                TaskScheduler.UnobservedTaskException += handler;
                ((IAsyncResult)t1).AsyncWaitHandle.WaitOne();
                t1 = null;
                for (int i = 0; i < 10; i++)
                {
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                }
                TaskScheduler.UnobservedTaskException -= handler;
            }
        }
コード例 #24
0
ファイル: WorkCoordinator.cs プロジェクト: ryzngard/roslyn
 private bool NotOurShutdownToken(OperationCanceledException oce)
 => oce.CancellationToken == _shutdownToken;
コード例 #25
0
ファイル: SQLiteDataSource.cs プロジェクト: docevaad/Chain
        /// <summary>
        /// execute as an asynchronous operation.
        /// </summary>
        /// <param name="executionToken">The execution token.</param>
        /// <param name="implementation">The implementation.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <param name="state">The state.</param>
        /// <returns>Task.</returns>
        protected override async Task<int?> ExecuteAsync(OperationExecutionToken<SQLiteConnection, SQLiteTransaction> executionToken, OperationImplementationAsync<SQLiteConnection, SQLiteTransaction> implementation, CancellationToken cancellationToken, object state)
        {
            if (executionToken == null)
                throw new ArgumentNullException("executionToken", "executionToken is null.");
            if (implementation == null)
                throw new ArgumentNullException("implementation", "implementation is null.");

            var mode = DisableLocks ? LockType.None : (executionToken as SQLiteOperationExecutionToken)?.LockType ?? LockType.Write;

            var startTime = DateTimeOffset.Now;
            OnExecutionStarted(executionToken, startTime, state);

            IDisposable lockToken = null;
            try
            {
                switch (mode)
                {
                    case LockType.Read: lockToken = await SyncLock.ReaderLockAsync().ConfigureAwait(false); break;
                    case LockType.Write: lockToken = await SyncLock.WriterLockAsync().ConfigureAwait(false); break;
                }

                using (var con = await CreateConnectionAsync(cancellationToken).ConfigureAwait(false))
                {
                    var rows = await implementation(con, null, cancellationToken).ConfigureAwait(false);
                    OnExecutionFinished(executionToken, startTime, DateTimeOffset.Now, rows, state);
                    return rows;
                }
            }
            catch (Exception ex)
            {
                if (cancellationToken.IsCancellationRequested) //convert SQLiteException into a OperationCanceledException 
                {
                    var ex2 = new OperationCanceledException("Operation was canceled.", ex, cancellationToken);
                    OnExecutionError(executionToken, startTime, DateTimeOffset.Now, ex2, state);
                    throw ex2;
                }
                else
                {
                    OnExecutionError(executionToken, startTime, DateTimeOffset.Now, ex, state);
                    throw;
                }
            }
            finally
            {
                if (lockToken != null)
                    lockToken.Dispose();
            }
        }
コード例 #26
0
        /// <summary>
        /// This does a mapping from hr to the exception and also takes care of making default exception in case of classic COM as COMException.
        /// and in winrt and marshal APIs as Exception.
        /// </summary>
        /// <param name="errorCode"></param>
        /// <param name="message"></param>
        /// <param name="createCOMException"></param>
        /// <returns></returns>
        internal static Exception GetMappingExceptionForHR(int errorCode, string message, bool createCOMException, bool hasErrorInfo)
        {
            if (errorCode >= 0)
            {
                return(null);
            }

            Exception exception = null;

            bool shouldDisplayHR = false;

            switch (errorCode)
            {
            case __HResults.COR_E_NOTFINITENUMBER:     // NotFiniteNumberException
            case __HResults.COR_E_ARITHMETIC:
                exception = new ArithmeticException();
                break;

            case __HResults.COR_E_ARGUMENT:
            case unchecked ((int)0x800A01C1):
            case unchecked ((int)0x800A01C2):
            case __HResults.CLR_E_BIND_UNRECOGNIZED_IDENTITY_FORMAT:
                exception = new ArgumentException();

                if (errorCode != __HResults.COR_E_ARGUMENT)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.E_BOUNDS:
            case __HResults.COR_E_ARGUMENTOUTOFRANGE:
            case __HResults.ERROR_NO_UNICODE_TRANSLATION:
                exception = new ArgumentOutOfRangeException();

                if (errorCode != __HResults.COR_E_ARGUMENTOUTOFRANGE)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_ARRAYTYPEMISMATCH:
                exception = new ArrayTypeMismatchException();
                break;

            case __HResults.COR_E_BADIMAGEFORMAT:
            case __HResults.CLDB_E_FILE_OLDVER:
            case __HResults.CLDB_E_INDEX_NOTFOUND:
            case __HResults.CLDB_E_FILE_CORRUPT:
            case __HResults.COR_E_NEWER_RUNTIME:
            case __HResults.COR_E_ASSEMBLYEXPECTED:
            case __HResults.ERROR_BAD_EXE_FORMAT:
            case __HResults.ERROR_EXE_MARKED_INVALID:
            case __HResults.CORSEC_E_INVALID_IMAGE_FORMAT:
            case __HResults.ERROR_NOACCESS:
            case __HResults.ERROR_INVALID_ORDINAL:
            case __HResults.ERROR_INVALID_DLL:
            case __HResults.ERROR_FILE_CORRUPT:
            case __HResults.COR_E_LOADING_REFERENCE_ASSEMBLY:
            case __HResults.META_E_BAD_SIGNATURE:
                exception = new BadImageFormatException();

                // Always show HR for BadImageFormatException
                shouldDisplayHR = true;

                break;

            case __HResults.COR_E_CUSTOMATTRIBUTEFORMAT:
                exception = new FormatException();
                break;     // CustomAttributeFormatException

            case __HResults.COR_E_DATAMISALIGNED:
                exception = InteropExtensions.CreateDataMisalignedException(message);     // TODO: Do we need to add msg here?
                break;

            case __HResults.COR_E_DIVIDEBYZERO:
            case __HResults.CTL_E_DIVISIONBYZERO:
                exception = new DivideByZeroException();

                if (errorCode != __HResults.COR_E_DIVIDEBYZERO)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_DLLNOTFOUND:
#if ENABLE_WINRT
                exception = new DllNotFoundException();
#endif
                break;

            case __HResults.COR_E_DUPLICATEWAITOBJECT:
                exception = new ArgumentException();
                break;     // DuplicateWaitObjectException

            case __HResults.COR_E_ENDOFSTREAM:
            case unchecked ((int)0x800A003E):
                exception = new System.IO.EndOfStreamException();

                if (errorCode != __HResults.COR_E_ENDOFSTREAM)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_TYPEACCESS:     // TypeAccessException
            case __HResults.COR_E_ENTRYPOINTNOTFOUND:
                exception = new TypeLoadException();

                break;     // EntryPointNotFoundException

            case __HResults.COR_E_EXCEPTION:
                exception = new Exception();
                break;

            case __HResults.COR_E_DIRECTORYNOTFOUND:
            case __HResults.STG_E_PATHNOTFOUND:
            case __HResults.CTL_E_PATHNOTFOUND:
                exception = new System.IO.DirectoryNotFoundException();

                if (errorCode != __HResults.COR_E_DIRECTORYNOTFOUND)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_FILELOAD:
            case __HResults.FUSION_E_INVALID_PRIVATE_ASM_LOCATION:
            case __HResults.FUSION_E_SIGNATURE_CHECK_FAILED:
            case __HResults.FUSION_E_LOADFROM_BLOCKED:
            case __HResults.FUSION_E_CACHEFILE_FAILED:
            case __HResults.FUSION_E_ASM_MODULE_MISSING:
            case __HResults.FUSION_E_INVALID_NAME:
            case __HResults.FUSION_E_PRIVATE_ASM_DISALLOWED:
            case __HResults.FUSION_E_HOST_GAC_ASM_MISMATCH:
            case __HResults.COR_E_MODULE_HASH_CHECK_FAILED:
            case __HResults.FUSION_E_REF_DEF_MISMATCH:
            case __HResults.SECURITY_E_INCOMPATIBLE_SHARE:
            case __HResults.SECURITY_E_INCOMPATIBLE_EVIDENCE:
            case __HResults.SECURITY_E_UNVERIFIABLE:
            case __HResults.COR_E_FIXUPSINEXE:
            case __HResults.ERROR_TOO_MANY_OPEN_FILES:
            case __HResults.ERROR_SHARING_VIOLATION:
            case __HResults.ERROR_LOCK_VIOLATION:
            case __HResults.ERROR_OPEN_FAILED:
            case __HResults.ERROR_DISK_CORRUPT:
            case __HResults.ERROR_UNRECOGNIZED_VOLUME:
            case __HResults.ERROR_DLL_INIT_FAILED:
            case __HResults.FUSION_E_CODE_DOWNLOAD_DISABLED:
            case __HResults.CORSEC_E_MISSING_STRONGNAME:
            case __HResults.MSEE_E_ASSEMBLYLOADINPROGRESS:
            case __HResults.ERROR_FILE_INVALID:
                exception = new System.IO.FileLoadException();

                shouldDisplayHR = true;
                break;

            case __HResults.COR_E_PATHTOOLONG:
                exception = new System.IO.PathTooLongException();
                break;

            case __HResults.COR_E_IO:
            case __HResults.CTL_E_DEVICEIOERROR:
            case unchecked ((int)0x800A793C):
            case unchecked ((int)0x800A793D):
                exception = new System.IO.IOException();

                if (errorCode != __HResults.COR_E_IO)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.ERROR_FILE_NOT_FOUND:
            case __HResults.ERROR_MOD_NOT_FOUND:
            case __HResults.ERROR_INVALID_NAME:
            case __HResults.CTL_E_FILENOTFOUND:
            case __HResults.ERROR_BAD_NET_NAME:
            case __HResults.ERROR_BAD_NETPATH:
            case __HResults.ERROR_NOT_READY:
            case __HResults.ERROR_WRONG_TARGET_NAME:
            case __HResults.INET_E_UNKNOWN_PROTOCOL:
            case __HResults.INET_E_CONNECTION_TIMEOUT:
            case __HResults.INET_E_CANNOT_CONNECT:
            case __HResults.INET_E_RESOURCE_NOT_FOUND:
            case __HResults.INET_E_OBJECT_NOT_FOUND:
            case __HResults.INET_E_DOWNLOAD_FAILURE:
            case __HResults.INET_E_DATA_NOT_AVAILABLE:
            case __HResults.ERROR_DLL_NOT_FOUND:
            case __HResults.CLR_E_BIND_ASSEMBLY_VERSION_TOO_LOW:
            case __HResults.CLR_E_BIND_ASSEMBLY_PUBLIC_KEY_MISMATCH:
            case __HResults.CLR_E_BIND_ASSEMBLY_NOT_FOUND:
                exception = new System.IO.FileNotFoundException();

                shouldDisplayHR = true;
                break;

            case __HResults.COR_E_FORMAT:
                exception = new FormatException();
                break;

            case __HResults.COR_E_INDEXOUTOFRANGE:
            case unchecked ((int)0x800a0009):
                exception = new IndexOutOfRangeException();

                if (errorCode != __HResults.COR_E_INDEXOUTOFRANGE)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_INVALIDCAST:
                exception = new InvalidCastException();
                break;

            case __HResults.COR_E_INVALIDCOMOBJECT:
                exception = new InvalidComObjectException();
                break;

            case __HResults.COR_E_INVALIDOLEVARIANTTYPE:
                exception = new InvalidOleVariantTypeException();
                break;

            case __HResults.COR_E_INVALIDOPERATION:
            case __HResults.E_ILLEGAL_STATE_CHANGE:
            case __HResults.E_ILLEGAL_METHOD_CALL:
            case __HResults.E_ILLEGAL_DELEGATE_ASSIGNMENT:
            case __HResults.APPMODEL_ERROR_NO_PACKAGE:
                exception = new InvalidOperationException();

                if (errorCode != __HResults.COR_E_INVALIDOPERATION)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_MARSHALDIRECTIVE:
                exception = new MarshalDirectiveException();
                break;

            case __HResults.COR_E_METHODACCESS:            // MethodAccessException
            case __HResults.META_E_CA_FRIENDS_SN_REQUIRED: // MethodAccessException
            case __HResults.COR_E_FIELDACCESS:
            case __HResults.COR_E_MEMBERACCESS:
                exception = new MemberAccessException();

                if (errorCode != __HResults.COR_E_METHODACCESS)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_MISSINGFIELD:     // MissingFieldException
            case __HResults.COR_E_MISSINGMETHOD:    // MissingMethodException
            case __HResults.COR_E_MISSINGMEMBER:
            case unchecked ((int)0x800A01CD):
                exception = new MissingMemberException();
                break;

            case __HResults.COR_E_MISSINGMANIFESTRESOURCE:
                exception = new System.Resources.MissingManifestResourceException();
                break;

            case __HResults.COR_E_NOTSUPPORTED:
            case unchecked ((int)0x800A01B6):
            case unchecked ((int)0x800A01BD):
            case unchecked ((int)0x800A01CA):
            case unchecked ((int)0x800A01CB):
                exception = new NotSupportedException();

                if (errorCode != __HResults.COR_E_NOTSUPPORTED)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_NULLREFERENCE:
                exception = new NullReferenceException();
                break;

            case __HResults.COR_E_OBJECTDISPOSED:
            case __HResults.RO_E_CLOSED:
                // No default constructor
                exception = new ObjectDisposedException(String.Empty);
                break;

            case __HResults.COR_E_OPERATIONCANCELED:
#if ENABLE_WINRT
                exception = new OperationCanceledException();
#endif
                break;

            case __HResults.COR_E_OVERFLOW:
            case __HResults.CTL_E_OVERFLOW:
                exception = new OverflowException();
                break;

            case __HResults.COR_E_PLATFORMNOTSUPPORTED:
                exception = new PlatformNotSupportedException(message);
                break;

            case __HResults.COR_E_RANK:
                exception = new RankException();
                break;

            case __HResults.COR_E_REFLECTIONTYPELOAD:
#if ENABLE_WINRT
                exception = new System.Reflection.ReflectionTypeLoadException(null, null);
#endif
                break;

            case __HResults.COR_E_SECURITY:
            case __HResults.CORSEC_E_INVALID_STRONGNAME:
            case __HResults.CTL_E_PERMISSIONDENIED:
            case unchecked ((int)0x800A01A3):
            case __HResults.CORSEC_E_INVALID_PUBLICKEY:
            case __HResults.CORSEC_E_SIGNATURE_MISMATCH:
                exception = new System.Security.SecurityException();
                break;

            case __HResults.COR_E_SAFEARRAYRANKMISMATCH:
                exception = new SafeArrayRankMismatchException();
                break;

            case __HResults.COR_E_SAFEARRAYTYPEMISMATCH:
                exception = new SafeArrayTypeMismatchException();
                break;

            case __HResults.COR_E_SERIALIZATION:
                exception = ConstructExceptionUsingReflection(
                    "System.Runtime.Serialization.SerializationException, System.Runtime.Serialization.Primitives, Version=4.0.0.0",
                    message);
                break;

            case __HResults.COR_E_SYNCHRONIZATIONLOCK:
                exception = new System.Threading.SynchronizationLockException();
                break;

            case __HResults.COR_E_TARGETINVOCATION:
                exception = new System.Reflection.TargetInvocationException(null);
                break;

            case __HResults.COR_E_TARGETPARAMCOUNT:
                exception = new System.Reflection.TargetParameterCountException();
                break;

            case __HResults.COR_E_TYPEINITIALIZATION:
                exception = InteropExtensions.CreateTypeInitializationException(message);
                break;

            case __HResults.COR_E_TYPELOAD:
            case __HResults.RO_E_METADATA_NAME_NOT_FOUND:
            case __HResults.CLR_E_BIND_TYPE_NOT_FOUND:
                exception = new TypeLoadException();

                if (errorCode != __HResults.COR_E_TYPELOAD)
                {
                    shouldDisplayHR = true;
                }

                break;

            case __HResults.COR_E_UNAUTHORIZEDACCESS:
            case __HResults.CTL_E_PATHFILEACCESSERROR:
            case unchecked ((int)0x800A014F):
                exception = new UnauthorizedAccessException();

                shouldDisplayHR = true;

                break;

            case __HResults.COR_E_VERIFICATION:
                exception = new System.Security.VerificationException();
                break;

            case __HResults.E_NOTIMPL:
                exception = new NotImplementedException();
                break;

            case __HResults.E_OUTOFMEMORY:
            case __HResults.CTL_E_OUTOFMEMORY:
            case unchecked ((int)0x800A7919):
                exception = new OutOfMemoryException();

                if (errorCode != __HResults.E_OUTOFMEMORY)
                {
                    shouldDisplayHR = true;
                }

                break;

#if ENABLE_WINRT
            case __HResults.E_XAMLPARSEFAILED:
                exception = ConstructExceptionUsingReflection(
                    "Windows.UI.Xaml.Markup.XamlParseException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0",
                    message);
                break;

            case __HResults.E_ELEMENTNOTAVAILABLE:
                exception = ConstructExceptionUsingReflection(
                    "Windows.UI.Xaml.Automation.ElementNotAvailableException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0",
                    message);
                break;

            case __HResults.E_ELEMENTNOTENABLED:
                exception = ConstructExceptionUsingReflection(
                    "Windows.UI.Xaml.Automation.ElementNotEnabledException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0",
                    message);
                break;

            case __HResults.E_LAYOUTCYCLE:
                exception = ConstructExceptionUsingReflection(
                    "Windows.UI.Xaml.LayoutCycleException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0",
                    message);
                break;
#endif // ENABLE_WINRT
            case __HResults.COR_E_AMBIGUOUSMATCH:     // AmbiguousMatchException
            case __HResults.COR_E_APPLICATION:     // ApplicationException
            case __HResults.COR_E_APPDOMAINUNLOADED:          // AppDomainUnloadedException
            case __HResults.COR_E_CANNOTUNLOADAPPDOMAIN:      // CannotUnloadAppDomainException
            case __HResults.COR_E_CODECONTRACTFAILED:         // ContractException
            case __HResults.COR_E_CONTEXTMARSHAL:             // ContextMarshalException
            case __HResults.CORSEC_E_CRYPTO:                  // CryptographicException
            case __HResults.CORSEC_E_CRYPTO_UNEX_OPER:        // CryptographicUnexpectedOperationException
            case __HResults.COR_E_EXECUTIONENGINE:            // ExecutionEngineException
            case __HResults.COR_E_INSUFFICIENTEXECUTIONSTACK: // InsufficientExecutionStackException
            case __HResults.COR_E_INVALIDFILTERCRITERIA:      // InvalidFilterCriteriaException
            case __HResults.COR_E_INVALIDPROGRAM:             // InvalidProgramException
            case __HResults.COR_E_MULTICASTNOTSUPPORTED:      // MulticastNotSupportedException
            case __HResults.COR_E_REMOTING:                   // RemotingException
            case __HResults.COR_E_RUNTIMEWRAPPED:             // RuntimeWrappedException
            case __HResults.COR_E_SERVER:                     // ServerException
            case __HResults.COR_E_STACKOVERFLOW:              // StackOverflowException
            case __HResults.CTL_E_OUTOFSTACKSPACE:            // StackOverflowException
            case __HResults.COR_E_SYSTEM:                     // SystemException
            case __HResults.COR_E_TARGET:                     // TargetException
            case __HResults.COR_E_THREADABORTED:              // TargetException
            case __HResults.COR_E_THREADINTERRUPTED:          // ThreadInterruptedException
            case __HResults.COR_E_THREADSTATE:                // ThreadStateException
            case __HResults.COR_E_THREADSTART:                // ThreadStartException
            case __HResults.COR_E_TYPEUNLOADED:               // TypeUnloadedException
            case __HResults.CORSEC_E_POLICY_EXCEPTION:        // PolicyException
            case __HResults.CORSEC_E_NO_EXEC_PERM:            // PolicyException
            case __HResults.CORSEC_E_MIN_GRANT_FAIL:          // PolicyException
            case __HResults.CORSEC_E_XMLSYNTAX:               // XmlSyntaxException
            case __HResults.ISS_E_ALLOC_TOO_LARGE:            // IsolatedStorageException
            case __HResults.ISS_E_BLOCK_SIZE_TOO_SMALL:       // IsolatedStorageException
            case __HResults.ISS_E_CALLER:                     // IsolatedStorageException
            case __HResults.ISS_E_CORRUPTED_STORE_FILE:       // IsolatedStorageException
            case __HResults.ISS_E_CREATE_DIR:                 // IsolatedStorageException
            case __HResults.ISS_E_CREATE_MUTEX:               // IsolatedStorageException
            case __HResults.ISS_E_DEPRECATE:                  // IsolatedStorageException
            case __HResults.ISS_E_FILE_NOT_MAPPED:            // IsolatedStorageException
            case __HResults.ISS_E_FILE_WRITE:                 // IsolatedStorageException
            case __HResults.ISS_E_GET_FILE_SIZE:              // IsolatedStorageException
            case __HResults.ISS_E_ISOSTORE:                   // IsolatedStorageException
            case __HResults.ISS_E_LOCK_FAILED:                // IsolatedStorageException
            case __HResults.ISS_E_MACHINE:                    // IsolatedStorageException
            case __HResults.ISS_E_MACHINE_DACL:               // IsolatedStorageException
            case __HResults.ISS_E_MAP_VIEW_OF_FILE:           // IsolatedStorageException
            case __HResults.ISS_E_OPEN_FILE_MAPPING:          // IsolatedStorageException
            case __HResults.ISS_E_OPEN_STORE_FILE:            // IsolatedStorageException
            case __HResults.ISS_E_PATH_LENGTH:                // IsolatedStorageException
            case __HResults.ISS_E_SET_FILE_POINTER:           // IsolatedStorageException
            case __HResults.ISS_E_STORE_NOT_OPEN:             // IsolatedStorageException
            case __HResults.ISS_E_STORE_VERSION:              // IsolatedStorageException
            case __HResults.ISS_E_TABLE_ROW_NOT_FOUND:        // IsolatedStorageException
            case __HResults.ISS_E_USAGE_WILL_EXCEED_QUOTA:    // IsolatedStorageException
            case __HResults.E_FAIL:
            default:
                break;
            }

            if (exception == null)
            {
                if (createCOMException)
                {
                    exception = new COMException();
                    if (errorCode != __HResults.E_FAIL)
                    {
                        shouldDisplayHR = true;
                    }
                }
                else
                {
                    exception = new Exception();
                    if (errorCode != __HResults.COR_E_EXCEPTION)
                    {
                        shouldDisplayHR = true;
                    }
                }
            }

            bool shouldConstructMessage = false;
            if (hasErrorInfo)
            {
                // If there is a IErrorInfo/IRestrictedErrorInfo, only construct a new error message if
                // the message is not available and do not use the shouldDisplayHR setting
                if (message == null)
                {
                    shouldConstructMessage = true;
                }
            }
            else
            {
                // If there is no IErrorInfo, use the shouldDisplayHR setting from the big switch/case above
                shouldConstructMessage = shouldDisplayHR;
            }

            if (shouldConstructMessage)
            {
                //
                // Append the HR into error message, just in case the app wants to look at the HR in
                // message to determine behavior.  We didn't expose HResult property until v4.5 and
                // GetHRFromException has side effects so probably Message was their only choice.
                // This behavior is probably not exactly the same as in desktop but it is fine to append
                // more message at the end. In any case, having the HR in the error message are helpful
                // to developers.
                // This makes sure:
                // 1. We always have a HR 0xNNNNNNNN in the message
                // 2. Put in a nice "Exception thrown from HRESULT" message if we can
                // 3. Wrap it in () if there is an existing message
                //

                // TODO: Add Symbolic Name into Messaage, convert 0x80020006 to DISP_E_UNKNOWNNAME
                string hrMessage = String.Format("{0} 0x{1:X}", SR.Excep_FromHResult, errorCode);

                message = ExternalInterop.GetMessage(errorCode);

                // Always make sure we have at least the HRESULT part in retail build or when the message
                // is empty.
                if (message == null)
                {
                    message = hrMessage;
                }
                else
                {
                    message = message + " (" + hrMessage + ")";
                }
            }

            if (message != null)
            {
                // Set message explicitly rather than calling constructor because certain ctors would append a
                // prefix to the message and that is not what we want
                InteropExtensions.SetExceptionMessage(exception, message);
            }

            InteropExtensions.SetExceptionErrorCode(exception, errorCode);

            return(exception);
        }
コード例 #27
0
            Exception createExceptionForNSError(NSError error)
            {
                var ret = default(Exception);
                var urlError = default(NSUrlError);
                var webExceptionStatus = WebExceptionStatus.UnknownError;

                // If the domain is something other than NSUrlErrorDomain, 
                // just grab the default info
                if (error.Domain != NSError.NSUrlErrorDomain) goto leave;

                // Convert the error code into an enumeration (this is future
                // proof, rather than just casting integer)
                if (!Enum.TryParse<NSUrlError>(error.Code.ToString(), out urlError)) urlError = NSUrlError.Unknown;

                // Parse the enum into a web exception status or exception. some
                // of these values don't necessarily translate completely to
                // what WebExceptionStatus supports, so made some best guesses
                // here.  for your reading pleasure, compare these:
                //
                // Apple docs: https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/Reference/reference.html
                // .NET docs: http://msdn.microsoft.com/en-us/library/system.net.webexceptionstatus(v=vs.110).aspx
                switch(urlError) {
                case NSUrlError.Cancelled:
                case NSUrlError.UserCancelledAuthentication:
                    ret = new OperationCanceledException();
                    break;
                case NSUrlError.BadURL:
                case NSUrlError.UnsupportedURL:
                case NSUrlError.CannotConnectToHost:
                case NSUrlError.ResourceUnavailable:
                case NSUrlError.NotConnectedToInternet:
                case NSUrlError.UserAuthenticationRequired:
                    webExceptionStatus = WebExceptionStatus.ConnectFailure;
                    break;
                case NSUrlError.TimedOut:
                    webExceptionStatus = WebExceptionStatus.Timeout;
                    break;
                case NSUrlError.CannotFindHost:
                case NSUrlError.DNSLookupFailed:
                    webExceptionStatus = WebExceptionStatus.NameResolutionFailure;
                    break;
                case NSUrlError.DataLengthExceedsMaximum:
                    webExceptionStatus = WebExceptionStatus.MessageLengthLimitExceeded;
                    break;
                case NSUrlError.NetworkConnectionLost:
                    webExceptionStatus = WebExceptionStatus.ConnectionClosed;
                    break;
                case NSUrlError.HTTPTooManyRedirects:
                case NSUrlError.RedirectToNonExistentLocation:
                    webExceptionStatus = WebExceptionStatus.ProtocolError;
                    break;
                case NSUrlError.BadServerResponse:
                case NSUrlError.ZeroByteResource:
                case NSUrlError.CannotDecodeContentData:
                case NSUrlError.CannotDecodeRawData:
                case NSUrlError.CannotParseResponse:
                case NSUrlError.FileDoesNotExist:
                case NSUrlError.FileIsDirectory:
                case NSUrlError.NoPermissionsToReadFile:
                case NSUrlError.CannotLoadFromNetwork:
                case NSUrlError.CannotCreateFile:
                case NSUrlError.CannotOpenFile:
                case NSUrlError.CannotCloseFile:
                case NSUrlError.CannotWriteToFile:
                case NSUrlError.CannotRemoveFile:
                case NSUrlError.CannotMoveFile:
                case NSUrlError.DownloadDecodingFailedMidStream:
                case NSUrlError.DownloadDecodingFailedToComplete:
                    webExceptionStatus = WebExceptionStatus.ReceiveFailure;
                    break;
                case NSUrlError.SecureConnectionFailed:
                    webExceptionStatus = WebExceptionStatus.SecureChannelFailure;
                    break;
                case NSUrlError.ServerCertificateHasBadDate:
                case NSUrlError.ServerCertificateHasUnknownRoot:
                case NSUrlError.ServerCertificateNotYetValid:
                case NSUrlError.ServerCertificateUntrusted:
                case NSUrlError.ClientCertificateRejected:
                    webExceptionStatus = WebExceptionStatus.TrustFailure;
                    break;
                }

                // If we parsed a web exception status code, create an exception
                // for it
                if (webExceptionStatus != WebExceptionStatus.UnknownError) {
                    ret = new WebException(error.LocalizedDescription, webExceptionStatus);
                }

            leave:
                // If no exception generated yet, throw a normal exception with
                // the error message.
                return ret ?? new Exception(error.LocalizedDescription);
            }
コード例 #28
0
 public TUSException(OperationCanceledException ex)
     : base(ex.Message, ex, WebExceptionStatus.RequestCanceled, null)
 {
     this.OriginalException = null;
 }
コード例 #29
0
        /// <summary>
        /// Execute the operation asynchronously.
        /// </summary>
        /// <param name="executionToken">The execution token.</param>
        /// <param name="implementation">The implementation.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <param name="state">The state.</param>
        /// <returns>Task.</returns>
        protected override async Task<int?> ExecuteAsync(OperationExecutionToken<OleDbConnection, OleDbTransaction> executionToken, OperationImplementationAsync<OleDbConnection, OleDbTransaction> implementation, CancellationToken cancellationToken, object state)
        {
            if (executionToken == null)
                throw new ArgumentNullException("executionToken", "executionToken is null.");
            if (implementation == null)
                throw new ArgumentNullException("implementation", "implementation is null.");

            var startTime = DateTimeOffset.Now;
            OnExecutionStarted(executionToken, startTime, state);

            try
            {
                using (var con = CreateConnection())
                {
                    var rows = await implementation(con, null, cancellationToken).ConfigureAwait(false);
                    OnExecutionFinished(executionToken, startTime, DateTimeOffset.Now, rows, state);
                    return rows;
                }
            }
            catch (Exception ex)
            {
                if (cancellationToken.IsCancellationRequested) //convert Exception into a OperationCanceledException 
                {
                    var ex2 = new OperationCanceledException("Operation was canceled.", ex, cancellationToken);
                    OnExecutionCanceled(executionToken, startTime, DateTimeOffset.Now, state);
                    throw ex2;
                }
                else
                {
                    OnExecutionError(executionToken, startTime, DateTimeOffset.Now, ex, state);
                    throw;
                }
            }
        }
コード例 #30
0
            private void ExecuteInternal()
            {
                Debug.Assert(_operation >= Operation.Read && _operation <= Operation.WriteGather);

                long      result    = 0;
                Exception?exception = null;

                try
                {
                    // This is the operation's last chance to be canceled.
                    if (_cancellationToken.IsCancellationRequested)
                    {
                        exception = new OperationCanceledException(_cancellationToken);
                    }
                    else
                    {
                        switch (_operation)
                        {
                        case Operation.Read:
                            Memory <byte> writableSingleSegment = MemoryMarshal.AsMemory(_singleSegment);
                            result = RandomAccess.ReadAtOffset(_fileHandle, writableSingleSegment.Span, _fileOffset);
                            break;

                        case Operation.Write:
                            result = RandomAccess.WriteAtOffset(_fileHandle, _singleSegment.Span, _fileOffset);
                            break;

                        case Operation.ReadScatter:
                            Debug.Assert(_readScatterBuffers != null);
                            result = RandomAccess.ReadScatterAtOffset(_fileHandle, _readScatterBuffers, _fileOffset);
                            break;

                        case Operation.WriteGather:
                            Debug.Assert(_writeGatherBuffers != null);
                            result = RandomAccess.WriteGatherAtOffset(_fileHandle, _writeGatherBuffers, _fileOffset);
                            break;
                        }
                    }
                }
                catch (Exception e)
                {
                    exception = e;
                }
                finally
                {
                    _operation          = Operation.None;
                    _context            = null;
                    _cancellationToken  = default;
                    _singleSegment      = default;
                    _readScatterBuffers = null;
                    _writeGatherBuffers = null;
                }

                if (exception == null)
                {
                    _source.SetResult(result);
                }
                else
                {
                    _source.SetException(exception);
                }
            }
コード例 #31
0
 private static void HandleCanceledOperations(CancellationToken cancellationToken, TaskCompletionSource <HttpResponseMessage> tcs, OperationCanceledException e)
 {
     if (cancellationToken.IsCancellationRequested && e.CancellationToken == cancellationToken)
     {
         tcs.TrySetCanceled();
     }
     else
     {
         tcs.TrySetException(e);
     }
 }
コード例 #32
0
        //-----------------------------------------------------------------------------------
        // Marks the end of a query's execution, waiting for all tasks to finish and
        // propagating any relevant exceptions.  Note that the full set of tasks must have
        // been initialized (with SetTask) before calling this.
        //

        internal void QueryEnd(bool userInitiatedDispose)
        {
            Debug.Assert(_rootTask != null);
            //Debug.Assert(Task.Current == null || (Task.Current != _rootTask && Task.Current.Parent != _rootTask));

            if (Interlocked.Exchange(ref _alreadyEnded, 1) == 0)
            {
                // There are four cases:
                // Case #1: Wait produced an exception that is not OCE(ct), or an AggregateException which is not full of OCE(ct) ==>  We rethrow.
                // Case #2: External cancellation has been requested ==> we'll manually throw OCE(externalToken).
                // Case #3a: We are servicing a call to Dispose() (and possibly also external cancellation has been requested).. simply return.
                // Case #3b: The enumerator has already been disposed (and possibly also external cancellation was requested).  Throw an ODE.
                // Case #4: No exceptions or explicit call to Dispose() by this caller ==> we just return.

                // See also "InlinedAggregationOperator" which duplicates some of this logic for the aggregators.
                // See also "QueryOpeningEnumerator" which duplicates some of this logic.
                // See also "ExceptionAggregator" which duplicates some of this logic.

                try
                {
                    // Wait for all the tasks to complete
                    // If any of the tasks ended in the Faulted stated, an AggregateException will be thrown.
                    _rootTask.Wait();
                }
                catch (AggregateException ae)
                {
                    AggregateException flattenedAE = ae.Flatten();
                    bool allOCEsOnTrackedExternalCancellationToken = true;
                    for (int i = 0; i < flattenedAE.InnerExceptions.Count; i++)
                    {
                        OperationCanceledException oce = flattenedAE.InnerExceptions[i] as OperationCanceledException;

                        // we only let it pass through iff:
                        // it is not null, not default, and matches the exact token we were given as being the external token
                        // and the external Token is actually canceled (ie not a spoof OCE(extCT) for a non-canceled extCT)
                        if (oce == null ||
                            !oce.CancellationToken.IsCancellationRequested ||
                            oce.CancellationToken != _cancellationState.ExternalCancellationToken)
                        {
                            allOCEsOnTrackedExternalCancellationToken = false;
                            break;
                        }
                    }

                    // if all the exceptions were OCE(externalToken), then we will propagate only a single OCE(externalToken) below
                    // otherwise, we flatten the aggregate (because the WaitAll above already aggregated) and rethrow.
                    if (!allOCEsOnTrackedExternalCancellationToken)
                    {
                        throw flattenedAE;  // Case #1
                    }
                }
                finally
                {
                    //_rootTask don't support Dispose on some platforms
                    IDisposable disposable = _rootTask as IDisposable;
                    if (disposable != null)
                    {
                        disposable.Dispose();
                    }
                }

                if (_cancellationState.MergedCancellationToken.IsCancellationRequested)
                {
                    // cancellation has occurred but no user-delegate exceptions were detected

                    // NOTE: it is important that we see other state variables correctly here, and that
                    // read-reordering hasn't played havoc.
                    // This is OK because
                    //   1. all the state writes (eg in the Initiate* methods) are volatile writes (standard .NET MM)
                    //   2. tokenCancellationRequested is backed by a volatile field, hence the reads below
                    //   won't get reordered about the read of token.IsCancellationRequested.

                    // If the query has already been disposed, we don't want to throw an OCE
                    if (!_cancellationState.TopLevelDisposedFlag.Value)
                    {
                        CancellationState.ThrowWithStandardMessageIfCanceled(_cancellationState.ExternalCancellationToken); // Case #2
                    }

                    //otherwise, given that there were no user-delegate exceptions (they would have been rethrown above),
                    //the only remaining situation is user-initiated dispose.
                    Debug.Assert(_cancellationState.TopLevelDisposedFlag.Value);

                    // If we aren't actively disposing, that means somebody else previously disposed
                    // of the enumerator. We must throw an ObjectDisposedException.
                    if (!userInitiatedDispose)
                    {
                        throw new ObjectDisposedException("enumerator", SR.PLINQ_DisposeRequested); // Case #3
                    }
                }
                // Case #4. nothing to do.
            }
        }
コード例 #33
0
ファイル: SQLiteDataSource.cs プロジェクト: chucker/Chain
        /// <summary>
        /// Executes the specified operation asynchronously.
        /// </summary>
        /// <param name="executionToken"></param>
        /// <param name="implementation"></param>
        /// <param name="cancellationToken"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        protected override async Task <int?> ExecuteAsync(CommandExecutionToken <SQLiteCommand, SQLiteParameter> executionToken, CommandImplementationAsync <SQLiteCommand> implementation, CancellationToken cancellationToken, object state)
        {
            if (executionToken == null)
            {
                throw new ArgumentNullException("executionToken", "executionToken is null.");
            }
            if (implementation == null)
            {
                throw new ArgumentNullException("implementation", "implementation is null.");
            }

            var mode = DisableLocks ? LockType.None : (executionToken as SQLiteCommandExecutionToken)?.LockType ?? LockType.Write;

            var startTime = DateTimeOffset.Now;

            OnExecutionStarted(executionToken, startTime, state);

            IDisposable lockToken = null;

            try
            {
                switch (mode)
                {
                case LockType.Read: lockToken = await SyncLock.ReaderLockAsync().ConfigureAwait(false); break;

                case LockType.Write: lockToken = await SyncLock.WriterLockAsync().ConfigureAwait(false); break;
                }

                using (var con = await CreateConnectionAsync(cancellationToken).ConfigureAwait(false))
                {
                    using (var cmd = new SQLiteCommand())
                    {
                        cmd.Connection = con;
                        if (DefaultCommandTimeout.HasValue)
                        {
                            cmd.CommandTimeout = (int)DefaultCommandTimeout.Value.TotalSeconds;
                        }
                        cmd.CommandText = executionToken.CommandText;
                        cmd.CommandType = executionToken.CommandType;
                        foreach (var param in executionToken.Parameters)
                        {
                            cmd.Parameters.Add(param);
                        }

                        executionToken.ApplyCommandOverrides(cmd);

                        var rows = await implementation(cmd).ConfigureAwait(false);

                        executionToken.RaiseCommandExecuted(cmd, rows);
                        OnExecutionFinished(executionToken, startTime, DateTimeOffset.Now, rows, state);
                        return(rows);
                    }
                }
            }
            catch (Exception ex)
            {
                if (cancellationToken.IsCancellationRequested) //convert SQLiteException into a OperationCanceledException
                {
                    var ex2 = new OperationCanceledException("Operation was canceled.", ex, cancellationToken);
                    OnExecutionError(executionToken, startTime, DateTimeOffset.Now, ex2, state);
                    throw ex2;
                }
                else
                {
                    OnExecutionError(executionToken, startTime, DateTimeOffset.Now, ex, state);
                    throw;
                }
            }
            finally
            {
                if (lockToken != null)
                {
                    lockToken.Dispose();
                }
            }
        }
コード例 #34
0
        private void OpenConnection(IConnection connection,
                                    string data,
                                    CancellationToken disconnectToken,
                                    Action initializeCallback,
                                    Action <Exception> errorCallback)
        {
            // If we're reconnecting add /connect to the url
            bool   reconnecting     = initializeCallback == null;
            var    callbackInvoker  = new ThreadSafeInvoker();
            var    requestDisposer  = new Disposer();
            Action initializeInvoke = () =>
            {
                callbackInvoker.Invoke(initializeCallback);
            };
            var url = connection.Url + (reconnecting ? "reconnect" : "connect") + GetReceiveQueryString(connection, data);

            connection.Trace(TraceLevels.Events, "SSE: GET {0}", url);

            HttpClient.Get(url, req =>
            {
                _request        = req;
                _request.Accept = "text/event-stream";

                connection.PrepareRequest(_request);
            }, isLongRunning: true).ContinueWith(task =>
            {
                if (task.IsFaulted || task.IsCanceled)
                {
                    Exception exception;

                    if (task.IsCanceled)
                    {
                        exception = new OperationCanceledException(Resources.Error_TaskCancelledException);
                    }
                    else
                    {
                        exception = task.Exception.Unwrap();
                    }

                    if (errorCallback != null)
                    {
                        callbackInvoker.Invoke((cb, ex) => cb(ex), errorCallback, exception);
                    }
                    else if (!_stop && reconnecting)
                    {
                        // Only raise the error event if we failed to reconnect
                        connection.OnError(exception);

                        Reconnect(connection, data, disconnectToken);
                    }
                    requestDisposer.Dispose();
                }
                else
                {
                    // If the disconnect token is canceled the response to the task doesn't matter.
                    if (disconnectToken.IsCancellationRequested)
                    {
                        return;
                    }

                    var response  = task.Result;
                    Stream stream = response.GetStream();

                    var eventSource = new EventSourceStreamReader(connection, stream);

                    var esCancellationRegistration = disconnectToken.SafeRegister(state =>
                    {
                        _stop = true;

                        ((IRequest)state).Abort();
                    },
                                                                                  _request);

                    eventSource.Opened = () =>
                    {
                        // This will noop if we're not in the reconnecting state
                        if (connection.ChangeState(ConnectionState.Reconnecting, ConnectionState.Connected))
                        {
                            // Raise the reconnect event if the connection comes back up
                            connection.OnReconnected();
                        }
                    };

                    eventSource.Message = sseEvent =>
                    {
                        if (sseEvent.EventType == EventType.Data)
                        {
                            if (sseEvent.Data.Equals("initialized", StringComparison.OrdinalIgnoreCase))
                            {
                                return;
                            }

                            bool shouldReconnect;
                            bool disconnected;
                            TransportHelper.ProcessResponse(connection, sseEvent.Data, out shouldReconnect, out disconnected, initializeInvoke);

                            if (disconnected)
                            {
                                _stop = true;
                                connection.Disconnect();
                            }
                        }
                    };

                    eventSource.Closed = exception =>
                    {
                        if (exception != null)
                        {
                            // Check if the request is aborted
                            bool isRequestAborted = ExceptionHelper.IsRequestAborted(exception);

                            if (!isRequestAborted)
                            {
                                // Don't raise exceptions if the request was aborted (connection was stopped).
                                connection.OnError(exception);
                            }
                        }

                        requestDisposer.Dispose();
                        esCancellationRegistration.Dispose();
                        response.Dispose();

                        if (_stop)
                        {
                            AbortHandler.CompleteAbort();
                        }
                        else if (AbortHandler.TryCompleteAbort())
                        {
                            // Abort() was called, so don't reconnect
                        }
                        else
                        {
                            Reconnect(connection, data, disconnectToken);
                        }
                    };

                    eventSource.Start();
                }
            });

            var requestCancellationRegistration = disconnectToken.SafeRegister(state =>
            {
                if (state != null)
                {
                    // This will no-op if the request is already finished.
                    ((IRequest)state).Abort();
                }

                if (errorCallback != null)
                {
                    callbackInvoker.Invoke((cb, token) =>
                    {
                        cb(new OperationCanceledException(Resources.Error_ConnectionCancelled, token));
                    }, errorCallback, disconnectToken);
                }
            }, _request);

            requestDisposer.Set(requestCancellationRegistration);
        }
コード例 #35
0
        public static void OperationCanceledException_PropagatesThroughCanceledTask(int lineNumber, Task task, OperationCanceledException expected)
        {
            var caught = Assert.ThrowsAny <OperationCanceledException>(() => task.GetAwaiter().GetResult());

            Assert.Same(expected, caught);
        }
コード例 #36
0
        //Identified as a possible concern in bug 544743.
        private static bool SemaphoreSlim_MultipleWaitersWithSeparateTokens()
        {
            TestHarness.TestLog("* SemaphoreSlimCancellationTests.SemaphoreSlim_MultipleWaitersWithSeparateTokens()");
            bool passed = true;

            SemaphoreSlim semaphoreSlim                = new SemaphoreSlim(0); // this semaphore will always be blocked for waiters.
            const int     waitTimeoutMilliseconds      = 1000;
            const int     waitBeforeCancelMilliseconds = 300;

            CancellationTokenSource cts1        = new CancellationTokenSource();
            CancellationTokenSource cts2        = new CancellationTokenSource();
            bool wait1WokeUpNormally            = false;
            bool wait2WokeUpNormally            = false;
            OperationCanceledException wait1OCE = null;
            OperationCanceledException wait2OCE = null;
            int wait1ElapsedMilliseconds        = -1;
            int wait2ElapsedMilliseconds        = -1;

            CountdownEvent cde_allThreadsFinished = new CountdownEvent(2);

            //Queue up cancellation of CTS1.
            ThreadPool.QueueUserWorkItem(
                unused =>
            {
                Thread.Sleep(waitBeforeCancelMilliseconds);     // wait a little while.
                cts1.Cancel();
            }
                );

            //Queue up a wait on mres(CTS1)
            ThreadPool.QueueUserWorkItem(
                unused =>
            {
                Stopwatch sw = Stopwatch.StartNew();
                try
                {
                    wait1WokeUpNormally = semaphoreSlim.Wait(waitTimeoutMilliseconds, cts1.Token);
                }
                catch (OperationCanceledException oce)
                {
                    wait1OCE = oce;
                }
                finally
                {
                    sw.Stop();
                }
                wait1ElapsedMilliseconds = (int)sw.Elapsed.TotalMilliseconds;

                cde_allThreadsFinished.Signal();
            }
                );

            //Queue up a wait on mres(CTS2)
            ThreadPool.QueueUserWorkItem(
                unused =>
            {
                Stopwatch sw = Stopwatch.StartNew();
                try
                {
                    wait2WokeUpNormally = semaphoreSlim.Wait(waitTimeoutMilliseconds, cts2.Token);
                }
                catch (OperationCanceledException oce)
                {
                    wait2OCE = oce;
                }
                finally
                {
                    sw.Stop();
                }
                wait2ElapsedMilliseconds = (int)sw.Elapsed.TotalMilliseconds;
                cde_allThreadsFinished.Signal();
            }
                );

            cde_allThreadsFinished.Wait();

            Console.WriteLine("        (first  wait duration [expecting <={0,4}]        ={1,4})", 500, wait1ElapsedMilliseconds);
            Console.WriteLine("        (second wait duration [expecting   {0,4} +-50ms] ={1,4})", waitTimeoutMilliseconds, wait2ElapsedMilliseconds);

            passed &= TestHarnessAssert.IsFalse(wait1WokeUpNormally, "The first wait should be canceled.");
            passed &= TestHarnessAssert.IsNotNull(wait1OCE, "The first wait should have thrown an OCE.");
            passed &= TestHarnessAssert.AreEqual(cts1.Token, OCEHelper.ExtractCT(wait1OCE), "The first wait should have thrown an OCE(cts1.token).");
            passed &= TestHarnessAssert.IsTrue(wait1ElapsedMilliseconds < 500, "[Warning: Timing Sensitive Test] The first wait should have canceled before 500ms elapsed.");


            passed &= TestHarnessAssert.IsFalse(wait2WokeUpNormally, "The second wait should not have woken up normally. It should have woken due to timeout.");
            passed &= TestHarnessAssert.IsNull(wait2OCE, "The second wait should not have thrown an OCE.");
            passed &= TestHarnessAssert.IsTrue(950 <= wait2ElapsedMilliseconds && wait2ElapsedMilliseconds <= 1050, "[Warning: Timing Sensitive Test] The second wait should have waited 1000ms +-50ms). Actual wait duration = " + wait2ElapsedMilliseconds);

            return(passed);
        }
コード例 #37
0
            public override Task <int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
            {
                if (buffer == null)
                {
                    throw new ArgumentNullException(nameof(buffer));
                }
                if (offset < 0)
                {
                    throw new ArgumentOutOfRangeException(nameof(offset));
                }
                if (count < 0)
                {
                    throw new ArgumentOutOfRangeException(nameof(count));
                }
                if (offset > buffer.Length - count)
                {
                    throw new ArgumentException(SR.net_http_buffer_insufficient_length, nameof(buffer));
                }
                CheckDisposed();

                EventSourceTrace("Buffer: {0}, Offset: {1}, Count: {2}", buffer.Length, offset, count);

                // Check for cancellation
                if (cancellationToken.IsCancellationRequested)
                {
                    EventSourceTrace("Canceled");
                    return(Task.FromCanceled <int>(cancellationToken));
                }

                lock (_lockObject)
                {
                    VerifyInvariants();

                    // If there's currently a pending read, fail this read, as we don't support concurrent reads.
                    if (_pendingReadRequest != null)
                    {
                        EventSourceTrace("Failing due to existing pending read; concurrent reads not supported.");
                        return(Task.FromException <int>(new InvalidOperationException(SR.net_http_content_no_concurrent_reads)));
                    }

                    // If the stream was already completed with failure, complete the read as a failure.
                    if (_completed != null && _completed != s_completionSentinel)
                    {
                        EventSourceTrace("Failing read with error: {0}", _completed);

                        OperationCanceledException oce = _completed as OperationCanceledException;
                        return((oce != null && oce.CancellationToken.IsCancellationRequested) ?
                               Task.FromCanceled <int>(oce.CancellationToken) :
                               Task.FromException <int>(MapToReadWriteIOException(_completed, isRead: true)));
                    }

                    // Quick check for if no data was actually requested.  We do this after the check
                    // for errors so that we can still fail the read and transfer the exception if we should.
                    if (count == 0)
                    {
                        return(s_zeroTask);
                    }

                    // If there's any data left over from a previous call, grab as much as we can.
                    if (_remainingDataCount > 0)
                    {
                        int bytesToCopy = Math.Min(count, _remainingDataCount);
                        Buffer.BlockCopy(_remainingData, _remainingDataOffset, buffer, offset, bytesToCopy);

                        _remainingDataOffset += bytesToCopy;
                        _remainingDataCount  -= bytesToCopy;
                        Debug.Assert(_remainingDataCount >= 0, "The remaining count should never go negative");
                        Debug.Assert(_remainingDataOffset <= _remainingData.Length, "The remaining offset should never exceed the buffer size");

                        EventSourceTrace("Read {0} bytes", bytesToCopy);
                        return(Task.FromResult(bytesToCopy));
                    }

                    // If the stream has already been completed, complete the read immediately.
                    if (_completed == s_completionSentinel)
                    {
                        EventSourceTrace("Stream already completed");
                        return(s_zeroTask);
                    }

                    // Finally, the stream is still alive, and we want to read some data, but there's no data
                    // in the buffer so we need to register ourself to get the next write.
                    if (cancellationToken.CanBeCanceled)
                    {
                        // If the cancellation token is cancelable, then we need to register for cancellation.
                        // We create a special CancelableReadState that carries with it additional info:
                        // the cancellation token and the registration with that token.  When cancellation
                        // is requested, we schedule a work item that tries to remove the read state
                        // from being pending, canceling it in the process.  This needs to happen under the
                        // lock, which is why we schedule the operation to run asynchronously: if it ran
                        // synchronously, it could deadlock due to code on another thread holding the lock
                        // and calling Dispose on the registration concurrently with the call to Cancel
                        // the cancellation token.  Dispose on the registration won't return until the action
                        // associated with the registration has completed, but if that action is currently
                        // executing and is blocked on the lock that's held while calling Dispose... deadlock.
                        var crs = new CancelableReadState(buffer, offset, count, this, cancellationToken);
                        crs._registration = cancellationToken.Register(s1 =>
                        {
                            ((CancelableReadState)s1)._stream.EventSourceTrace("Cancellation invoked. Queueing work item to cancel read state");
                            Task.Factory.StartNew(s2 =>
                            {
                                var crsRef = (CancelableReadState)s2;
                                Debug.Assert(crsRef._token.IsCancellationRequested, "We should only be here if cancellation was requested.");
                                lock (crsRef._stream._lockObject)
                                {
                                    if (crsRef._stream._pendingReadRequest == crsRef)
                                    {
                                        crsRef._stream.EventSourceTrace("Canceling");
                                        crsRef.TrySetCanceled(crsRef._token);
                                        crsRef._stream.ClearPendingReadRequest();
                                    }
                                }
                            }, s1, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default);
                        }, crs);
                        _pendingReadRequest = crs;
                    }
                    else
                    {
                        // The token isn't cancelable.  Just create a normal read state.
                        _pendingReadRequest = new ReadState(buffer, offset, count);
                    }

                    _easy._associatedMultiAgent.RequestUnpause(_easy);
                    _easy._selfStrongToWeakReference.MakeStrong(); // convert from a weak to a strong ref to keep the easy alive during the read
                    return(_pendingReadRequest.Task);
                }
            }
コード例 #38
0
 public static void ReportingCancelled(this ILog logger, OperationCanceledException ex)
 {
     logger.Error(ex, "Report execution cancelled");
 }
コード例 #39
0
        public static void AsyncMethodBuilderTCreate_SetExceptionTest()
        {
            // Creating a task builder, building it, completing it faulted, and making sure it can't be reset
            {
                var atmb = AsyncTaskMethodBuilder<int>.Create();
                var t = atmb.Task;
                Assert.True(t.Status == TaskStatus.WaitingForActivation, "    > FAILURE. Builder should still be active (ATMBT, build then fault)");
                atmb.SetException(new InvalidCastException());
                Assert.True(t.Status == TaskStatus.Faulted, "    > FAILURE. Builder should be faulted after an exception occurs (ATMBT, build then fault)");
                Assert.True(t.Exception.InnerException is InvalidCastException, "    > FAILURE. Wrong exception found in builder (ATMBT, build then fault)");
                Assert.Throws<InvalidOperationException>(
                   () => { atmb.SetResult(44); });
                Assert.Throws<InvalidOperationException>(
                   () => { atmb.SetException(new Exception()); });
            }

            // Creating a task builder, completing it faulted, building it, and making sure it can't be reset
            {
                var atmb = AsyncTaskMethodBuilder<int>.Create();
                atmb.SetException(new InvalidCastException());
                var t = atmb.Task;
                Assert.True(t.Status == TaskStatus.Faulted, "    > FAILURE. Builder should be faulted after an exception occurs (ATMBT, fault then build)");
                Assert.True(t.Exception.InnerException is InvalidCastException, "    > FAILURE. Wrong exception found in builder (ATMBT, fault then build)");
                Assert.Throws<InvalidOperationException>(
                   () => { atmb.SetResult(44); });
                Assert.Throws<InvalidOperationException>(
                   () => { atmb.SetException(new Exception()); });
            }

            // Test cancellation
            {
                var atmb = AsyncTaskMethodBuilder<int>.Create();
                var oce = new OperationCanceledException();
                atmb.SetException(oce);
                var t = atmb.Task;
                Assert.True(t.Status == TaskStatus.Canceled, "    > FAILURE. Builder should be canceled from an unhandled OCE (ATMBT cancellation)");
                try
                {
                    t.GetAwaiter().GetResult();
                    Assert.True(false, "    > FAILURE. Excepted GetResult to throw. (ATMBT cancellation)");
                }
                catch (Exception exc)
                {
                    Assert.True(Object.ReferenceEquals(oce, exc), "    > FAILURE. Excepted original OCE to be thrown. (ATMBT cancellation)");
                }
                Assert.Throws<InvalidOperationException>(
                   () => { atmb.SetResult(44); });
                Assert.Throws<InvalidOperationException>(
                   () => { atmb.SetException(new Exception()); });
            }
        }
コード例 #40
0
        internal async Task ProcessRequestAsync(HttpContextBase context)
        {
            Exception exception = _exceptionInfo.SourceException;

            Contract.Assert(exception != null);

            OperationCanceledException canceledException = exception as OperationCanceledException;

            if (canceledException != null)
            {
                // If the route throws a cancelation exception, then we'll abort the request instead of
                // reporting an 'error'. We don't expect this to happen, but aborting the request is
                // consistent with our behavior in other hosts.
                context.Request.Abort();
                return;
            }

            HttpRequestMessage  request           = context.GetOrCreateHttpRequestMessage();
            HttpResponseMessage response          = null;
            CancellationToken   cancellationToken = context.Response.GetClientDisconnectedTokenWhenFixed();

            HttpResponseException responseException = exception as HttpResponseException;

            try
            {
                if (responseException != null)
                {
                    response = responseException.Response;
                    Contract.Assert(response != null);

                    // This method call is hardened and designed not to throw exceptions (since they won't be caught
                    // and handled further by its callers).
                    await HttpControllerHandler.CopyResponseAsync(context, request, response, _exceptionLogger,
                                                                  _exceptionHandler, cancellationToken);
                }
                else
                {
                    // This method call is hardened and designed not to throw exceptions (since they won't be caught and
                    // handled further by its callers).
                    bool handled = await HttpControllerHandler.CopyErrorResponseAsync(
                        WebHostExceptionCatchBlocks.HttpWebRoute, context, request, null,
                        _exceptionInfo.SourceException, _exceptionLogger, _exceptionHandler, cancellationToken);

                    if (!handled)
                    {
                        _exceptionInfo.Throw();
                    }
                }
            }
            catch (OperationCanceledException)
            {
                // This block handles cancellations that might occur while we're writing an 'error' response.
                //
                // HttpTaskAsyncHandler treats a canceled task as an unhandled exception (logged to Application event
                // log). Instead of returning a canceled task, abort the request and return a completed task.
                context.Request.Abort();
            }
            finally
            {
                // The other HttpTaskAsyncHandler is HttpControllerHandler; it has similar cleanup logic.
                request.DisposeRequestResources();
                request.Dispose();

                if (response != null)
                {
                    response.Dispose();
                }
            }
        }
コード例 #41
0
ファイル: SQLiteDataSource.cs プロジェクト: docevaad/Chain
        /// <summary>
        /// Executes the specified operation asynchronously.
        /// </summary>
        /// <param name="executionToken"></param>
        /// <param name="implementation"></param>
        /// <param name="cancellationToken"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        protected override async Task<int?> ExecuteAsync(CommandExecutionToken<SQLiteCommand, SQLiteParameter> executionToken, CommandImplementationAsync<SQLiteCommand> implementation, CancellationToken cancellationToken, object state)
        {
            if (executionToken == null)
                throw new ArgumentNullException("executionToken", "executionToken is null.");
            if (implementation == null)
                throw new ArgumentNullException("implementation", "implementation is null.");

            var mode = DisableLocks ? LockType.None : (executionToken as SQLiteCommandExecutionToken)?.LockType ?? LockType.Write;

            var startTime = DateTimeOffset.Now;
            OnExecutionStarted(executionToken, startTime, state);

            IDisposable lockToken = null;
            try
            {
                switch (mode)
                {
                    case LockType.Read: lockToken = await SyncLock.ReaderLockAsync().ConfigureAwait(false); break;
                    case LockType.Write: lockToken = await SyncLock.WriterLockAsync().ConfigureAwait(false); break;
                }

                using (var con = await CreateConnectionAsync(cancellationToken).ConfigureAwait(false))
                {
                    using (var cmd = new SQLiteCommand())
                    {
                        cmd.Connection = con;
                        if (DefaultCommandTimeout.HasValue)
                            cmd.CommandTimeout = (int)DefaultCommandTimeout.Value.TotalSeconds;
                        cmd.CommandText = executionToken.CommandText;
                        cmd.CommandType = executionToken.CommandType;
                        foreach (var param in executionToken.Parameters)
                            cmd.Parameters.Add(param);

                        executionToken.ApplyCommandOverrides(cmd);

                        var rows = await implementation(cmd).ConfigureAwait(false);
                        executionToken.RaiseCommandExecuted(cmd, rows);
                        OnExecutionFinished(executionToken, startTime, DateTimeOffset.Now, rows, state);
                        return rows;
                    }
                }
            }
            catch (Exception ex)
            {
                if (cancellationToken.IsCancellationRequested) //convert SQLiteException into a OperationCanceledException 
                {
                    var ex2 = new OperationCanceledException("Operation was canceled.", ex, cancellationToken);
                    OnExecutionError(executionToken, startTime, DateTimeOffset.Now, ex2, state);
                    throw ex2;
                }
                else
                {
                    OnExecutionError(executionToken, startTime, DateTimeOffset.Now, ex, state);
                    throw;
                }
            }
            finally
            {
                if (lockToken != null)
                    lockToken.Dispose();
            }
        }
コード例 #42
0
        private void Poll()
        {
            // This is to ensure that we do not accidently fire off another poll after being told to stop
            lock (_stopLock)
            {
                // Only poll if we're running
                if (_running == 0)
                {
                    return;
                }                

                // A url is required
                string url = ResolveUrl();

                _httpClient.Post(url, request =>
                {
                    PrepareRequest(request);
                    _currentRequest = request;

                    // This is called just prior to posting the request to ensure that any in-flight polling request
                    // is always executed before an OnAfterPoll
                    OnPolling();
                }, isLongRunning: true)
                .ContinueWith(task =>
                {
                    var next = TaskAsyncHelper.Empty;
                    Exception exception = null;

                    if (task.IsFaulted || task.IsCanceled)
                    {
                        if (task.IsCanceled)
                        {
                            exception = new OperationCanceledException(Resources.Error_TaskCancelledException);
                        }
                        else
                        {
                            exception = task.Exception.Unwrap();
                        }

                        OnError(exception);
                    }
                    else
                    {
                        try
                        {
                            next = task.Result.ReadAsString(OnChunk).Then(raw => OnMessage(raw));
                        }
                        catch (Exception ex)
                        {
                            exception = ex;

                            OnError(exception);
                        }
                    }

                    next.Finally(state =>
                    {
                        OnAfterPoll((Exception)state).Then(() => Poll());
                    },
                    exception);
                });
            }            
        }
コード例 #43
0
 public void TryCancel(OperationCanceledException exception) {
     _createRequestTcs.TrySetCanceled(exception);
     _responseTcs.TrySetCanceled(exception);
     _cancellationTokenRegistration.Dispose();
 }
コード例 #44
0
        private void Done(IAsyncInfo info, AsyncStatus status, bool initial)
        {
            var error  = default(Exception);
            var result = default(TResult);

            //
            // Initial interactions with the IAsyncInfo object. Those could fail, which indicates
            // a rogue implementation. Failure is just propagated out.
            //
            switch (status)
            {
            case AsyncStatus.Error:
                error = info.ErrorCode;
                if (error == null)
                {
                    throw new InvalidOperationException("The asynchronous operation failed with a null error code.");
                }
                break;

            case AsyncStatus.Canceled:
                error = new OperationCanceledException();
                break;

            case AsyncStatus.Completed:
                if (_getResult != null)
                {
                    result = _getResult(info);
                }
                break;

            default:
                if (!initial)
                {
                    throw new InvalidOperationException("The asynchronous operation completed unexpectedly.");
                }

                _onCompleted(info, (iai, s) => Done(iai, s, false));
                return;
            }

            //
            // Close as early as possible, before running continuations which could fail. In case of
            // failure above, we don't close out the object in order to allow for debugging of the
            // rogue implementation without losing state prematurely. Notice _getResults is merely
            // an indirect call to the appropriate GetResults method, which is not supposed to throw.
            // Instead, an Error status should be returned.
            //
            info.Close();

            //
            // Now we run the continuations, which could take a long time. Failure here is catastrophic
            // and under control of the upstream subscriber.
            //
            if (error != null)
            {
                _subject.OnError(error);
            }
            else
            {
                if (_getResult != null)
                {
                    _subject.OnNext(result);
                }

                _subject.OnCompleted();
            }
        }
コード例 #45
0
        private void OpenConnection(IConnection connection,
                                    string data,
                                    CancellationToken disconnectToken,
                                    Action initializeCallback,
                                    Action<Exception> errorCallback)
        {
            // If we're reconnecting add /connect to the url
            bool reconnecting = initializeCallback == null;
            var callbackInvoker = new ThreadSafeInvoker();
            var requestDisposer = new Disposer();
            Action initializeInvoke = () =>
            {
                callbackInvoker.Invoke(initializeCallback);
            };
            var url = connection.Url + (reconnecting ? "reconnect" : "connect") + GetReceiveQueryString(connection, data);

            connection.Trace(TraceLevels.Events, "SSE: GET {0}", url);

            HttpClient.Get(url, req =>
            {
                _request = req;
                _request.Accept = "text/event-stream";

                connection.PrepareRequest(_request);

            }, isLongRunning: true).ContinueWith(task =>
            {
                if (task.IsFaulted || task.IsCanceled)
                {
                    Exception exception;

                    if (task.IsCanceled)
                    {
                        exception = new OperationCanceledException(Resources.Error_TaskCancelledException);
                    }
                    else
                    {
                        exception = task.Exception.Unwrap();
                    }

                    if (errorCallback != null)
                    {
                        callbackInvoker.Invoke((cb, ex) => cb(ex), errorCallback, exception);
                    }
                    else if (!_stop && reconnecting)
                    {
                        // Only raise the error event if we failed to reconnect
                        connection.OnError(exception);

                        Reconnect(connection, data, disconnectToken);
                    }
                    requestDisposer.Dispose();
                }
                else
                {
                    // If the disconnect token is canceled the response to the task doesn't matter.
                    if (disconnectToken.IsCancellationRequested)
                    {
                        return;
                    }

                    var response = task.Result;
                    Stream stream = response.GetStream();

                    var eventSource = new EventSourceStreamReader(connection, stream);

                    var esCancellationRegistration = disconnectToken.SafeRegister(state =>
                    {
                        _stop = true;

                        ((IRequest)state).Abort();
                    },
                    _request);

                    eventSource.Opened = () =>
                    {
                        // This will noop if we're not in the reconnecting state
                        if (connection.ChangeState(ConnectionState.Reconnecting, ConnectionState.Connected))
                        {
                            // Raise the reconnect event if the connection comes back up
                            connection.OnReconnected();
                        }
                    };

                    eventSource.Message = sseEvent =>
                    {
                        if (sseEvent.EventType == EventType.Data)
                        {
                            if (sseEvent.Data.Equals("initialized", StringComparison.OrdinalIgnoreCase))
                            {
                                return;
                            }

                            bool shouldReconnect;
                            bool disconnected;
                            TransportHelper.ProcessResponse(connection, sseEvent.Data, out shouldReconnect, out disconnected, initializeInvoke);

                            if (disconnected)
                            {
                                _stop = true;
                                connection.Disconnect();
                            }
                        }
                    };

                    eventSource.Closed = exception =>
                    {
                        if (exception != null)
                        {
                            // Check if the request is aborted
                            bool isRequestAborted = ExceptionHelper.IsRequestAborted(exception);

                            if (!isRequestAborted)
                            {
                                // Don't raise exceptions if the request was aborted (connection was stopped).
                                connection.OnError(exception);
                            }
                        }

                        requestDisposer.Dispose();
                        esCancellationRegistration.Dispose();
                        response.Dispose();

                        if (_stop)
                        {
                            AbortHandler.CompleteAbort();
                        }
                        else if (AbortHandler.TryCompleteAbort())
                        {
                            // Abort() was called, so don't reconnect
                        }
                        else
                        {
                            Reconnect(connection, data, disconnectToken);
                        }
                    };

                    eventSource.Start();
                }
            });

            var requestCancellationRegistration = disconnectToken.SafeRegister(state =>
            {
                if (state != null)
                {
                    // This will no-op if the request is already finished.
                    ((IRequest)state).Abort();
                }

                if (errorCallback != null)
                {
                    callbackInvoker.Invoke((cb, token) =>
                    {
#if !NET35
                        cb(new OperationCanceledException(Resources.Error_ConnectionCancelled, token));
#else
                        cb(new OperationCanceledException(Resources.Error_ConnectionCancelled));
#endif
                    }, errorCallback, disconnectToken);
                }
            }, _request);

            requestDisposer.Set(requestCancellationRegistration);
        }
コード例 #46
0
 protected override void OperationCanceled(OperationCanceledException ex)
 {
     WriteLine("Fixing was canceled.", Verbosity.Quiet);
 }
コード例 #47
0
ファイル: Connection.cs プロジェクト: hodgesz/cassandra-sharp
        public void Dispose()
        {
            lock (_globalLock)
            {
                OnFailure = null;

                // wake up clients waiting for a stream id (so they can cancel themselves)
                _cancellation.Cancel();
                Monitor.Pulse(_globalLock);

                // cancel pending readers
                Exception cancelException = new OperationCanceledException();
                for (byte idx = 0; idx < MAX_STREAMID; ++idx)
                {
                    if (!_availableStreamIds.Contains(idx))
                    {
                        _instrumentation.ClientTrace(_queryInfos[idx].InstrumentationToken, EventType.Cancellation);

                        _queryInfos[idx].Exception = cancelException;
                        _queryInfos[idx].ReadTask.RunSynchronously();
                    }
                }

                _logger.Debug("Connection to {0} is being disposed", Endpoint);
                _tcpClient.SafeDispose();
                //_cancellation.SafeDispose();
            }
        }
コード例 #48
0
 private static void HandleCanceledOperations(CancellationToken cancellationToken,
     TaskCompletionSource<HttpResponseMessage> tcs, OperationCanceledException e)
 {
     // Check if the exception was due to a cancellation. If so, check if the OperationCanceledException is 
     // related to our CancellationToken. If it was indeed caused due to our cancellation token being
     // canceled, set the Task as canceled. Set it to faulted otherwise, since the OperationCanceledException
     // is not related to our cancellation token.
     if (cancellationToken.IsCancellationRequested && (e.CancellationToken == cancellationToken))
     {
         tcs.TrySetCanceled();
     }
     else
     {
         tcs.TrySetException(e);
     }
 }
コード例 #49
0
ファイル: WinRTWebSocket.cs プロジェクト: noahfalk/corefx
        private void CancelAllOperations()
        {
            if (_receiveAsyncBufferTcs != null)
            {
                // This exception will be received by OnMessageReceived and won't be exposed
                // to user code.
                var exception = new OperationCanceledException("Aborted");
                _receiveAsyncBufferTcs.TrySetException(exception);
            }

            if (_webSocketReceiveResultTcs != null)
            {
                var exception = new WebSocketException(
                    WebSocketError.InvalidState,
                    SR.Format(
                        SR.net_WebSockets_InvalidState_ClosedOrAborted,
                        "System.Net.WebSockets.InternalClientWebSocket",
                        "Aborted"));

                _webSocketReceiveResultTcs.TrySetException(exception);
            }

            if (_closeWebSocketReceiveResultTcs != null)
            {
                var exception = new WebSocketException(
                    WebSocketError.InvalidState,
                    SR.Format(
                        SR.net_WebSockets_InvalidState_ClosedOrAborted,
                        "System.Net.WebSockets.InternalClientWebSocket",
                        "Aborted"));

                _closeWebSocketReceiveResultTcs.TrySetException(exception);
            }
        }
コード例 #50
0
        private void ResolveTransport(IConnection connection, string data, CancellationToken disconnectToken, TaskCompletionSource<object> tcs, int index)
        {
            // Pick the current transport
            IClientTransport transport = _transports[index];

            transport.Start(connection, data, disconnectToken).ContinueWith(task =>
            {
                if (task.IsFaulted || task.IsCanceled)
                {
                    Exception ex;
                    if (task.IsCanceled)
                    {
                        ex = new OperationCanceledException(Resources.Error_TaskCancelledException);
                    }
                    else
                    {
                        ex = task.Exception.GetBaseException();
                    }

                    connection.Trace(TraceLevels.Events, "Auto: Failed to connect to using transport {0}. {1}", transport.Name, ex);

                    // If that transport fails to initialize, then fallback.
                    // If it is that /start request that failed, do not fallback.
                    var next = index + 1;
                    if (next < _transports.Count && !(ex is StartException))
                    {
                        // Try the next transport
                        ResolveTransport(connection, data, disconnectToken, tcs, next);
                    }
                    else
                    {
                        // If there's nothing else to try then just fail
                        tcs.SetException(ex);
                    }
                }
                else
                {
                    // Set the active transport
                    _transport = transport;

                    // Complete the process
                    tcs.SetResult(null);
                }

            },
            TaskContinuationOptions.ExecuteSynchronously);
        }
コード例 #51
0
        /// <summary>
        /// Execute the operation asynchronously.
        /// </summary>
        /// <param name="executionToken">The execution token.</param>
        /// <param name="implementation">The implementation that handles processing the result of the command.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <param name="state">User supplied state.</param>
        /// <returns>Task.</returns>
        protected override async Task<int?> ExecuteAsync(CommandExecutionToken<OleDbCommand, OleDbParameter> executionToken, CommandImplementationAsync<OleDbCommand> implementation, CancellationToken cancellationToken, object state)
        {
            if (executionToken == null)
                throw new ArgumentNullException("executionToken", "executionToken is null.");
            if (implementation == null)
                throw new ArgumentNullException("implementation", "implementation is null.");

            var startTime = DateTimeOffset.Now;
            OnExecutionStarted(executionToken, startTime, state);

            try
            {
                using (var con = await CreateConnectionAsync(cancellationToken).ConfigureAwait(false))
                {
                    using (var cmd = new OleDbCommand())
                    {
                        cmd.Connection = con;
                        if (DefaultCommandTimeout.HasValue)
                            cmd.CommandTimeout = (int)DefaultCommandTimeout.Value.TotalSeconds;
                        cmd.CommandText = executionToken.CommandText;
                        cmd.CommandType = executionToken.CommandType;
                        foreach (var param in executionToken.Parameters)
                            cmd.Parameters.Add(param);

                        executionToken.ApplyCommandOverrides(cmd);

                        var rows = await implementation(cmd).ConfigureAwait(false);
                        executionToken.RaiseCommandExecuted(cmd, rows);
                        OnExecutionFinished(executionToken, startTime, DateTimeOffset.Now, rows, state);
                        return rows;
                    }
                }
            }
            catch (Exception ex)
            {
                if (cancellationToken.IsCancellationRequested) //convert Exception into a OperationCanceledException 
                {
                    var ex2 = new OperationCanceledException("Operation was canceled.", ex, cancellationToken);
                    OnExecutionCanceled(executionToken, startTime, DateTimeOffset.Now, state);
                    throw ex2;
                }
                else
                {
                    OnExecutionError(executionToken, startTime, DateTimeOffset.Now, ex, state);
                    throw;
                }
            }

        }
コード例 #52
0
        /// <summary>
        /// Throws the cancellation exception.
        /// </summary>
        /// <param name="url">The URL.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <param name="exception">The exception.</param>
        /// <returns>Exception.</returns>
        private Exception GetCancellationException(string url, CancellationToken cancellationToken, OperationCanceledException exception)
        {
            // If the HttpClient's timeout is reached, it will cancel the Task internally
            if (!cancellationToken.IsCancellationRequested)
            {
                var msg = string.Format("Connection to {0} timed out", url);

                _logger.Error(msg);

                // Throw an HttpException so that the caller doesn't think it was cancelled by user code
                return new HttpException(msg, exception) { IsTimedOut = true };
            }

            return exception;
        }
コード例 #53
0
ファイル: ExceptionHelpers.cs プロジェクト: justinvp/corert
        /// <summary>
        /// This does a mapping from hr to the exception and also takes care of making default exception in case of classic COM as COMException.
        /// and in winrt and marshal APIs as Exception.
        /// </summary>
        /// <param name="errorCode"></param>
        /// <param name="message"></param>
        /// <param name="createCOMException"></param>
        /// <returns></returns>
        internal static Exception GetMappingExceptionForHR(int errorCode, string message, bool createCOMException, bool hasErrorInfo)
        {
            if (errorCode >= 0)
            {
                return null;
            }

            Exception exception = null;

            bool shouldDisplayHR = false;

            switch (errorCode)
            {
                case __HResults.COR_E_NOTFINITENUMBER: // NotFiniteNumberException
                case __HResults.COR_E_ARITHMETIC:
                    exception = new ArithmeticException();
                    break;
                case __HResults.COR_E_ARGUMENT:
                case unchecked((int)0x800A01C1):
                case unchecked((int)0x800A01C2):
                case __HResults.CLR_E_BIND_UNRECOGNIZED_IDENTITY_FORMAT:
                    exception = new ArgumentException();

                    if (errorCode != __HResults.COR_E_ARGUMENT)
                        shouldDisplayHR = true;

                    break;
                case __HResults.E_BOUNDS:
                case __HResults.COR_E_ARGUMENTOUTOFRANGE:
                case __HResults.ERROR_NO_UNICODE_TRANSLATION:
                    exception = new ArgumentOutOfRangeException();

                    if (errorCode != __HResults.COR_E_ARGUMENTOUTOFRANGE)
                        shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_ARRAYTYPEMISMATCH:
                    exception = new ArrayTypeMismatchException();
                    break;
                case __HResults.COR_E_BADIMAGEFORMAT:
                case __HResults.CLDB_E_FILE_OLDVER:
                case __HResults.CLDB_E_INDEX_NOTFOUND:
                case __HResults.CLDB_E_FILE_CORRUPT:
                case __HResults.COR_E_NEWER_RUNTIME:
                case __HResults.COR_E_ASSEMBLYEXPECTED:
                case __HResults.ERROR_BAD_EXE_FORMAT:
                case __HResults.ERROR_EXE_MARKED_INVALID:
                case __HResults.CORSEC_E_INVALID_IMAGE_FORMAT:
                case __HResults.ERROR_NOACCESS:
                case __HResults.ERROR_INVALID_ORDINAL:
                case __HResults.ERROR_INVALID_DLL:
                case __HResults.ERROR_FILE_CORRUPT:
                case __HResults.COR_E_LOADING_REFERENCE_ASSEMBLY:
                case __HResults.META_E_BAD_SIGNATURE:
                    exception = new BadImageFormatException();

                    // Always show HR for BadImageFormatException
                    shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_CUSTOMATTRIBUTEFORMAT:
                    exception = new FormatException();
                    break; // CustomAttributeFormatException
                case __HResults.COR_E_DATAMISALIGNED:
                    exception = InteropExtensions.CreateDataMisalignedException(message); // TODO: Do we need to add msg here?
                    break;
                case __HResults.COR_E_DIVIDEBYZERO:
                case __HResults.CTL_E_DIVISIONBYZERO:
                    exception = new DivideByZeroException();

                    if (errorCode != __HResults.COR_E_DIVIDEBYZERO)
                        shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_DLLNOTFOUND:
#if ENABLE_WINRT
                    exception = new DllNotFoundException();
#endif
                    break;
                case __HResults.COR_E_DUPLICATEWAITOBJECT:
                    exception = new ArgumentException();
                    break; // DuplicateWaitObjectException
                case __HResults.COR_E_ENDOFSTREAM:
                case unchecked((int)0x800A003E):
                    exception = new System.IO.EndOfStreamException();

                    if (errorCode != __HResults.COR_E_ENDOFSTREAM)
                        shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_TYPEACCESS: // TypeAccessException
                case __HResults.COR_E_ENTRYPOINTNOTFOUND:
                    exception = new TypeLoadException();

                    break; // EntryPointNotFoundException
                case __HResults.COR_E_EXCEPTION:
                    exception = new Exception();
                    break;
                case __HResults.COR_E_DIRECTORYNOTFOUND:
                case __HResults.STG_E_PATHNOTFOUND:
                case __HResults.CTL_E_PATHNOTFOUND:
                    exception = new System.IO.DirectoryNotFoundException();

                    if (errorCode != __HResults.COR_E_DIRECTORYNOTFOUND)
                        shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_FILELOAD:
                case __HResults.FUSION_E_INVALID_PRIVATE_ASM_LOCATION:
                case __HResults.FUSION_E_SIGNATURE_CHECK_FAILED:
                case __HResults.FUSION_E_LOADFROM_BLOCKED:
                case __HResults.FUSION_E_CACHEFILE_FAILED:
                case __HResults.FUSION_E_ASM_MODULE_MISSING:
                case __HResults.FUSION_E_INVALID_NAME:
                case __HResults.FUSION_E_PRIVATE_ASM_DISALLOWED:
                case __HResults.FUSION_E_HOST_GAC_ASM_MISMATCH:
                case __HResults.COR_E_MODULE_HASH_CHECK_FAILED:
                case __HResults.FUSION_E_REF_DEF_MISMATCH:
                case __HResults.SECURITY_E_INCOMPATIBLE_SHARE:
                case __HResults.SECURITY_E_INCOMPATIBLE_EVIDENCE:
                case __HResults.SECURITY_E_UNVERIFIABLE:
                case __HResults.COR_E_FIXUPSINEXE:
                case __HResults.ERROR_TOO_MANY_OPEN_FILES:
                case __HResults.ERROR_SHARING_VIOLATION:
                case __HResults.ERROR_LOCK_VIOLATION:
                case __HResults.ERROR_OPEN_FAILED:
                case __HResults.ERROR_DISK_CORRUPT:
                case __HResults.ERROR_UNRECOGNIZED_VOLUME:
                case __HResults.ERROR_DLL_INIT_FAILED:
                case __HResults.FUSION_E_CODE_DOWNLOAD_DISABLED:
                case __HResults.CORSEC_E_MISSING_STRONGNAME:
                case __HResults.MSEE_E_ASSEMBLYLOADINPROGRESS:
                case __HResults.ERROR_FILE_INVALID:
                    exception = new System.IO.FileLoadException();

                    shouldDisplayHR = true;
                    break;
                case __HResults.COR_E_PATHTOOLONG:
                    exception = new System.IO.PathTooLongException();
                    break;
                case __HResults.COR_E_IO:
                case __HResults.CTL_E_DEVICEIOERROR:
                case unchecked((int)0x800A793C):
                case unchecked((int)0x800A793D):
                    exception = new System.IO.IOException();

                    if (errorCode != __HResults.COR_E_IO)
                        shouldDisplayHR = true;

                    break;
                case __HResults.ERROR_FILE_NOT_FOUND:
                case __HResults.ERROR_MOD_NOT_FOUND:
                case __HResults.ERROR_INVALID_NAME:
                case __HResults.CTL_E_FILENOTFOUND:
                case __HResults.ERROR_BAD_NET_NAME:
                case __HResults.ERROR_BAD_NETPATH:
                case __HResults.ERROR_NOT_READY:
                case __HResults.ERROR_WRONG_TARGET_NAME:
                case __HResults.INET_E_UNKNOWN_PROTOCOL:
                case __HResults.INET_E_CONNECTION_TIMEOUT:
                case __HResults.INET_E_CANNOT_CONNECT:
                case __HResults.INET_E_RESOURCE_NOT_FOUND:
                case __HResults.INET_E_OBJECT_NOT_FOUND:
                case __HResults.INET_E_DOWNLOAD_FAILURE:
                case __HResults.INET_E_DATA_NOT_AVAILABLE:
                case __HResults.ERROR_DLL_NOT_FOUND:
                case __HResults.CLR_E_BIND_ASSEMBLY_VERSION_TOO_LOW:
                case __HResults.CLR_E_BIND_ASSEMBLY_PUBLIC_KEY_MISMATCH:
                case __HResults.CLR_E_BIND_ASSEMBLY_NOT_FOUND:
                    exception = new System.IO.FileNotFoundException();

                    shouldDisplayHR = true;
                    break;
                case __HResults.COR_E_FORMAT:
                    exception = new FormatException();
                    break;
                case __HResults.COR_E_INDEXOUTOFRANGE:
                case unchecked((int)0x800a0009):
                    exception = new IndexOutOfRangeException();

                    if (errorCode != __HResults.COR_E_INDEXOUTOFRANGE)
                        shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_INVALIDCAST:
                    exception = new InvalidCastException();
                    break;
                case __HResults.COR_E_INVALIDCOMOBJECT:
                    exception = new InvalidComObjectException();
                    break;
                case __HResults.COR_E_INVALIDOLEVARIANTTYPE:
                    exception = new InvalidOleVariantTypeException();
                    break;
                case __HResults.COR_E_INVALIDOPERATION:
                case __HResults.E_ILLEGAL_STATE_CHANGE:
                case __HResults.E_ILLEGAL_METHOD_CALL:
                case __HResults.E_ILLEGAL_DELEGATE_ASSIGNMENT:
                case __HResults.APPMODEL_ERROR_NO_PACKAGE:
                    exception = new InvalidOperationException();

                    if (errorCode != __HResults.COR_E_INVALIDOPERATION)
                        shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_MARSHALDIRECTIVE:
                    exception = new MarshalDirectiveException();
                    break;
                case __HResults.COR_E_METHODACCESS: // MethodAccessException
                case __HResults.META_E_CA_FRIENDS_SN_REQUIRED: // MethodAccessException
                case __HResults.COR_E_FIELDACCESS:
                case __HResults.COR_E_MEMBERACCESS:
                    exception = new MemberAccessException();

                    if (errorCode != __HResults.COR_E_METHODACCESS)
                        shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_MISSINGFIELD: // MissingFieldException
                case __HResults.COR_E_MISSINGMETHOD: // MissingMethodException
                case __HResults.COR_E_MISSINGMEMBER:
                case unchecked((int)0x800A01CD):
                    exception = new MissingMemberException();
                    break;
                case __HResults.COR_E_MISSINGMANIFESTRESOURCE:
                    exception = new System.Resources.MissingManifestResourceException();
                    break;
                case __HResults.COR_E_NOTSUPPORTED:
                case unchecked((int)0x800A01B6):
                case unchecked((int)0x800A01BD):
                case unchecked((int)0x800A01CA):
                case unchecked((int)0x800A01CB):
                    exception = new NotSupportedException();

                    if (errorCode != __HResults.COR_E_NOTSUPPORTED)
                        shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_NULLREFERENCE:
                    exception = new NullReferenceException();
                    break;
                case __HResults.COR_E_OBJECTDISPOSED:
                case __HResults.RO_E_CLOSED:
                    // No default constructor
                    exception = new ObjectDisposedException(String.Empty);
                    break;
                case __HResults.COR_E_OPERATIONCANCELED:
#if ENABLE_WINRT
                    exception = new OperationCanceledException();
#endif
                    break;
                case __HResults.COR_E_OVERFLOW:
                case __HResults.CTL_E_OVERFLOW:
                    exception = new OverflowException();
                    break;
                case __HResults.COR_E_PLATFORMNOTSUPPORTED:
                    exception = new PlatformNotSupportedException(message);
                    break;
                case __HResults.COR_E_RANK:
                    exception = new RankException();
                    break;
                case __HResults.COR_E_REFLECTIONTYPELOAD:
#if ENABLE_WINRT
                    exception = new System.Reflection.ReflectionTypeLoadException(null, null);
#endif
                    break;
                case __HResults.COR_E_SECURITY:
                case __HResults.CORSEC_E_INVALID_STRONGNAME:
                case __HResults.CTL_E_PERMISSIONDENIED:
                case unchecked((int)0x800A01A3):
                case __HResults.CORSEC_E_INVALID_PUBLICKEY:
                case __HResults.CORSEC_E_SIGNATURE_MISMATCH:
                    exception = new System.Security.SecurityException();
                    break;
                case __HResults.COR_E_SAFEARRAYRANKMISMATCH:
                    exception = new SafeArrayRankMismatchException();
                    break;
                case __HResults.COR_E_SAFEARRAYTYPEMISMATCH:
                    exception = new SafeArrayTypeMismatchException();
                    break;
                case __HResults.COR_E_SERIALIZATION:
                    exception = new System.Runtime.Serialization.SerializationException(message);
                    break;
                case __HResults.COR_E_SYNCHRONIZATIONLOCK:
                    exception = new System.Threading.SynchronizationLockException();
                    break;
                case __HResults.COR_E_TARGETINVOCATION:
                    exception = new System.Reflection.TargetInvocationException(null);
                    break;
                case __HResults.COR_E_TARGETPARAMCOUNT:
                    exception = new System.Reflection.TargetParameterCountException();
                    break;
                case __HResults.COR_E_TYPEINITIALIZATION:
                    exception = InteropExtensions.CreateTypeInitializationException(message);
                    break;
                case __HResults.COR_E_TYPELOAD:
                case __HResults.RO_E_METADATA_NAME_NOT_FOUND:
                case __HResults.CLR_E_BIND_TYPE_NOT_FOUND:
                    exception = new TypeLoadException();

                    if (errorCode != __HResults.COR_E_TYPELOAD)
                        shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_UNAUTHORIZEDACCESS:
                case __HResults.CTL_E_PATHFILEACCESSERROR:
                case unchecked((int)0x800A014F):
                    exception = new UnauthorizedAccessException();

                    shouldDisplayHR = true;

                    break;
                case __HResults.COR_E_VERIFICATION:
                    exception = new System.Security.VerificationException();
                    break;
                case __HResults.E_NOTIMPL:
                    exception = new NotImplementedException();
                    break;
                case __HResults.E_OUTOFMEMORY:
                case __HResults.CTL_E_OUTOFMEMORY:
                case unchecked((int)0x800A7919):
                    exception = new OutOfMemoryException();

                    if (errorCode != __HResults.E_OUTOFMEMORY)
                        shouldDisplayHR = true;

                    break;
#if ENABLE_WINRT
                case __HResults.E_XAMLPARSEFAILED:
                    exception = ConstructExceptionUsingReflection(
                        "Windows.UI.Xaml.Markup.XamlParseException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0",
                        message);
                    break;
                case __HResults.E_ELEMENTNOTAVAILABLE:
                    exception = ConstructExceptionUsingReflection(
                        "Windows.UI.Xaml.Automation.ElementNotAvailableException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0",
                        message);
                    break;
                case __HResults.E_ELEMENTNOTENABLED:
                    exception = ConstructExceptionUsingReflection(
                        "Windows.UI.Xaml.Automation.ElementNotEnabledException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0", 
                        message);
                    break;
                case __HResults.E_LAYOUTCYCLE:
                    exception = ConstructExceptionUsingReflection(
                        "Windows.UI.Xaml.LayoutCycleException, System.Runtime.WindowsRuntime.UI.Xaml, Version=4.0.0.0", 
                        message);
                    break;
#endif // ENABLE_WINRT
                case __HResults.COR_E_AMBIGUOUSMATCH: // AmbiguousMatchException
                case __HResults.COR_E_APPLICATION: // ApplicationException
                case __HResults.COR_E_APPDOMAINUNLOADED: // AppDomainUnloadedException
                case __HResults.COR_E_CANNOTUNLOADAPPDOMAIN: // CannotUnloadAppDomainException
                case __HResults.COR_E_CODECONTRACTFAILED: // ContractException
                case __HResults.COR_E_CONTEXTMARSHAL: // ContextMarshalException
                case __HResults.CORSEC_E_CRYPTO: // CryptographicException
                case __HResults.CORSEC_E_CRYPTO_UNEX_OPER: // CryptographicUnexpectedOperationException
                case __HResults.COR_E_EXECUTIONENGINE: // ExecutionEngineException
                case __HResults.COR_E_INSUFFICIENTEXECUTIONSTACK: // InsufficientExecutionStackException
                case __HResults.COR_E_INVALIDFILTERCRITERIA: // InvalidFilterCriteriaException
                case __HResults.COR_E_INVALIDPROGRAM: // InvalidProgramException
                case __HResults.COR_E_MULTICASTNOTSUPPORTED: // MulticastNotSupportedException
                case __HResults.COR_E_REMOTING: // RemotingException
                case __HResults.COR_E_RUNTIMEWRAPPED: // RuntimeWrappedException
                case __HResults.COR_E_SERVER: // ServerException
                case __HResults.COR_E_STACKOVERFLOW: // StackOverflowException
                case __HResults.CTL_E_OUTOFSTACKSPACE: // StackOverflowException
                case __HResults.COR_E_SYSTEM: // SystemException
                case __HResults.COR_E_TARGET: // TargetException
                case __HResults.COR_E_THREADABORTED: // TargetException
                case __HResults.COR_E_THREADINTERRUPTED: // ThreadInterruptedException
                case __HResults.COR_E_THREADSTATE: // ThreadStateException
                case __HResults.COR_E_THREADSTART: // ThreadStartException
                case __HResults.COR_E_TYPEUNLOADED: // TypeUnloadedException
                case __HResults.CORSEC_E_POLICY_EXCEPTION: // PolicyException
                case __HResults.CORSEC_E_NO_EXEC_PERM: // PolicyException
                case __HResults.CORSEC_E_MIN_GRANT_FAIL: // PolicyException
                case __HResults.CORSEC_E_XMLSYNTAX: // XmlSyntaxException
                case __HResults.ISS_E_ALLOC_TOO_LARGE: // IsolatedStorageException
                case __HResults.ISS_E_BLOCK_SIZE_TOO_SMALL: // IsolatedStorageException
                case __HResults.ISS_E_CALLER: // IsolatedStorageException
                case __HResults.ISS_E_CORRUPTED_STORE_FILE: // IsolatedStorageException
                case __HResults.ISS_E_CREATE_DIR: // IsolatedStorageException
                case __HResults.ISS_E_CREATE_MUTEX: // IsolatedStorageException
                case __HResults.ISS_E_DEPRECATE: // IsolatedStorageException
                case __HResults.ISS_E_FILE_NOT_MAPPED: // IsolatedStorageException
                case __HResults.ISS_E_FILE_WRITE: // IsolatedStorageException
                case __HResults.ISS_E_GET_FILE_SIZE: // IsolatedStorageException
                case __HResults.ISS_E_ISOSTORE: // IsolatedStorageException
                case __HResults.ISS_E_LOCK_FAILED: // IsolatedStorageException
                case __HResults.ISS_E_MACHINE: // IsolatedStorageException
                case __HResults.ISS_E_MACHINE_DACL: // IsolatedStorageException
                case __HResults.ISS_E_MAP_VIEW_OF_FILE: // IsolatedStorageException
                case __HResults.ISS_E_OPEN_FILE_MAPPING: // IsolatedStorageException
                case __HResults.ISS_E_OPEN_STORE_FILE: // IsolatedStorageException
                case __HResults.ISS_E_PATH_LENGTH: // IsolatedStorageException
                case __HResults.ISS_E_SET_FILE_POINTER: // IsolatedStorageException
                case __HResults.ISS_E_STORE_NOT_OPEN: // IsolatedStorageException
                case __HResults.ISS_E_STORE_VERSION: // IsolatedStorageException
                case __HResults.ISS_E_TABLE_ROW_NOT_FOUND: // IsolatedStorageException
                case __HResults.ISS_E_USAGE_WILL_EXCEED_QUOTA: // IsolatedStorageException
                case __HResults.E_FAIL:
                default:
                    break;
            }

            if (exception == null)
            {
                if (createCOMException)
                {
                    exception = new COMException();
                    if (errorCode != __HResults.E_FAIL)
                        shouldDisplayHR = true;
                }
                else
                {
                    exception = new Exception();
                    if (errorCode != __HResults.COR_E_EXCEPTION)
                        shouldDisplayHR = true;
                 }
            }

            bool shouldConstructMessage = false;
            if (hasErrorInfo)
            {
                // If there is a IErrorInfo/IRestrictedErrorInfo, only construct a new error message if
                // the message is not available and do not use the shouldDisplayHR setting
                if (message == null)
                    shouldConstructMessage = true;
            }
            else
            {
                // If there is no IErrorInfo, use the shouldDisplayHR setting from the big switch/case above
                shouldConstructMessage = shouldDisplayHR;
            }

            if (shouldConstructMessage)
            {
                //
                // Append the HR into error message, just in case the app wants to look at the HR in
                // message to determine behavior.  We didn't expose HResult property until v4.5 and
                // GetHRFromException has side effects so probably Message was their only choice.
                // This behavior is probably not exactly the same as in desktop but it is fine to append
                // more message at the end. In any case, having the HR in the error message are helpful
                // to developers.
                // This makes sure:
                // 1. We always have a HR 0xNNNNNNNN in the message
                // 2. Put in a nice "Exception thrown from HRESULT" message if we can
                // 3. Wrap it in () if there is an existing message
                //

                // TODO: Add Symbolic Name into Messaage, convert 0x80020006 to DISP_E_UNKNOWNNAME
                string hrMessage = String.Format("{0} 0x{1}", SR.Excep_FromHResult, errorCode.LowLevelToString());

                message = ExternalInterop.GetMessage(errorCode);

                // Always make sure we have at least the HRESULT part in retail build or when the message
                // is empty.
                if (message == null)
                    message = hrMessage;
                else
                    message = message + " (" + hrMessage + ")";
            }

            if (message != null)
            {
                // Set message explicitly rather than calling constructor because certain ctors would append a
                // prefix to the message and that is not what we want
                InteropExtensions.SetExceptionMessage(exception, message);
            }

            InteropExtensions.SetExceptionErrorCode(exception, errorCode);

            return exception;
        }
コード例 #54
0
ファイル: CPClient.cs プロジェクト: wwj229/ScreenStreamer
            public object WaitResult(int timeout = -1, Func <bool> canceled = null)
            {
                if (disposed)
                {
                    throw new ObjectDisposedException("InvokeCommand");
                }

                Exception ex = null;

                long      msec = 0;
                Stopwatch sw   = Stopwatch.StartNew();

                bool result = false;

                do
                {
                    result = waitEvent.WaitOne(300);
                    if (result)
                    {
                        logger.Verb("Request completed");
                        break;
                    }

                    if (canceled?.Invoke() ?? false)
                    {
                        ex = new OperationCanceledException();

                        logger.Verb("Request canceled");
                        break;
                    }

                    if (timeout > 0)
                    {
                        msec = sw.ElapsedMilliseconds;
                        if (msec > timeout)
                        {
                            ex = new TimeoutException();

                            logger.Verb("Request timed out: " + msec + " " + timeout);
                            break;
                        }
                    }

                    logger.Verb("Waiting for result...");
                } while (!result);

                if (exception == null)
                {
                    exception = ex;
                }

                if (exception != null)
                {
                    throw exception;
                }

                if (response == null)
                {
                    var message = "Request dropped";
                    if (request != null)
                    {
                        message = "Request dropped: " + "\"" + request.ToString() + "\"";
                    }

                    throw new Exception(message);
                }

                return(response);
            }
コード例 #55
0
ファイル: WorkerTest.cs プロジェクト: ArsenShnurkov/BitSharp
        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);
            }
        }
コード例 #56
0
        private static void HandleOperationCanceledException(HttpActionExecutedContext ctx, OperationCanceledException e)
        {
            ctx.Response = new HttpResponseMessage
            {
                StatusCode = HttpStatusCode.RequestTimeout
            };

            Stopwatch sp = ctx.Request.Properties["timer"] as Stopwatch;

            var elapsedMilliseconds = sp == null ? -1 : sp.ElapsedMilliseconds;

            SerializeError(ctx, new
            {
                Url   = ctx.Request.RequestUri.PathAndQuery,
                Error = string.Format("Request was canceled by the server due to timeout after {0}ms", elapsedMilliseconds.ToString("#,#;;0", CultureInfo.InvariantCulture)),
                e.Message
            });
        }
コード例 #57
0
    /// <summary>
    /// execute as an asynchronous operation.
    /// </summary>
    /// <param name="executionToken">The execution token.</param>
    /// <param name="implementation">The implementation.</param>
    /// <param name="cancellationToken">The cancellation token.</param>
    /// <param name="state">The state.</param>
    /// <returns>Task.</returns>
    /// <exception cref="ArgumentNullException">
    /// executionToken;executionToken is null.
    /// or
    /// implementation;implementation is null.
    /// </exception>
    protected override async Task <int?> ExecuteAsync(CommandExecutionToken <OleDbCommand, OleDbParameter> executionToken, CommandImplementationAsync <OleDbCommand> implementation, CancellationToken cancellationToken, object?state)
    {
        if (executionToken == null)
        {
            throw new ArgumentNullException(nameof(executionToken), $"{nameof(executionToken)} is null.");
        }
        if (implementation == null)
        {
            throw new ArgumentNullException(nameof(implementation), $"{nameof(implementation)} is null.");
        }
        var currentToken = executionToken as AccessCommandExecutionToken;

        if (currentToken == null)
        {
            throw new ArgumentNullException(nameof(executionToken), "only AccessCommandExecutionToken is supported.");
        }

        var startTime = DateTimeOffset.Now;

        OnExecutionStarted(executionToken, startTime, state);

        try
        {
            int?rows = null;
            while (currentToken != null)
            {
                OnExecutionStarted(currentToken, startTime, state);
                using (var cmd = new OleDbCommand())
                {
                    cmd.Connection  = m_Connection;
                    cmd.Transaction = m_Transaction;
                    currentToken.PopulateCommand(cmd, DefaultCommandTimeout);

                    if (currentToken.ExecutionMode == AccessCommandExecutionMode.Materializer)
                    {
                        rows = await implementation(cmd).ConfigureAwait(false);
                    }
                    else if (currentToken.ExecutionMode == AccessCommandExecutionMode.ExecuteScalarAndForward)
                    {
                        if (currentToken.ForwardResult == null)
                        {
                            throw new InvalidOperationException("currentToken.ExecutionMode is ExecuteScalarAndForward, but currentToken.ForwardResult is null.");
                        }

                        currentToken.ForwardResult(await cmd.ExecuteScalarAsync().ConfigureAwait(false));
                    }
                    else
                    {
                        rows = await cmd.ExecuteNonQueryAsync().ConfigureAwait(false);
                    }
                    executionToken.RaiseCommandExecuted(cmd, rows);
                    OnExecutionFinished(currentToken, startTime, DateTimeOffset.Now, rows, state);
                }
                currentToken = currentToken.NextCommand;
            }
            return(rows);
        }
        catch (Exception ex)
        {
            if (cancellationToken.IsCancellationRequested)             //convert AccessException into a OperationCanceledException
            {
                var ex2 = new OperationCanceledException("Operation was canceled.", ex, cancellationToken);
                OnExecutionError(executionToken, startTime, DateTimeOffset.Now, ex2, state);
                throw ex2;
            }
            else
            {
                OnExecutionError(executionToken, startTime, DateTimeOffset.Now, ex, state);
                throw;
            }
        }
    }
コード例 #58
0
        /// <summary>
        /// Throws the cancellation exception.
        /// </summary>
        /// <param name="options">The options.</param>
        /// <param name="client">The client.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <param name="exception">The exception.</param>
        /// <returns>Exception.</returns>
        private Exception GetCancellationException(HttpRequestOptions options, HttpClientInfo client, CancellationToken cancellationToken, OperationCanceledException exception)
        {
            // If the HttpClient's timeout is reached, it will cancel the Task internally
            if (!cancellationToken.IsCancellationRequested)
            {
                var msg = string.Format("Connection to {0} timed out", options.Url);

                if (options.LogErrors)
                {
                    _logger.Error(msg);
                }

                client.LastTimeout = DateTime.UtcNow;

                // Throw an HttpException so that the caller doesn't think it was cancelled by user code
                return(new HttpException(msg, exception)
                {
                    IsTimedOut = true
                });
            }

            return(exception);
        }
コード例 #59
0
ファイル: HttpClientManager.cs プロジェクト: NickBolles/Emby
        /// <summary>
        /// Throws the cancellation exception.
        /// </summary>
        /// <param name="options">The options.</param>
        /// <param name="client">The client.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <param name="exception">The exception.</param>
        /// <returns>Exception.</returns>
        private Exception GetCancellationException(HttpRequestOptions options, HttpClientInfo client, CancellationToken cancellationToken, OperationCanceledException exception)
        {
            // If the HttpClient's timeout is reached, it will cancel the Task internally
            if (!cancellationToken.IsCancellationRequested)
            {
                var msg = string.Format("Connection to {0} timed out", options.Url);

                if (options.LogErrors)
                {
                    _logger.Error(msg);
                }

                client.LastTimeout = DateTime.UtcNow;

                // Throw an HttpException so that the caller doesn't think it was cancelled by user code
                return new HttpException(msg, exception)
                {
                    IsTimedOut = true
                };
            }

            return exception;
        }
コード例 #60
0
 /// <summary>
 /// Initializes a new instance of the <see cref="SpotifyHttpRequestCanceledException" /> class.
 /// </summary>
 /// <param name="operationCanceledException">The operation canceled exception.</param>
 public SpotifyHttpRequestCanceledException(OperationCanceledException operationCanceledException)
     : base("The HTTP request has been canceled from an internal cancellation token.", operationCanceledException)
 {
 }