Exemple #1
0
        public void Begin_WithCallbackSyncContext_ThrowsAsyncEvenIfSendContextCaptures()
        {
            // Arrange
            InvalidOperationException exception = new InvalidOperationException(
                "Some exception text."
                );
            CapturingSynchronizationContext capturingSyncContext =
                new CapturingSynchronizationContext();
            MockAsyncResult asyncResult = new MockAsyncResult()
            {
                CompletedSynchronously = false,
                IsCompleted            = true
            };

            using (asyncResult)
            {
                bool          originalCallbackCalled = false;
                IAsyncResult  passedAsyncResult      = null;
                AsyncCallback passedCallback         = null;
                AsyncCallback originalCallback       = ar =>
                {
                    passedAsyncResult      = ar;
                    originalCallbackCalled = true;
                    throw exception;
                };

                // Act & Assert
                IAsyncResult outerResult = AsyncResultWrapper.Begin <object>(
                    originalCallback,
                    null,
                    (callback, callbackState, state) =>
                {
                    passedCallback         = callback;
                    asyncResult.AsyncState = callbackState;
                    return(asyncResult);
                },
                    (ar, state) =>
                {
                    asyncResult.IsCompleted = true;
                    passedCallback(ar);
                },
                    null,
                    callbackSyncContext: capturingSyncContext
                    );
                SynchronousOperationException thrownException =
                    Assert.Throws <SynchronousOperationException>(
                        delegate
                {
                    AsyncResultWrapper.End(outerResult);
                },
                        @"An operation that crossed a synchronization context failed. See the inner exception for more information."
                        );

                // Assert
                Assert.Equal(exception, thrownException.InnerException);
                Assert.True(originalCallbackCalled);
                Assert.False(passedAsyncResult.CompletedSynchronously);
                Assert.True(capturingSyncContext.SendCalled);
            }
        }
Exemple #2
0
        public void Begin_AsynchronousCompletion()
        {
            // Arrange
            AsyncCallback capturedCallback      = null;
            IAsyncResult  resultGivenToCallback = null;

            using (MockAsyncResult innerResult = new MockAsyncResult())
            {
                // Act
                IAsyncResult outerResult = AsyncResultWrapper.Begin <object>(
                    ar => { resultGivenToCallback = ar; },
                    null,
                    (callback, callbackState, state) =>
                {
                    capturedCallback = callback;
                    return(innerResult);
                },
                    (ar, state) => { },
                    null);

                capturedCallback(innerResult);

                // Assert
                Assert.Equal(outerResult, resultGivenToCallback);
            }
        }
Exemple #3
0
        public void Begin_ReturnsAsyncResultWhichWrapsInnerResult()
        {
            // Arrange
            MockAsyncResult innerResult = new MockAsyncResult()
            {
                AsyncState             = "inner state",
                CompletedSynchronously = true,
                IsCompleted            = true
            };

            using (innerResult)
            {
                // Act
                IAsyncResult outerResult = AsyncResultWrapper.Begin <object>(
                    null, "outer state",
                    (callback, callbackState, state) => innerResult,
                    (ar, state) => { },
                    null);

                // Assert
                Assert.Equal(innerResult.AsyncState, outerResult.AsyncState);
                Assert.Null(outerResult.AsyncWaitHandle);
                Assert.Equal(innerResult.CompletedSynchronously, outerResult.CompletedSynchronously);
                Assert.Equal(innerResult.IsCompleted, outerResult.IsCompleted);
            }
        }
Exemple #4
0
        public void Begin_AsynchronousCompletionWithStateAndResult()
        {
            // Arrange
            using (MockAsyncResult innerResult = new MockAsyncResult())
            {
                object invokeState        = new object();
                object capturedBeginState = null;
                object capturedEndState   = null;
                object expectedRetun      = new object();

                // Act
                IAsyncResult outerResult = AsyncResultWrapper.Begin(
                    null,
                    null,
                    (AsyncCallback callback, object callbackState, object innerInvokeState) =>
                {
                    capturedBeginState = innerInvokeState;
                    return(innerResult);
                },
                    (IAsyncResult result, object innerInvokeState) =>
                {
                    capturedEndState = innerInvokeState;
                    return(expectedRetun);
                },
                    invokeState,
                    null,
                    Timeout.Infinite);
                object endResult = AsyncResultWrapper.End <object>(outerResult);

                // Assert
                Assert.Same(expectedRetun, endResult);
                Assert.Same(invokeState, capturedBeginState);
                Assert.Same(invokeState, capturedEndState);
            }
        }
Exemple #5
0
        public void TimedOut()
        {
            // Arrange
            using (ManualResetEvent waitHandle = new ManualResetEvent(false /* initialState */))
            {
                AsyncCallback callback = ar => { waitHandle.Set(); };

                // Act & assert
                using (var mockResult = new MockAsyncResult())
                {
                    IAsyncResult asyncResult = AsyncResultWrapper.Begin <object>(
                        callback, null,
                        (innerCallback, callbackState, state) => mockResult,
                        (ar, state) => { Assert.True(false, "This callback should never execute since we timed out."); },
                        null,
                        null, 0);

                    // wait for the timeout
                    waitHandle.WaitOne();

                    Assert.True(asyncResult.IsCompleted);
                    Assert.Throws <TimeoutException>(
                        delegate { AsyncResultWrapper.End(asyncResult); });
                }
            }
        }
        public void WrapCallbackForSynchronizedExecution_DoesNotCallSyncIfOperationCompletedSynchronously()
        {
            // Arrange
            MockAsyncResult asyncResult = new MockAsyncResult()
            {
                CompletedSynchronously = true,
                IsCompleted = true
            };

            bool originalCallbackCalled = false;
            AsyncCallback originalCallback = ar =>
            {
                Assert.Equal(asyncResult, ar);
                originalCallbackCalled = true;
            };

            DummySynchronizationContext syncContext = new DummySynchronizationContext();

            // Act
            AsyncCallback retVal = AsyncUtil.WrapCallbackForSynchronizedExecution(originalCallback, syncContext);
            retVal(asyncResult);

            // Assert
            Assert.True(originalCallbackCalled);
            Assert.False(syncContext.SendCalled);
        }
Exemple #7
0
        public void End_ThrowsIfAsyncResultTagMismatch()
        {
            // Arrange
            using (var mockResult = new MockAsyncResult())
            {
                IAsyncResult asyncResult = AsyncResultWrapper.Begin <object>(
                    null,
                    null,
                    (callback, callbackState, state) => mockResult,
                    (ar, state) => { },
                    null,
                    "some tag"
                    );

                // Act & assert
                Assert.Throws <ArgumentException>(
                    delegate
                {
                    AsyncResultWrapper.End(asyncResult, "some other tag");
                },
                    "The provided IAsyncResult is not valid for this method."
                    + Environment.NewLine
                    + "Parameter name: asyncResult"
                    );
            }
        }
        public void Begin_AsynchronousCompletionWithStateAndResult()
        {
            // Arrange
            IAsyncResult innerResult = new MockAsyncResult();
            object invokeState = new object();
            object capturedBeginState = null;
            object capturedEndState = null;
            object expectedRetun = new object();

            // Act
            IAsyncResult outerResult = AsyncResultWrapper.Begin(
                null,
                null,
                (AsyncCallback callback, object callbackState, object innerInvokeState) =>
                {
                    capturedBeginState = innerInvokeState;
                    return innerResult;
                },
                (IAsyncResult result, object innerInvokeState) =>
                {
                    capturedEndState = innerInvokeState;
                    return expectedRetun;
                },
                invokeState,
                null,
                Timeout.Infinite);
            object endResult = AsyncResultWrapper.End<object>(outerResult);

            // Assert
            Assert.Same(expectedRetun, endResult);
            Assert.Same(invokeState, capturedBeginState);
            Assert.Same(invokeState, capturedEndState);
        }
Exemple #9
0
        public void WrapCallbackForSynchronizedExecution_DoesNotCallSyncIfOperationCompletedSynchronously()
        {
            // Arrange
            MockAsyncResult asyncResult = new MockAsyncResult()
            {
                CompletedSynchronously = true,
                IsCompleted            = true
            };

            bool          originalCallbackCalled = false;
            AsyncCallback originalCallback       = ar =>
            {
                Assert.Equal(asyncResult, ar);
                originalCallbackCalled = true;
            };

            DummySynchronizationContext syncContext = new DummySynchronizationContext();

            // Act
            AsyncCallback retVal = AsyncUtil.WrapCallbackForSynchronizedExecution(originalCallback, syncContext);

            retVal(asyncResult);

            // Assert
            Assert.True(originalCallbackCalled);
            Assert.False(syncContext.SendCalled);
        }
        public void WaitForAsyncResultCompletion_DoesNothingIfResultAlreadyCompleted() {
            // Arrange
            MockAsyncResult asyncResult = new MockAsyncResult() {
                IsCompleted = true
            };

            // Act
            AsyncUtil.WaitForAsyncResultCompletion(asyncResult, null /* app */);

            // Assert
            // If we reached this point of execution, the operation completed
        }
Exemple #11
0
        public void Begin_WithCallbackSyncContext_ThrowsSynchronous()
        {
            // Arrange
            InvalidOperationException exception = new InvalidOperationException(
                "Some exception text."
                );
            CapturingSynchronizationContext capturingSyncContext =
                new CapturingSynchronizationContext();
            MockAsyncResult asyncResult = new MockAsyncResult()
            {
                CompletedSynchronously = true,
                IsCompleted            = true
            };

            using (asyncResult)
            {
                bool          originalCallbackCalled = false;
                IAsyncResult  passedAsyncResult      = null;
                AsyncCallback originalCallback       = ar =>
                {
                    passedAsyncResult      = ar;
                    originalCallbackCalled = true;
                    throw exception;
                };

                // Act & Assert
                InvalidOperationException thrownException =
                    Assert.Throws <InvalidOperationException>(
                        delegate
                {
                    AsyncResultWrapper.Begin <object>(
                        originalCallback,
                        null,
                        (callback, callbackState, state) =>
                    {
                        asyncResult.AsyncState = callbackState;
                        return(asyncResult);
                    },
                        (ar, state) => { },
                        null,
                        callbackSyncContext: capturingSyncContext
                        );
                },
                        exception.Message
                        );

                // Assert
                Assert.Equal(exception, thrownException);
                Assert.True(originalCallbackCalled);
                Assert.True(passedAsyncResult.CompletedSynchronously);
                Assert.False(capturingSyncContext.SendCalled);
            }
        }
Exemple #12
0
        public void Begin_WithCallbackSyncContext_CallsSendIfOperationCompletedAsynchronously()
        {
            // Arrange
            MockAsyncResult asyncResult = new MockAsyncResult()
            {
                CompletedSynchronously = false,
                IsCompleted            = false
            };

            using (asyncResult)
            {
                bool          originalCallbackCalled = false;
                IAsyncResult  passedAsyncResult      = null;
                AsyncCallback passedCallback         = null;
                AsyncCallback originalCallback       = ar =>
                {
                    originalCallbackCalled = true;
                    passedAsyncResult      = ar;
                };
                object originalState = new object();
                DummySynchronizationContext syncContext = new DummySynchronizationContext();

                // Act
                IAsyncResult outerResult = AsyncResultWrapper.Begin <object>(
                    originalCallback,
                    originalState,
                    (callback, callbackState, state) =>
                {
                    passedCallback         = callback;
                    asyncResult.AsyncState = callbackState;
                    return(asyncResult);
                },
                    (ar, state) =>
                {
                    asyncResult.IsCompleted = true;
                    passedCallback(ar);
                },
                    null,
                    callbackSyncContext: syncContext
                    );
                AsyncResultWrapper.End(outerResult);

                // Assert
                Assert.True(originalCallbackCalled);
                Assert.False(passedAsyncResult.CompletedSynchronously);
                Assert.True(passedAsyncResult.IsCompleted);
                Assert.Same(originalState, passedAsyncResult.AsyncState);
                Assert.True(syncContext.SendCalled);
            }
        }
Exemple #13
0
        public void WaitForAsyncResultCompletion_DoesNothingIfResultAlreadyCompleted()
        {
            // Arrange
            MockAsyncResult asyncResult = new MockAsyncResult()
            {
                IsCompleted = true
            };

            // Act
            AsyncUtil.WaitForAsyncResultCompletion(asyncResult, null /* app */);

            // Assert
            // If we reached this point of execution, the operation completed
        }
            public override IAsyncResult BeginExecute(ControllerContext controllerContext, IDictionary<string, object> parameters, AsyncCallback callback, object state) {
                MockAsyncResult asyncResult = new MockAsyncResult() {
                    IsCompleted = false,
                    CompletedSynchronously = false
                };

                _timer = new Timer(_ => {
                    lock (controllerContext.HttpContext.ApplicationInstance) {
                        asyncResult.IsCompleted = true;
                        asyncResult.AsyncWaitHandle.Set();
                    }
                }, null, 1000, Timeout.Infinite);

                return asyncResult;
            }
        public void InvokeActionMethodWithFilters()
        {
            // Arrange
            List <string>               actionLog         = new List <string>();
            ControllerContext           controllerContext = new ControllerContext();
            Dictionary <string, object> parameters        = new Dictionary <string, object>();
            MockAsyncResult             innerAsyncResult  = new MockAsyncResult();
            ActionResult actionResult = new ViewResult();

            ActionFilterImpl filter1 = new ActionFilterImpl()
            {
                OnActionExecutingImpl = delegate(ActionExecutingContext filterContext) {
                    actionLog.Add("OnActionExecuting1");
                },
                OnActionExecutedImpl = delegate(ActionExecutedContext filterContext) {
                    actionLog.Add("OnActionExecuted1");
                }
            };
            ActionFilterImpl filter2 = new ActionFilterImpl()
            {
                OnActionExecutingImpl = delegate(ActionExecutingContext filterContext) {
                    actionLog.Add("OnActionExecuting2");
                },
                OnActionExecutedImpl = delegate(ActionExecutedContext filterContext) {
                    actionLog.Add("OnActionExecuted2");
                }
            };

            Mock <AsyncActionDescriptor> mockActionDescriptor = new Mock <AsyncActionDescriptor>();

            mockActionDescriptor.Expect(d => d.BeginExecute(controllerContext, parameters, It.IsAny <AsyncCallback>(), It.IsAny <object>())).Returns(innerAsyncResult);
            mockActionDescriptor.Expect(d => d.EndExecute(innerAsyncResult)).Returns(actionResult);

            AsyncControllerActionInvoker invoker = new AsyncControllerActionInvoker();

            IActionFilter[] filters = new IActionFilter[] { filter1, filter2 };

            // Act
            IAsyncResult          outerAsyncResult = invoker.BeginInvokeActionMethodWithFilters(controllerContext, filters, mockActionDescriptor.Object, parameters, null, null);
            ActionExecutedContext postContext      = invoker.EndInvokeActionMethodWithFilters(outerAsyncResult);

            // Assert
            CollectionAssert.AreEqual(
                new string[] { "OnActionExecuting1", "OnActionExecuting2", "OnActionExecuted2", "OnActionExecuted1" },
                actionLog);
            Assert.AreEqual(actionResult, postContext.Result);
        }
Exemple #16
0
        public void End_ExecutesStoredDelegateAndReturnsValue()
        {
            // Arrange
            using (var mockResult = new MockAsyncResult())
            {
                IAsyncResult asyncResult = AsyncResultWrapper.Begin(
                    null, null,
                    (callback, state) => mockResult,
                    ar => 42);

                // Act
                int returned = AsyncResultWrapper.End <int>(asyncResult);

                // Assert
                Assert.Equal(42, returned);
            }
        }
Exemple #17
0
            public override IAsyncResult BeginExecute(ControllerContext controllerContext, IDictionary <string, object> parameters, AsyncCallback callback, object state)
            {
                MockAsyncResult asyncResult = new MockAsyncResult()
                {
                    IsCompleted            = false,
                    CompletedSynchronously = false
                };

                _timer = new Timer(_ => {
                    lock (controllerContext.HttpContext.ApplicationInstance) {
                        asyncResult.IsCompleted = true;
                        asyncResult.AsyncWaitHandle.Set();
                    }
                }, null, 1000, Timeout.Infinite);

                return(asyncResult);
            }
        public void Begin_SynchronousCompletion() {
            // Arrange
            IAsyncResult resultGivenToCallback = null;
            IAsyncResult innerResult = new MockAsyncResult();

            // Act
            IAsyncResult outerResult = AsyncResultWrapper.Begin(
                ar => { resultGivenToCallback = ar; },
                null,
                (callback, state) => {
                    callback(innerResult);
                    return innerResult;
                },
                ar => { });

            // Assert
            Assert.AreEqual(outerResult, resultGivenToCallback);
        }
Exemple #19
0
        public void End_ThrowsIfCalledTwiceOnSameAsyncResult()
        {
            // Arrange
            using (var mockResult = new MockAsyncResult())
            {
                IAsyncResult asyncResult = AsyncResultWrapper.Begin <object>(
                    null, null,
                    (callback, callbackState, state) => mockResult,
                    (ar, state) => { },
                    null);

                // Act & assert
                AsyncResultWrapper.End(asyncResult);
                Assert.Throws <InvalidOperationException>(
                    delegate { AsyncResultWrapper.End(asyncResult); },
                    "The provided IAsyncResult has already been consumed.");
            }
        }
        public void Begin_ReturnsAsyncResultWhichWrapsInnerResult() {
            // Arrange
            IAsyncResult innerResult = new MockAsyncResult() {
                AsyncState = "inner state",
                CompletedSynchronously = true,
                IsCompleted = true
            };

            // Act
            IAsyncResult outerResult = AsyncResultWrapper.Begin(null, "outer state",
                (callback, state) => innerResult,
                ar => { });

            // Assert
            Assert.AreEqual(innerResult.AsyncState, outerResult.AsyncState);
            Assert.AreEqual(innerResult.AsyncWaitHandle, outerResult.AsyncWaitHandle);
            Assert.AreEqual(innerResult.CompletedSynchronously, outerResult.CompletedSynchronously);
            Assert.AreEqual(innerResult.IsCompleted, outerResult.IsCompleted);
        }
        public void Begin_SynchronousCompletion()
        {
            // Arrange
            IAsyncResult resultGivenToCallback = null;
            IAsyncResult innerResult           = new MockAsyncResult();

            // Act
            IAsyncResult outerResult = AsyncResultWrapper.Begin(
                ar => { resultGivenToCallback = ar; },
                null,
                (callback, state) => {
                callback(innerResult);
                return(innerResult);
            },
                ar => { });

            // Assert
            Assert.AreEqual(outerResult, resultGivenToCallback);
        }
        public void WaitForAsyncResultCompletion_WaitsOnWaitHandleIfAvailable() {
            // Arrange
            MockAsyncResult asyncResult = new MockAsyncResult() {
                IsCompleted = false
            };
            HttpApplication app = new HttpApplication();

            Timer timer = new Timer(_ => {
                lock (app) {
                    asyncResult.IsCompleted = true;
                    asyncResult.AsyncWaitHandle.Set();
                }
            }, null, 1000, Timeout.Infinite);

            // Act
            lock (app) {
                AsyncUtil.WaitForAsyncResultCompletion(asyncResult, app);
            }
        }
        public void Begin_ReturnsAsyncResultWhichWrapsInnerResult()
        {
            // Arrange
            IAsyncResult innerResult = new MockAsyncResult()
            {
                AsyncState             = "inner state",
                CompletedSynchronously = true,
                IsCompleted            = true
            };

            // Act
            IAsyncResult outerResult = AsyncResultWrapper.Begin(null, "outer state",
                                                                (callback, state) => innerResult,
                                                                ar => { });

            // Assert
            Assert.AreEqual(innerResult.AsyncState, outerResult.AsyncState);
            Assert.AreEqual(innerResult.AsyncWaitHandle, outerResult.AsyncWaitHandle);
            Assert.AreEqual(innerResult.CompletedSynchronously, outerResult.CompletedSynchronously);
            Assert.AreEqual(innerResult.IsCompleted, outerResult.IsCompleted);
        }
        public void ExecuteCore_Asynchronous_ActionFound() {
            // Arrange
            MockAsyncResult innerAsyncResult = new MockAsyncResult();

            Mock<IAsyncActionInvoker> mockActionInvoker = new Mock<IAsyncActionInvoker>();
            mockActionInvoker.Setup(o => o.BeginInvokeAction(It.IsAny<ControllerContext>(), "SomeAction", It.IsAny<AsyncCallback>(), It.IsAny<object>())).Returns(innerAsyncResult);
            mockActionInvoker.Setup(o => o.EndInvokeAction(innerAsyncResult)).Returns(true);

            RequestContext requestContext = GetRequestContext("SomeAction");
            EmptyController controller = new EmptyController() {
                ActionInvoker = mockActionInvoker.Object
            };

            // Act & assert
            IAsyncResult outerAsyncResult = ((IAsyncController)controller).BeginExecute(requestContext, null, null);
            Assert.IsFalse(controller.TempDataSaved, "TempData shouldn't have been saved yet.");

            ((IAsyncController)controller).EndExecute(outerAsyncResult);
            Assert.IsTrue(controller.TempDataSaved);
            Assert.IsFalse(controller.HandleUnknownActionCalled);
        }
Exemple #25
0
        public void WaitForAsyncResultCompletion_WaitsOnWaitHandleIfAvailable()
        {
            // Arrange
            MockAsyncResult asyncResult = new MockAsyncResult()
            {
                IsCompleted = false
            };
            HttpApplication app = new HttpApplication();

            Timer timer = new Timer(_ => {
                lock (app) {
                    asyncResult.IsCompleted = true;
                    asyncResult.AsyncWaitHandle.Set();
                }
            }, null, 1000, Timeout.Infinite);

            // Act
            lock (app) {
                AsyncUtil.WaitForAsyncResultCompletion(asyncResult, app);
            }
        }
        public void InvokeActionMethod_AsynchronousDescriptor()
        {
            // Arrange
            ControllerContext           controllerContext = new ControllerContext();
            Dictionary <string, object> parameters        = new Dictionary <string, object>();
            IAsyncResult innerAsyncResult = new MockAsyncResult();
            ActionResult expectedResult   = new ViewResult();

            Mock <AsyncActionDescriptor> mockActionDescriptor = new Mock <AsyncActionDescriptor>();

            mockActionDescriptor.Expect(d => d.BeginExecute(controllerContext, parameters, It.IsAny <AsyncCallback>(), It.IsAny <object>())).Returns(innerAsyncResult);
            mockActionDescriptor.Expect(d => d.EndExecute(innerAsyncResult)).Returns(expectedResult);

            AsyncControllerActionInvoker invoker = new AsyncControllerActionInvoker();

            // Act
            IAsyncResult asyncResult    = invoker.BeginInvokeActionMethod(controllerContext, mockActionDescriptor.Object, parameters, null, null);
            ActionResult returnedResult = invoker.EndInvokeActionMethod(asyncResult);

            // Assert
            Assert.AreEqual(expectedResult, returnedResult);
        }
Exemple #27
0
        public void BeginInvokeActionMethodWithFilters_NormalExecutionNotCanceled()
        {
            // Arrange
            bool             onActionExecutingWasCalled = false;
            bool             onActionExecutedWasCalled  = false;
            MockAsyncResult  innerAsyncResult           = new MockAsyncResult();
            ActionFilterImpl actionFilter = new ActionFilterImpl()
            {
                OnActionExecutingImpl = _ => { onActionExecutingWasCalled = true; },
                OnActionExecutedImpl  = _ => { onActionExecutedWasCalled = true; }
            };
            Func <IAsyncResult> beginExecute = delegate
            {
                return(innerAsyncResult);
            };

            // Act
            ActionResult result = BeingInvokeActionMethodWithFiltersBeginTester(beginExecute, actionFilter);

            // Assert
            Assert.True(onActionExecutingWasCalled);
            Assert.True(onActionExecutedWasCalled);
        }
        public void Begin_AsynchronousCompletion()
        {
            // Arrange
            AsyncCallback capturedCallback = null;
            IAsyncResult resultGivenToCallback = null;
            IAsyncResult innerResult = new MockAsyncResult();

            // Act
            IAsyncResult outerResult = AsyncResultWrapper.Begin<object>(
                ar => { resultGivenToCallback = ar; },
                null,
                (callback, callbackState, state) =>
                {
                    capturedCallback = callback;
                    return innerResult;
                },
                (ar, state) => { },
                null);

            capturedCallback(innerResult);

            // Assert
            Assert.Equal(outerResult, resultGivenToCallback);
        }
        public void BeginInvokeActionMethodWithFilters_NormalExecutionNotCanceled()
        {
            // Arrange
            bool onActionExecutingWasCalled = false;
            bool onActionExecutedWasCalled = false;
            MockAsyncResult innerAsyncResult = new MockAsyncResult();
            ActionFilterImpl actionFilter = new ActionFilterImpl()
            {
                OnActionExecutingImpl = _ => { onActionExecutingWasCalled = true; },
                OnActionExecutedImpl = _ => { onActionExecutedWasCalled = true; }
            };
            Func<IAsyncResult> beginExecute = delegate
            {
                return innerAsyncResult;
            };

            // Act
            ActionResult result = BeingInvokeActionMethodWithFiltersBeginTester(beginExecute, actionFilter);

            // Assert
            Assert.True(onActionExecutingWasCalled);
            Assert.True(onActionExecutedWasCalled);
        }
        public void InvokeActionMethod_AsynchronousDescriptor()
        {
            // Arrange
            ControllerContext controllerContext = new ControllerContext();
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            IAsyncResult innerAsyncResult = new MockAsyncResult();
            ActionResult expectedResult = new ViewResult();

            Mock<AsyncActionDescriptor> mockActionDescriptor = new Mock<AsyncActionDescriptor>();
            mockActionDescriptor.Setup(d => d.BeginExecute(controllerContext, parameters, It.IsAny<AsyncCallback>(), It.IsAny<object>())).Returns(innerAsyncResult);
            mockActionDescriptor.Setup(d => d.EndExecute(innerAsyncResult)).Returns(expectedResult);

            AsyncControllerActionInvoker invoker = new AsyncControllerActionInvoker();

            // Act
            IAsyncResult asyncResult = invoker.BeginInvokeActionMethod(controllerContext, mockActionDescriptor.Object, parameters, null, null);
            ActionResult returnedResult = invoker.EndInvokeActionMethod(asyncResult);

            // Assert
            Assert.Equal(expectedResult, returnedResult);
        }
        public void InvokeActionMethodWithFilters() {
            // Arrange
            List<string> actionLog = new List<string>();
            ControllerContext controllerContext = new ControllerContext();
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            MockAsyncResult innerAsyncResult = new MockAsyncResult();
            ActionResult actionResult = new ViewResult();

            ActionFilterImpl filter1 = new ActionFilterImpl() {
                OnActionExecutingImpl = delegate(ActionExecutingContext filterContext) {
                    actionLog.Add("OnActionExecuting1");
                },
                OnActionExecutedImpl = delegate(ActionExecutedContext filterContext) {
                    actionLog.Add("OnActionExecuted1");
                }
            };
            ActionFilterImpl filter2 = new ActionFilterImpl() {
                OnActionExecutingImpl = delegate(ActionExecutingContext filterContext) {
                    actionLog.Add("OnActionExecuting2");
                },
                OnActionExecutedImpl = delegate(ActionExecutedContext filterContext) {
                    actionLog.Add("OnActionExecuted2");
                }
            };

            Mock<AsyncActionDescriptor> mockActionDescriptor = new Mock<AsyncActionDescriptor>();
            mockActionDescriptor.Expect(d => d.BeginExecute(controllerContext, parameters, It.IsAny<AsyncCallback>(), It.IsAny<object>())).Returns(innerAsyncResult);
            mockActionDescriptor.Expect(d => d.EndExecute(innerAsyncResult)).Returns(actionResult);

            AsyncControllerActionInvoker invoker = new AsyncControllerActionInvoker();
            IActionFilter[] filters = new IActionFilter[] { filter1, filter2 };

            // Act
            IAsyncResult outerAsyncResult = invoker.BeginInvokeActionMethodWithFilters(controllerContext, filters, mockActionDescriptor.Object, parameters, null, null);
            ActionExecutedContext postContext = invoker.EndInvokeActionMethodWithFilters(outerAsyncResult);

            // Assert
            CollectionAssert.AreEqual(
                new string[] { "OnActionExecuting1", "OnActionExecuting2", "OnActionExecuted2", "OnActionExecuted1" },
                actionLog);
            Assert.AreEqual(actionResult, postContext.Result);
        }
        public void Begin_WithCallbackSyncContext_ThrowsSynchronous()
        {
            // Arrange
            InvalidOperationException exception = new InvalidOperationException("Some exception text.");
            CapturingSynchronizationContext capturingSyncContext = new CapturingSynchronizationContext();
            MockAsyncResult asyncResult = new MockAsyncResult()
            {
                CompletedSynchronously = true,
                IsCompleted = true
            };

            bool originalCallbackCalled = false;
            IAsyncResult passedAsyncResult = null;
            AsyncCallback originalCallback = ar =>
            {
                passedAsyncResult = ar;
                originalCallbackCalled = true;
                throw exception;
            };

            // Act & Assert
            InvalidOperationException thrownException = Assert.Throws<InvalidOperationException>(
                delegate 
                {
                    AsyncResultWrapper.Begin<object>(
                        originalCallback,
                        null,
                        (callback, callbackState, state) =>
                        {
                            asyncResult.AsyncState = callbackState;
                            return asyncResult;
                        },
                        (ar, state) => { },
                        null,
                        callbackSyncContext: capturingSyncContext);
                },
                exception.Message);

            // Assert
            Assert.Equal(exception, thrownException);
            Assert.True(originalCallbackCalled);
            Assert.True(passedAsyncResult.CompletedSynchronously);
            Assert.False(capturingSyncContext.SendCalled);
        }
        public void ExecuteCore_Synchronous_ActionNotFound()
        {
            // Arrange
            MockAsyncResult innerAsyncResult = new MockAsyncResult();

            Mock<IActionInvoker> mockActionInvoker = new Mock<IActionInvoker>();
            mockActionInvoker.Setup(o => o.InvokeAction(It.IsAny<ControllerContext>(), "SomeAction")).Returns(false);

            RequestContext requestContext = GetRequestContext("SomeAction");
            EmptyController controller = new EmptyController()
            {
                ActionInvoker = mockActionInvoker.Object
            };

            // Act & assert
            IAsyncResult outerAsyncResult = ((IAsyncController)controller).BeginExecute(requestContext, null, null);
            Assert.False(controller.TempDataSaved);

            ((IAsyncController)controller).EndExecute(outerAsyncResult);
            Assert.True(controller.TempDataSaved);
            Assert.True(controller.HandleUnknownActionCalled);
        }
        public void ProcessRequestAsync_AsyncController_NormalExecution() {
            // Arrange
            MockAsyncResult innerAsyncResult = new MockAsyncResult();
            bool disposeWasCalled = false;

            Mock<IAsyncController> mockController = new Mock<IAsyncController>();
            mockController.Setup(o => o.BeginExecute(It.IsAny<RequestContext>(), It.IsAny<AsyncCallback>(), It.IsAny<object>())).Returns(innerAsyncResult);
            mockController.As<IDisposable>().Setup(o => o.Dispose()).Callback(delegate { disposeWasCalled = true; });

            MvcHandler handler = GetMvcHandler(mockController.Object);

            // Act & assert
            IAsyncResult outerAsyncResult = handler.BeginProcessRequest(handler.RequestContext.HttpContext, null, null);
            Assert.IsFalse(disposeWasCalled, "Dispose shouldn't have been called yet.");

            handler.EndProcessRequest(outerAsyncResult);
            Assert.IsTrue(disposeWasCalled);
            mockController.Verify(o => o.EndExecute(innerAsyncResult), Times.AtMostOnce());
        }
        public void Begin_WithCallbackSyncContext_ThrowsAsyncEvenIfSendContextCaptures()
        {
            // Arrange
            InvalidOperationException exception = new InvalidOperationException("Some exception text.");
            CapturingSynchronizationContext capturingSyncContext = new CapturingSynchronizationContext();
            MockAsyncResult asyncResult = new MockAsyncResult()
            {
                CompletedSynchronously = false,
                IsCompleted = true
            };

            bool originalCallbackCalled = false;
            IAsyncResult passedAsyncResult = null;
            AsyncCallback passedCallback = null;
            AsyncCallback originalCallback = ar =>
            {
                passedAsyncResult = ar;
                originalCallbackCalled = true;
                throw exception;
            };

            // Act & Assert
            IAsyncResult outerResult = AsyncResultWrapper.Begin<object>(
                 originalCallback,
                 null,
                 (callback, callbackState, state) =>
                 {
                     passedCallback = callback;
                     asyncResult.AsyncState = callbackState;
                     return asyncResult;
                 },
                 (ar, state) =>
                 {
                     asyncResult.IsCompleted = true;
                     passedCallback(ar);
                 },
                 null,
                 callbackSyncContext: capturingSyncContext);
            SynchronousOperationException thrownException = Assert.Throws<SynchronousOperationException>(
                delegate
                {
                    AsyncResultWrapper.End(outerResult);
                },
                @"An operation that crossed a synchronization context failed. See the inner exception for more information.");

            // Assert
            Assert.Equal(exception, thrownException.InnerException);
            Assert.True(originalCallbackCalled);
            Assert.False(passedAsyncResult.CompletedSynchronously);
            Assert.True(capturingSyncContext.SendCalled);
        }
        public void Begin_WithCallbackSyncContext_DoesNotCallSendIfOperationCompletedSynchronously()
        {
            // Arrange
            MockAsyncResult asyncResult = new MockAsyncResult()
            {
                CompletedSynchronously = true,
                IsCompleted = true
            };
            bool originalCallbackCalled = false;
            IAsyncResult passedAsyncResult = null;
            AsyncCallback originalCallback = ar =>
            {
                passedAsyncResult = ar;
                originalCallbackCalled = true;
            };
            object originalState = new object();

            DummySynchronizationContext syncContext = new DummySynchronizationContext();

            // Act
            IAsyncResult outerResult = AsyncResultWrapper.Begin<object>(
                originalCallback,
                originalState,
                (callback, callbackState, state) =>
                {
                    asyncResult.AsyncState = callbackState;
                    return asyncResult;
                },
                (ar, state) => { },
                null,
                callbackSyncContext: syncContext);

            // Assert
            Assert.True(originalCallbackCalled);
            Assert.True(passedAsyncResult.CompletedSynchronously);
            Assert.True(passedAsyncResult.IsCompleted);
            Assert.Same(originalState, passedAsyncResult.AsyncState);
            Assert.False(syncContext.SendCalled);
        }