/// <summary>
        /// Initiates an asynchronous call to the HTTP handler.
        /// </summary>
        /// <returns>
        /// An <see cref="T:System.IAsyncResult"/> that contains information about the status of the process.
        /// </returns>
        /// <param name="context">An <see cref="T:System.Web.HttpContext"/> object that provides references to intrinsic server objects (for example, Request, Response, Session, and Server) used to service HTTP requests. </param><param name="cb">The <see cref="T:System.AsyncCallback"/> to call when the asynchronous method call is complete. If <paramref name="cb"/> is null, the delegate is not called. </param><param name="extraData">Any extra data needed to process the request. </param>
        IAsyncResult IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
        {
            var asyncResult = new SimpleAsyncResult<CapacityTestData>(extraData);

            ProcessRequestAsync(context, cb, asyncResult);

            return asyncResult;
        }
        public void IsCompletedProperty() {
            // Arrange
            SimpleAsyncResult asyncResult = new SimpleAsyncResult(null);

            // Act
            bool isCompleted = asyncResult.IsCompleted;

            // Assert
            Assert.IsFalse(isCompleted, "IsCompleted should default to false.");
        }
        public void AsyncWaitHandleProperty() {
            // Arrange
            SimpleAsyncResult asyncResult = new SimpleAsyncResult(null);

            // Act
            WaitHandle asyncWaitHandle = asyncResult.AsyncWaitHandle;

            // Assert
            Assert.IsNull(asyncWaitHandle);
        }
        public void CompletedSynchronouslyProperty() {
            // Arrange
            SimpleAsyncResult asyncResult = new SimpleAsyncResult(null);

            // Act
            bool completedSynchronously = asyncResult.CompletedSynchronously;

            // Assert
            Assert.IsFalse(completedSynchronously, "CompletedSynchronously should default to false.");
        }
        public void AsyncStateProperty() {
            // Arrange
            string expected = "Hello!";
            SimpleAsyncResult asyncResult = new SimpleAsyncResult(expected);

            // Act
            object asyncState = asyncResult.AsyncState;

            // Assert
            Assert.AreEqual(expected, asyncState);
        }
        public void CompletedSynchronouslyProperty()
        {
            // Arrange
            SimpleAsyncResult asyncResult = new SimpleAsyncResult(null);

            // Act
            bool completedSynchronously = asyncResult.CompletedSynchronously;

            // Assert
            Assert.False(completedSynchronously);
        }
Beispiel #7
0
        private bool SetHeadersAsync(SimpleAsyncResult result, bool setInternalLength)
        {
            if (headersSent)
            {
                return(false);
            }

            string method         = request.Method;
            bool   no_writestream = (method == "GET" || method == "CONNECT" || method == "HEAD" || method == "TRACE");
            bool   webdav         = (method == "PROPFIND" || method == "PROPPATCH" || method == "MKCOL" || method == "COPY" || method == "MOVE" || method == "LOCK" ||
                                     method == "UNLOCK");

            if (setInternalLength && !no_writestream && writeBuffer != null)
            {
                request.InternalContentLength = writeBuffer.Length;
            }

            if (!(sendChunked || request.ContentLength > -1 || no_writestream || webdav))
            {
                return(false);
            }

            headersSent = true;
            headers     = request.GetRequestHeaders();

            var innerResult = cnc.BeginWrite(request, headers, 0, headers.Length, r =>
            {
                try
                {
                    cnc.EndWrite(request, true, r);
                    if (!initRead)
                    {
                        initRead = true;
                        WebConnection.InitRead(cnc);
                    }
                    var cl = request.ContentLength;
                    if (!sendChunked && cl == 0)
                    {
                        requestWritten = true;
                    }
                    result.SetCompleted(false);
                }
                catch (WebException e)
                {
                    result.SetCompleted(false, e);
                }
                catch (Exception e)
                {
                    result.SetCompleted(false, new WebException("Error writing headers", e, WebExceptionStatus.SendFailure));
                }
            }, null);

            return(innerResult != null);
        }
        public void IsCompletedProperty()
        {
            // Arrange
            SimpleAsyncResult asyncResult = new SimpleAsyncResult(null);

            // Act
            bool isCompleted = asyncResult.IsCompleted;

            // Assert
            Assert.False(isCompleted);
        }
        public void AsyncStateProperty()
        {
            // Arrange
            string            expected    = "Hello!";
            SimpleAsyncResult asyncResult = new SimpleAsyncResult(expected);

            // Act
            object asyncState = asyncResult.AsyncState;

            // Assert
            Assert.Equal(expected, asyncState);
        }
Beispiel #10
0
        public override object EndRunOperation(IAsyncResult result)
        {
            using (SimpleAsyncResult res = result as SimpleAsyncResult)
            {
                if (res == null)
                {
                    throw new ArgumentException("AsyncResult empty!", "result");
                }
                res.EndDisableLoadBalancing();

                return(null);
            }
        }
        public static IAsyncResult BeginSynchronous <TResult>(AsyncCallback callback, object state, Func <TResult> func, object tag)
        {
            BeginInvokeDelegate beginDelegate = delegate(AsyncCallback asyncCallback, object asyncState)
            {
                var result2 = new SimpleAsyncResult(asyncState);
                result2.MarkCompleted(true, asyncCallback);
                return(result2);
            };
            EndInvokeDelegate <TResult> endDelegate = (_ => func());
            var result = new WrappedAsyncResult <TResult>(beginDelegate, endDelegate, tag);

            result.Begin(callback, state, -1);
            return(result);
        }
        public void MarkCompleted_SynchronousCompletion() {
            // Arrange
            SimpleAsyncResult asyncResult = new SimpleAsyncResult(null);

            bool callbackWasCalled = false;
            AsyncCallback callback = ar => {
                callbackWasCalled = true;
                Assert.AreEqual(asyncResult, ar, "Wrong IAsyncResult passed to callback.");
                Assert.IsTrue(ar.IsCompleted, "IsCompleted property should have been true.");
                Assert.IsTrue(ar.CompletedSynchronously, "CompletedSynchronously property should have been true.");
            };

            // Act & assert
            asyncResult.MarkCompleted(true, callback);
            Assert.IsTrue(callbackWasCalled);
        }
Beispiel #13
0
        public static void Run(SimpleAsyncFunc func, SimpleAsyncCallback callback)
        {
            var result = new SimpleAsyncResult(callback);

            try
            {
                if (!func(result))
                {
                    result.SetCompleted(true);
                }
            }
            catch (Exception ex)
            {
                result.SetCompleted(true, ex);
            }
        }
        public IAsyncResult BeginGetCustomerDetails(int customerId, AsyncCallback callback, object state)
        {
            var asyncResult = new SimpleAsyncResult<Customer>(state);

            // mimic a long running operation
            var timer = new System.Timers.Timer(DelayMilliseconds);
            timer.Elapsed += (_, args) =>
            {
                asyncResult.Result = GetCustomer(customerId);
                asyncResult.IsCompleted = true;
                callback(asyncResult);
                timer.Enabled = false;
                timer.Close();
            };
            timer.Enabled = true;
            return asyncResult;
        }
        public void MarkCompleted_SynchronousCompletion()
        {
            // Arrange
            SimpleAsyncResult asyncResult = new SimpleAsyncResult(null);

            bool          callbackWasCalled = false;
            AsyncCallback callback          = ar => {
                callbackWasCalled = true;
                Assert.AreEqual(asyncResult, ar, "Wrong IAsyncResult passed to callback.");
                Assert.IsTrue(ar.IsCompleted, "IsCompleted property should have been true.");
                Assert.IsTrue(ar.CompletedSynchronously, "CompletedSynchronously property should have been true.");
            };

            // Act & assert
            asyncResult.MarkCompleted(true, callback);
            Assert.IsTrue(callbackWasCalled);
        }
Beispiel #16
0
        public IAsyncResult BeginGetStations(string city, AsyncCallback callback, object state)
        {
            var asyncResult = new SimpleAsyncResult <string[]>(state);

            var timer = new System.Timers.Timer(DelayMilliseconds);

            timer.Elapsed += (_, args) =>
            {
                asyncResult.Result      = GetStations(city);
                asyncResult.IsCompleted = true;
                callback(asyncResult);
                timer.Enabled = false;
                timer.Close();
            };
            timer.Enabled = true;
            return(asyncResult);
        }
        async void ProcessRequestAsync(HttpContext context, AsyncCallback cb, SimpleAsyncResult<CapacityTestData> asyncResult)
        {
            try
            {
                CapacityTestData data = await _tsService.WriteToStorageAsyncCtp();

                SyncHandler.WriteResultsToResponse(context.Response, data);

                asyncResult.Result = data;
            }
            catch (Exception ex)
            {
                asyncResult.Exception = ex;
            }

            if (cb != null) cb(asyncResult);
        }
        public IAsyncResult BeginGetCustomerDetails(int customerId, AsyncCallback callback, object state)
        {
            var asyncResult = new SimpleAsyncResult <Customer>(state);

            // mimic a long running operation
            var timer = new System.Timers.Timer(DelayMilliseconds);

            timer.Elapsed += (_, args) =>
            {
                asyncResult.Result      = GetCustomer(customerId);
                asyncResult.IsCompleted = true;
                callback(asyncResult);
                timer.Enabled = false;
                timer.Close();
            };
            timer.Enabled = true;
            return(asyncResult);
        }
        public void MarkCompleted_SynchronousCompletion()
        {
            // Arrange
            SimpleAsyncResult asyncResult = new SimpleAsyncResult(null);

            bool callbackWasCalled = false;
            AsyncCallback callback = ar =>
            {
                callbackWasCalled = true;
                Assert.Equal(asyncResult, ar);
                Assert.True(ar.IsCompleted);
                Assert.True(ar.CompletedSynchronously);
            };

            // Act & assert
            asyncResult.MarkCompleted(true, callback);
            Assert.True(callbackWasCalled);
        }
        public void MarkCompleted_SynchronousCompletion()
        {
            // Arrange
            SimpleAsyncResult asyncResult = new SimpleAsyncResult(null);

            bool          callbackWasCalled = false;
            AsyncCallback callback          = ar =>
            {
                callbackWasCalled = true;
                Assert.Equal(asyncResult, ar);
                Assert.True(ar.IsCompleted);
                Assert.True(ar.CompletedSynchronously);
            };

            // Act & assert
            asyncResult.MarkCompleted(true, callback);
            Assert.True(callbackWasCalled);
        }
Beispiel #21
0
        public IAsyncResult BeginGetNbVelibInStations(string stationsName, AsyncCallback callback, object state)
        {
            var asyncResult = new SimpleAsyncResult <List <string> >(state);

            // mimic a long running operation
            var timer = new System.Timers.Timer(DelayMilliseconds);

            timer.Elapsed += (_, args) =>
            {
                asyncResult.Result      = GetNbVelibInStations(stationsName);
                asyncResult.IsCompleted = true;
                callback(asyncResult);
                timer.Enabled = false;
                timer.Close();
            };
            timer.Enabled = true;
            return(asyncResult);
        }
Beispiel #22
0
        IAsyncResult IAsyncRelayTransport.BeginSendMessage(RelayMessage message, bool forceRoundTrip, AsyncCallback callback, object state)
        {
            var result = new SimpleAsyncResult(callback, state);

            if (forceRoundTrip)
            {
                ThreadPool.QueueUserWorkItem(o =>
                {
                    ((IRelayTransportExtended)this).SendSyncMessage(message);
                    result.SetComplete();
                });
                return(result);
            }
            ThreadPool.QueueUserWorkItem(o =>
            {
                ((IRelayTransport)this).SendMessage(message);
                result.SetComplete();
            });
            return(result);
        }
        public IAsyncResult BeginGetCustomerDetails(int customerId, AsyncCallback callback, object state)
        {
            var asyncResult = new SimpleAsyncResult<Customer>(state);

            var channelFactory = new ChannelFactory<ICustomerService>(
                new BasicHttpBinding(),
                new EndpointAddress(serviceUri));
            var customerService = channelFactory.CreateChannel();
            customerService.BeginGetCustomerDetails(customerId, serviceAsyncResult =>
            {
                try
                {
                    asyncResult.Result = customerService.EndGetCustomerDetails(serviceAsyncResult);
                }
                catch (Exception)
                {
                    asyncResult.Result = new Customer(0, "Error");
                }
                asyncResult.IsCompleted = true;
                callback(asyncResult);
            }, null);

            return asyncResult;
        }
Beispiel #24
0
        public IAsyncResult BeginInvoke(Delegate method, object[] args)
        {
            var result = new SimpleAsyncResult();

            ThreadPool.QueueUserWorkItem(
                delegate
            {
                result.AsyncWaitHandle = new ManualResetEvent(false);
                try
                {
                    result.AsyncState = Invoke(method, args);
                }
                catch (Exception exception)
                {
                    Debug.WriteLine(exception.Message);
                    Debug.WriteLine(exception.StackTrace);
                    result.Exception = exception;
                }
                result.IsCompleted = true;
            });


            return(result);
        }
Beispiel #25
0
        IAsyncResult IAsyncRelayTransport.BeginSendMessageList(List <RelayMessage> messages, AsyncCallback callback, object state)
        {
            var result = new SimpleAsyncResult(callback, state);

            if (messages.Count == 0)
            {
                result.SetComplete();
                return(result);
            }

            ThreadPool.QueueUserWorkItem(o =>
            {
                if (messages[0].IsTwoWayMessage)
                {
                    ((IRelayTransport)this).SendOutMessageList(messages);
                }
                else
                {
                    ((IRelayTransportExtended)this).SendSyncMessageList(messages);
                }
                result.SetComplete();
            });
            return(result);
        }
Beispiel #26
0
 internal void SetHeadersAsync(bool setInternalLength, SimpleAsyncCallback callback)
 {
     SimpleAsyncResult.Run(r => SetHeadersAsync(r, setInternalLength), callback);
 }
Beispiel #27
0
        internal bool WriteRequestAsync(SimpleAsyncResult result)
        {
            if (requestWritten)
            {
                return(false);
            }

            requestWritten = true;
            if (sendChunked || !allowBuffering || writeBuffer == null)
            {
                return(false);
            }

            // Keep the call for a potential side-effect of GetBuffer
            var bytes  = writeBuffer.GetBuffer();
            var length = (int)writeBuffer.Length;

            if (request.ContentLength != -1 && request.ContentLength < length)
            {
                nextReadCalled = true;
                cnc.Close(true);
                throw new WebException("Specified Content-Length is less than the number of bytes to write", null, WebExceptionStatus.ServerProtocolViolation, null);
            }

            SetHeadersAsync(true, inner =>
            {
                if (inner.GotException)
                {
                    result.SetCompleted(inner.CompletedSynchronously, inner.Exception);
                    return;
                }

                if (cnc.Data.StatusCode != 0 && cnc.Data.StatusCode != 100)
                {
                    result.SetCompleted(inner.CompletedSynchronously);
                    return;
                }

                if (!initRead)
                {
                    initRead = true;
                    WebConnection.InitRead(cnc);
                }

                if (length == 0)
                {
                    complete_request_written = true;
                    result.SetCompleted(inner.CompletedSynchronously);
                    return;
                }

                cnc.BeginWrite(request, bytes, 0, length, r =>
                {
                    try
                    {
                        complete_request_written = cnc.EndWrite(request, false, r);
                        result.SetCompleted(false);
                    }
                    catch (Exception exc)
                    {
                        result.SetCompleted(false, exc);
                    }
                }, null);
            });

            return(true);
        }
 private static IAsyncResult BeginInvokeAction_MakeSynchronousAsyncResult(AsyncCallback callback, object state)
 {
     SimpleAsyncResult simpleAsyncResult = new SimpleAsyncResult(state);
     simpleAsyncResult.MarkCompleted(true, callback);
     return simpleAsyncResult;
 }