예제 #1
0
        public void then_has_value_after_completion()
        {
            var expectedResult = 42;

            asyncResult.Complete(true, expectedResult);
            Assert.Equal(expectedResult, asyncResult.End());
        }
예제 #2
0
        public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
        {
            AsyncResult <NoResults> asyncResult = new AsyncResult <NoResults>("BufferPoolMemoryStream.Write", callback, state);

            try
            {
                this.Write(buffer, offset, count);
                asyncResult.Complete(null, true);
            }
            catch (Exception exception)
            {
                asyncResult.Complete(exception, true);
            }
            return(asyncResult);
        }
예제 #3
0
        /// <summary>
        ///     Matches a torrent based on whether the HASH('req2', SKEY) xor HASH('req3', S) matches, where SKEY is the InfoHash
        ///     of the torrent
        ///     and sets the SKEY to the InfoHash of the matched torrent.
        /// </summary>
        /// <returns>true if a match has been found</returns>
        private bool MatchSkey(IReadOnlyList <byte> torrentHash)
        {
            try
            {
                foreach (var t in _possibleSkeYs)
                {
                    var req2 = Hash(Encoding.ASCII.GetBytes("req2"), t.Hash);
                    var req3 = Hash(Encoding.ASCII.GetBytes("req3"), S);

                    var match = true;
                    for (var j = 0; j < req2.Length && match; j++)
                    {
                        match = torrentHash[j] == (req2[j] ^ req3[j]);
                    }

                    if (match)
                    {
                        Skey = t;
                        return(true);
                    }
                }
            }
            catch (Exception ex)
            {
                AsyncResult.Complete(ex);
            }
            return(false);
        }
예제 #4
0
 public when_asyncressult_completes_on_different_thread()
 {
     asyncResult = new AsyncResult <int>(ar => Thread.VolatileWrite(ref callbackWasInvoked, 1), null);
     ThreadPool.QueueUserWorkItem(_ => asyncResult.Complete(true, ExpectedResult));
     // give the thread-pool thread time to invoke the callback
     Thread.Sleep(100);
 }
예제 #5
0
        private void StepFour()
        {
            try
            {
                byte[] padD = GeneratePad();
                SelectCrypto(_b, false);
                // 4 B->A: ENCRYPT(VC, crypto_select, len(padD), padD)
                byte[] buffer = new byte[VerificationConstant.Length + CryptoSelect.Length + 2 + padD.Length];

                int offset = 0;
                offset += Message.Write(buffer, offset, VerificationConstant);
                offset += Message.Write(buffer, offset, CryptoSelect);
                offset += Message.Write(buffer, offset, Len(padD));
                offset += Message.Write(buffer, offset, padD);

                DoEncrypt(buffer, 0, buffer.Length);
                SendMessage(buffer);

                SelectCrypto(_b, true);

                Ready();
            }

            catch (Exception ex)
            {
                AsyncResult.Complete(ex);
            }
        }
예제 #6
0
        /// <summary>
        /// Matches a torrent based on whether the HASH('req2', SKEY) xor HASH('req3', S) matches, where SKEY is the InfoHash of the torrent
        /// and sets the SKEY to the InfoHash of the matched torrent.
        /// </summary>
        /// <returns>true if a match has been found</returns>
        private bool MatchSKEY(byte[] torrentHash)
        {
            try
            {
                foreach (var infoHash in _possibleSKEYs)
                {
                    byte[] req2 = Hash(Encoding.ASCII.GetBytes("req2"), infoHash.Hash);
                    byte[] req3 = Hash(Encoding.ASCII.GetBytes("req3"), S);

                    bool match = true;
                    for (int j = 0; j < req2.Length && match; j++)
                    {
                        match = torrentHash[j] == (req2[j] ^ req3[j]);
                    }

                    if (match)
                    {
                        SKEY = infoHash;
                        return(true);
                    }
                }
            }
            catch (Exception ex)
            {
                AsyncResult.Complete(ex);
            }
            return(false);
        }
        public static IAsyncResult BeginQuery(this DataContext ctx, IQueryable query,
                                              AsyncCallback callback, object state)
        {
            AsyncResult localResult = new AsyncResult();

            localResult.AsyncState = state;

            SqlCommand command = ctx.GetCommand(query) as SqlCommand;

            command.BeginExecuteReader(result =>
            {
                try
                {
                    SqlDataReader reader = command.EndExecuteReader(result);
                    localResult.Reader   = reader;
                }
                catch (Exception ex)
                {
                    // Needs to be rethrown to the caller...
                    localResult.Exception = ex;
                }
                finally
                {
                    // Need to call the caller...
                    localResult.Complete();

                    if (callback != null)
                    {
                        callback(localResult);
                    }
                }
            }, null);
            return(localResult);
        }
예제 #8
0
        public static IAsyncResult BeginReadMessage(object guidOrServer, Connection connection, AsyncCallback callback, object asyncState)
        {
            lock (_listenersLockObject)
            {
                Debug.Assert(!_listeners.ContainsKey(guidOrServer), "Handler for this guid already registered.");

                var ar = new AsyncResult(connection, callback, asyncState);

                // process pending message
                Queue <ConnectionAndMessage> queue;
                if (pendingMessages.TryGetValue(guidOrServer, out queue))
                {
                    if (queue.Count > 0)
                    {
                        var result = queue.Dequeue();
                        ar.Complete(result.Connection, result.Message);
                        return(ar);
                    }
                }

                // or start listening for incoming messages
                _listeners.Add(guidOrServer, ar);
                return(ar);
            }
        }
예제 #9
0
        /// <summary>
        /// Begins the message stream encryption handshaking process
        /// </summary>
        /// <param name="socket">The socket to perform handshaking with</param>
        public virtual IAsyncResult BeginHandshake(IConnection socket, AsyncCallback callback, object state)
        {
            if (socket == null)
            {
                throw new ArgumentNullException("socket");
            }

            if (asyncResult != null)
            {
                throw new ArgumentException("BeginHandshake has already been called");
            }

            asyncResult = new AsyncResult(callback, state);

            try
            {
                this.socket = socket;

                // Either "1 A->B: Diffie Hellman Ya, PadA" or "2 B->A: Diffie Hellman Yb, PadB"
                // These two steps will be done simultaneously to save time due to latency
                SendY();
                ReceiveY();
            }
            catch (Exception ex)
            {
                asyncResult.Complete(ex);
            }
            return(asyncResult);
        }
예제 #10
0
        public IAsyncResult BeginConnect(AsyncCallback callback, object state)
        {
            AsyncResult result = new AsyncResult(callback, state);

            result.Complete();
            return(result);
        }
 public when_asyncressult_completes_on_different_thread()
 {
     asyncResult = new AsyncResult<int>(ar => Thread.VolatileWrite(ref callbackWasInvoked, 1), null);
     ThreadPool.QueueUserWorkItem(_ => asyncResult.Complete(true, ExpectedResult));
     // give the thread-pool thread time to invoke the callback
     Thread.Sleep(100);
 }
예제 #12
0
        internal static void ReceiveMessage(IAsyncResult ar)
        {
            Message    m          = null;
            Connection connection = null;

            try
            {
                m = Message.EndReceive(out connection, ar);
            }
            catch (MessageException e)
            {
                TriggerException(e);
                return;
            }

            lock (_listenersLockObject)
            {
                if (!_listeners.ContainsKey(m.Guid))
                {
                    // New incoming message
                    if (_listeners.ContainsKey(connection.LocalChannelID))
                    {
                        AsyncResult myAr = _listeners[connection.LocalChannelID];
                        _listeners.Remove(connection.LocalChannelID);
                        myAr.Complete(connection, m);
                    }
                    else if (_listeners.ContainsKey(connection.LocalAddress))
                    {
                        AsyncResult myAr = _listeners[connection.LocalAddress];
                        _listeners.Remove(connection.LocalAddress);
                        myAr.Complete(connection, m);
                    }
                    else
                    {
                        // add incoming message to the pending messages
                        var key = connection.LocalChannelID;
                        Queue <ConnectionAndMessage> queue;
                        if (!pendingMessages.TryGetValue(key, out queue))
                        {
                            queue = new Queue <ConnectionAndMessage>();
                            pendingMessages.Add(key, queue);
                        }

                        queue.Enqueue(new ConnectionAndMessage
                        {
                            Connection = connection,
                            Message    = m
                        });
                    }
                }
                else
                {
                    // Response to previous message
                    AsyncResult myAr = _listeners[m.Guid];
                    _listeners.Remove(m.Guid);
                    myAr.Complete(connection, m);
                }
            }
        }
            // Asynchronous version of time-consuming method (private part
            // to set completion result/exception)
            private void DoTaskHelper(Object asyncResult)
            {
                // We know that it's really an AsyncResult<DateTime> object
                AsyncResult <DateTime> ar = (AsyncResult <DateTime>)asyncResult;

                try
                {
                    // Perform the operation; if sucessful set the result
                    DateTime dt = DoTask();
                    ar.Complete(false, dt);
                }
                catch (Exception e)
                {
                    // If operation fails, set the exception
                    ar.Complete(false, e);
                }
            }
예제 #14
0
        public override IAsyncResult BeginGetExternalIP(AsyncCallback callback, object asyncState)
        {
            StartOp(ref externalIpResult, callback, asyncState);
            AsyncResult result = externalIpResult;

            result.Complete();
            return(result);
        }
예제 #15
0
 private void gotInitialPayload(IAsyncResult result)
 {
     try
     {
         DoDecrypt(RemoteInitialPayload, 0, RemoteInitialPayload.Length); // ... ENCRYPT(IA)
         StepFour();
     }
     catch (Exception ex)
     {
         AsyncResult.Complete(ex);
     }
 }
예제 #16
0
        internal static void ReceiveMessage(IAsyncResult ar)
        {
            Message    m          = null;
            Connection connection = null;

            try
            {
                m = Message.EndReceive(out connection, ar);
            }
            catch (MessageException e)
            {
                TriggerException(e);
                return;
            }

            lock (_listenersLockObject)
            {
                if (!_listeners.Contains(m.Guid))
                {
                    // New incoming message
                    if (_listeners.Contains(connection.LocalChannelID))
                    {
                        AsyncResult myAr = (AsyncResult)_listeners[connection.LocalChannelID];
                        _listeners.Remove(connection.LocalChannelID);
                        myAr.Complete(connection, m);
                    }
                    else if (_listeners.Contains(connection.LocalAddress))
                    {
                        AsyncResult myAr = (AsyncResult)_listeners[connection.LocalAddress];
                        _listeners.Remove(connection.LocalAddress);
                        myAr.Complete(connection, m);
                    }
                    else
                    {
                        Stack outstanding = (Stack)outstandingMessages[connection.LocalAddress];
                        if (outstanding == null)
                        {
                            outstanding = new Stack();
                            outstandingMessages.Add(connection.LocalAddress, outstanding);
                        }
                        outstanding.Push(new Object[] { connection, m });
                    }
                }
                else
                {
                    // Response to previous message
                    AsyncResult myAr = (AsyncResult)_listeners[m.Guid];
                    _listeners.Remove(m.Guid);
                    myAr.Complete(connection, m);
                }
            }
        }
예제 #17
0
 private void GotPadD(IAsyncResult result)
 {
     try
     {
         DoDecrypt(PadD, 0, PadD.Length); // padD
         SelectCrypto(_b, true);
         Ready();
     }
     catch (Exception ex)
     {
         AsyncResult.Complete(ex);
     }
 }
예제 #18
0
        protected override void doneReceiveY()
        {
            try
            {
                base.doneReceiveY(); // 2 B->A: Diffie Hellman Yb, PadB

                StepThree();
            }
            catch (Exception ex)
            {
                AsyncResult.Complete(ex);
            }
        }
예제 #19
0
 /// <summary>
 /// Called when the Socket has finished talking to the proxy server and is ready to relay data.
 /// </summary>
 /// <param name="error">The error to throw when the EndConnect method is called.</param>
 private void OnHandShakeComplete(Exception error)
 {
     if (error != null)
     {
         Close();
     }
     ToThrow = error;
     AsyncResult.Complete(error);
     if (CallBack != null)
     {
         CallBack(AsyncResult);
     }
 }
예제 #20
0
        protected override void DoneSynchronize()
        {
            try
            {
                base.DoneSynchronize(); // 4 B->A: ENCRYPT(VC, ...

                _verifyBytes = new byte[4 + 2];
                ReceiveMessage(_verifyBytes, _verifyBytes.Length, _gotVerificationCallback); // crypto_select, len(padD) ...
            }
            catch (Exception ex)
            {
                AsyncResult.Complete(ex);
            }
        }
예제 #21
0
        protected override void doneReceiveY()
        {
            try
            {
                base.doneReceiveY(); // 1 A->B: Diffie Hellman Ya, PadA

                byte[] req1 = Hash(Encoding.ASCII.GetBytes("req1"), S);
                Synchronize(req1, 628); // 3 A->B: HASH('req1', S)
            }
            catch (Exception ex)
            {
                AsyncResult.Complete(ex);
            }
        }
예제 #22
0
        private void StepThree()
        {
            try
            {
                CreateCryptors("keyA", "keyB");

                // 3 A->B: HASH('req1', S)
                byte[] req1 = Hash(Encoding.ASCII.GetBytes("req1"), S);

                // ... HASH('req2', SKEY)
                byte[] req2 = Hash(Encoding.ASCII.GetBytes("req2"), SKEY.Hash);

                // ... HASH('req3', S)
                byte[] req3 = Hash(Encoding.ASCII.GetBytes("req3"), S);

                // HASH('req2', SKEY) xor HASH('req3', S)
                for (int i = 0; i < req2.Length; i++)
                {
                    req2[i] ^= req3[i];
                }

                byte[] padC = GeneratePad();

                // 3 A->B: HASH('req1', S), HASH('req2', SKEY) xor HASH('req3', S), ENCRYPT(VC, crypto_provide, len(PadC), ...
                byte[] buffer = new byte[req1.Length + req2.Length + VerificationConstant.Length + CryptoProvide.Length
                                         + 2 + padC.Length + 2 + InitialPayload.Length];

                int offset = 0;
                offset += Message.Write(buffer, offset, req1);
                offset += Message.Write(buffer, offset, req2);
                offset += Message.Write(buffer, offset, DoEncrypt(VerificationConstant));
                offset += Message.Write(buffer, offset, DoEncrypt(CryptoProvide));
                offset += Message.Write(buffer, offset, DoEncrypt(Len(padC)));
                offset += Message.Write(buffer, offset, DoEncrypt(padC));

                // ... PadC, len(IA)), ENCRYPT(IA)
                offset += Message.Write(buffer, offset, DoEncrypt(Len(InitialPayload)));
                offset += Message.Write(buffer, offset, DoEncrypt(InitialPayload));

                // Send the entire message in one go
                SendMessage(buffer);
                InitialPayload = BufferManager.EmptyBuffer;

                Synchronize(DoDecrypt(VerificationConstant), 616); // 4 B->A: ENCRYPT(VC)
            }
            catch (Exception ex)
            {
                AsyncResult.Complete(ex);
            }
        }
예제 #23
0
        protected override void DoneSynchronize()
        {
            try
            {
                base.DoneSynchronize();

                _verifyBytes = new byte[20 + VerificationConstant.Length + 4 + 2];
                // ... HASH('req2', SKEY) xor HASH('req3', S), ENCRYPT(VC, crypto_provide, len(PadC), PadC, len(IA))

                ReceiveMessage(_verifyBytes, _verifyBytes.Length, _gotVerificationCallback);
            }
            catch (Exception ex)
            {
                AsyncResult.Complete(ex);
            }
        }
예제 #24
0
        private void gotPadC(IAsyncResult result)
        {
            try
            {
                DoDecrypt(PadC, 0, PadC.Length);

                byte[] lenInitialPayload = new byte[2]; // ... len(IA))
                Array.Copy(PadC, PadC.Length - 2, lenInitialPayload, 0, 2);

                RemoteInitialPayload = new byte[DeLen(lenInitialPayload)]; // ... ENCRYPT(IA)
                ReceiveMessage(RemoteInitialPayload, RemoteInitialPayload.Length, gotInitialPayload);
            }
            catch (Exception ex)
            {
                AsyncResult.Complete(ex);
            }
        }
예제 #25
0
        public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, long?crc, AsyncCallback callback, object state)
        {
            Exception exception = null;

            try
            {
                this.UpdateDataCrc(buffer, offset, count, crc);
                this.Write(buffer, offset, count);
            }
            catch (Exception exception1)
            {
                exception = exception1;
            }
            AsyncResult <NoResults> asyncResult = new AsyncResult <NoResults>("CrcMemoryStream.BeginWrite", callback, state);

            asyncResult.Complete(exception, true);
            return(asyncResult);
        }
예제 #26
0
        private void GotVerification(IAsyncResult result)
        {
            try
            {
                var torrentHash = new byte[20];

                var myVc    = new byte[8];
                var myCp    = new byte[4];
                var lenPadC = new byte[2];

                Array.Copy(_verifyBytes, 0, torrentHash, 0, torrentHash.Length);
                // HASH('req2', SKEY) xor HASH('req3', S)

                if (!MatchSkey(torrentHash))
                {
                    AsyncResult.Complete(new EncryptionException("No valid SKey found"));
                    return;
                }

                CreateCryptors("keyB", "keyA");

                DoDecrypt(_verifyBytes, 20, 14); // ENCRYPT(VC, ...

                Array.Copy(_verifyBytes, 20, myVc, 0, myVc.Length);
                if (!Toolbox.ByteMatch(myVc, VerificationConstant))
                {
                    AsyncResult.Complete(new EncryptionException("Verification constant was invalid"));
                    return;
                }

                Array.Copy(_verifyBytes, 28, myCp, 0, myCp.Length); // ...crypto_provide ...

                // We need to select the crypto *after* we send our response, otherwise the wrong
                // encryption will be used on the response
                _b = myCp;
                Array.Copy(_verifyBytes, 32, lenPadC, 0, lenPadC.Length); // ... len(padC) ...
                PadC = new byte[DeLen(lenPadC) + 2];
                ReceiveMessage(PadC, PadC.Length, _gotPadCCallback);      // padC
            }
            catch (Exception ex)
            {
                AsyncResult.Complete(ex);
            }
        }
            public IAsyncResult BeginExecuteReader(AsyncCallback callback)
            {
                AsyncResult <IDataReader> asyncResult = new AsyncResult <IDataReader>(callback, this);

                Task.Factory.StartNew(() =>
                {
                    try
                    {
                        IDataReader dataReader = _command.ExecuteReader();
                        asyncResult.Complete(dataReader, false);
                    }
                    catch (Exception exc)
                    {
                        asyncResult.HandleException(exc, false);
                    }
                });

                return(asyncResult);
            }
예제 #28
0
 public void TestCallback()
 {
     AsyncResult result;
      Boolean called;
      // callback with null state
      called = false;
      result = new AsyncResult(
     ar =>
     {
        Assert.IsNull(ar.AsyncState);
        Assert.IsFalse(ar.CompletedSynchronously);
        Assert.IsTrue(ar.IsCompleted);
        Assert.IsTrue(ar.AsyncWaitHandle.WaitOne(0));
        called = true;
     },
     null
      );
      Assert.IsNull(result.AsyncState);
      Assert.IsFalse(result.IsCompleted);
      Assert.IsFalse(called);
      result.Complete(null);
      Assert.IsTrue(called);
      // callback with valid state
      called = false;
      result = new AsyncResult(
     ar =>
     {
        Assert.AreEqual(ar.AsyncState, 1);
        Assert.IsFalse(ar.CompletedSynchronously);
        Assert.IsTrue(ar.IsCompleted);
        Assert.IsTrue(ar.AsyncWaitHandle.WaitOne(0));
        called = true;
     },
     1
      );
      Assert.AreEqual(result.AsyncState, 1);
      Assert.IsFalse(result.IsCompleted);
      Assert.IsFalse(called);
      result.Complete(null);
      Assert.IsTrue(called);
 }
예제 #29
0
        public static IAsyncResult BeginReadMessage(object guidOrServer, Connection connection, AsyncCallback callback, object asyncState)
        {
            lock (_listenersLockObject)
            {
                Debug.Assert(!_listeners.Contains(guidOrServer), "Handler for this guid already registered.");

                AsyncResult ar = new AsyncResult(connection, callback, asyncState);
                if (outstandingMessages.Contains(guidOrServer))
                {
                    Stack outstanding = (Stack)outstandingMessages[guidOrServer];
                    if (outstanding.Count > 0)
                    {
                        object[] result = (object[])outstanding.Pop();
                        ar.Complete((Connection)result[0], (Message)result[1]);
                        return(ar);
                    }
                }
                _listeners.Add(guidOrServer, ar);
                return(ar);
            }
        }
예제 #30
0
        /// <summary>
        /// Read data from the socket until the byte string in syncData is read, or until syncStopPoint
        /// is reached (in that case, there is an EncryptionError).
        /// (Either "3 A->B: HASH('req1', S)" or "4 B->A: ENCRYPT(VC)")
        /// </summary>
        /// <param name="syncData">Buffer with the data to synchronize to</param>
        /// <param name="syncStopPoint">Maximum number of bytes (measured from the total received from the socket since connection) to read before giving up</param>
        protected void Synchronize(byte[] syncData, int syncStopPoint)
        {
            try
            {
                // The strategy here is to create a window the size of the data to synchronize and just refill that until its contents match syncData
                synchronizeData    = syncData;
                synchronizeWindow  = new byte[syncData.Length];
                this.syncStopPoint = syncStopPoint;

                if (bytesReceived > syncStopPoint)
                {
                    asyncResult.Complete(new EncryptionException("Couldn't synchronise 1"));
                }
                else
                {
                    NetworkIO.EnqueueReceive(socket, synchronizeWindow, 0, synchronizeWindow.Length, null, null, null, fillSynchronizeBytesCallback, 0);
                }
            }
            catch (Exception ex)
            {
                asyncResult.Complete(ex);
            }
        }
예제 #31
0
        public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
        {
            AsyncResult <AsyncHelper.Tuple <int, long?> > asyncResult = new AsyncResult <AsyncHelper.Tuple <int, long?> >("CrcMemoryStream.BeginRead", callback, state);
            Exception exception = null;

            try
            {
                int  num      = this.memoryStream.Read(buffer, offset, count);
                long?nullable = null;
                if (this.DataCrc.HasValue && num > 0)
                {
                    nullable = ((long)num != this.Length ? new long?(this.CalculatePartialDataCrc(this.Position - (long)num, num)) : this.DataCrc);
                }
                asyncResult.ResultData = new AsyncHelper.Tuple <int, long?>(num, nullable);
            }
            catch (Exception exception1)
            {
                exception = exception1;
            }
            asyncResult.Complete(exception, true);
            return(asyncResult);
        }
예제 #32
0
        static void TriggerException(MessageException e)
        {
            lock (_listenersLockObject)
            {
                ArrayList toBeDeleted = new ArrayList();

                foreach (object key in _listeners.Keys)
                {
                    AsyncResult myAr = _listeners[key];
                    if (myAr != null && myAr.Connection == e.Connection)
                    {
                        myAr.Complete(e);
                        toBeDeleted.Add(key);
                    }
                }
                foreach (object o in toBeDeleted)
                {
                    _listeners.Remove(o);
                }
            }
            e.Connection.Close();
        }
예제 #33
0
 public void TestCompletion()
 {
     AsyncResult result;
      // default completion
      result = new AsyncResult(null, null);
      Assert.IsFalse(result.CompletedSynchronously);
      Assert.IsFalse(result.IsCompleted);
      Assert.IsFalse(result.AsyncWaitHandle.WaitOne(0));
      Assert.IsFalse(result.AsyncWaitHandle.WaitOne(1));
      result.Complete(null);
      Assert.IsFalse(result.CompletedSynchronously);
      Assert.IsTrue(result.IsCompleted);
      Assert.IsTrue(result.AsyncWaitHandle.WaitOne(0));
      Assert.IsTrue(result.AsyncWaitHandle.WaitOne(1));
      // completion with callback
      result = new AsyncResult(o => { }, null);
      Assert.IsFalse(result.CompletedSynchronously);
      Assert.IsFalse(result.IsCompleted);
      Assert.IsFalse(result.AsyncWaitHandle.WaitOne(0));
      Assert.IsFalse(result.AsyncWaitHandle.WaitOne(1));
      result.Complete(null);
      Assert.IsFalse(result.CompletedSynchronously);
      Assert.IsTrue(result.IsCompleted);
      Assert.IsTrue(result.AsyncWaitHandle.WaitOne(0));
      Assert.IsTrue(result.AsyncWaitHandle.WaitOne(1));
      // completion with callback/state
      result = new AsyncResult(o => { }, 1);
      Assert.IsFalse(result.CompletedSynchronously);
      Assert.IsFalse(result.IsCompleted);
      Assert.IsFalse(result.AsyncWaitHandle.WaitOne(0));
      Assert.IsFalse(result.AsyncWaitHandle.WaitOne(1));
      result.Complete(null);
      Assert.IsFalse(result.CompletedSynchronously);
      Assert.IsTrue(result.IsCompleted);
      Assert.IsTrue(result.AsyncWaitHandle.WaitOne(0));
      Assert.IsTrue(result.AsyncWaitHandle.WaitOne(1));
      // completion with exception
      result = new AsyncResult(o => { }, 1);
      Assert.IsFalse(result.CompletedSynchronously);
      Assert.IsFalse(result.IsCompleted);
      Assert.IsFalse(result.AsyncWaitHandle.WaitOne(0));
      Assert.IsFalse(result.AsyncWaitHandle.WaitOne(1));
      result.Complete(null, new Exception("exception"));
      Assert.IsFalse(result.CompletedSynchronously);
      Assert.IsTrue(result.IsCompleted);
      Assert.IsTrue(result.AsyncWaitHandle.WaitOne(0));
      Assert.IsTrue(result.AsyncWaitHandle.WaitOne(1));
      // multiple completion
      result = new AsyncResult(o => { }, 1);
      result.Complete(null, new Exception("exception"));
      Assert.IsFalse(result.CompletedSynchronously);
      Assert.IsTrue(result.IsCompleted);
      Assert.IsTrue(result.AsyncWaitHandle.WaitOne(0));
      Assert.IsTrue(result.AsyncWaitHandle.WaitOne(1));
      try
      {
     result.Complete(null);
     Assert.Fail("Exception expected");
      }
      catch (AssertFailedException) { throw; }
      catch { }
 }
예제 #34
0
 public void TestState()
 {
     AsyncResult result;
      // null state
      result = new AsyncResult(null, null);
      Assert.IsNull(result.AsyncState);
      Assert.IsFalse(result.IsCompleted);
      result.Complete(null);
      Assert.IsNull(result.AsyncState);
      Assert.IsTrue(result.IsCompleted);
      // valid state
      result = new AsyncResult(null, 1);
      Assert.AreEqual(result.AsyncState, 1);
      Assert.IsFalse(result.IsCompleted);
      result.Complete(null);
      Assert.AreEqual(result.AsyncState, 1);
      Assert.IsTrue(result.IsCompleted);
      // callback + state
      result = new AsyncResult(o => { }, 2);
      Assert.AreEqual(result.AsyncState, 2);
      Assert.IsFalse(result.IsCompleted);
      result.Complete(null);
      Assert.AreEqual(result.AsyncState, 2);
      Assert.IsTrue(result.IsCompleted);
 }
예제 #35
0
 private void JobFinished(AsyncResult<IOutput> jar, IOutput outp)
 {
     try
     {
         FreeStreamId(jar.StreamId);
     }
     finally
     {
         jar.SetResult(outp);
         jar.Complete();
         (outp as IWaitableForDispose).WaitForDispose();
     }
 }
예제 #36
0
 public void TestWait()
 {
     AsyncResult result;
      // default timeout
      result = new AsyncResult(null, null);
      Assert.AreEqual(result.Timeout, TimeSpan.MaxValue);
      Assert.IsFalse(result.TryWaitFor(TimeSpan.Zero));
      Assert.IsFalse(result.TryWaitFor(TimeSpan.FromMilliseconds(1)));
      try
      {
     result.WaitFor(TimeSpan.Zero);
     Assert.Fail("TimeoutException expected");
      }
      catch (TimeoutException) { }
      try
      {
     result.WaitFor(TimeSpan.FromMilliseconds(1));
     Assert.Fail("TimeoutException expected");
      }
      catch (TimeoutException) { }
      result.Complete("complete", new Exception("exception"));
      Assert.IsTrue(result.TryWaitFor(TimeSpan.Zero));
      Assert.IsTrue(result.TryWaitFor(TimeSpan.MaxValue));
      result.WaitFor();
      result.WaitFor(TimeSpan.Zero);
      result.WaitFor(TimeSpan.MaxValue);
      // valid timeout
      result = new AsyncResult(null, null, TimeSpan.FromMilliseconds(10));
      Assert.AreEqual(result.Timeout, TimeSpan.FromMilliseconds(10));
      Assert.IsFalse(result.TryWaitFor(TimeSpan.Zero));
      Assert.IsFalse(result.TryWaitFor(TimeSpan.FromMilliseconds(1)));
      try
      {
     result.WaitFor(TimeSpan.Zero);
     Assert.Fail("TimeoutException expected");
      }
      catch (TimeoutException) { }
      try
      {
     result.WaitFor(TimeSpan.FromMilliseconds(1));
     Assert.Fail("TimeoutException expected");
      }
      catch (TimeoutException) { }
      try
      {
     result.WaitFor();
     Assert.Fail("TimeoutException expected");
      }
      catch (TimeoutException) { }
      result.Complete("complete", new Exception("exception"));
      Assert.IsTrue(result.TryWaitFor(TimeSpan.Zero));
      Assert.IsTrue(result.TryWaitFor(TimeSpan.MaxValue));
      result.WaitFor();
      result.WaitFor(TimeSpan.Zero);
      result.WaitFor(TimeSpan.MaxValue);
 }
예제 #37
0
        void BeginSendMessage(string msg, int i, AsyncResult rar)
        {
            try
            {
                _jc.BeginSendMessage(_to[i], msg, ar =>
                {
                    try
                    {
                        _jc.EndSendMessage(ar);
                    }
                    catch (Exception ex)
                    {
                        rar.Complete(i == 0, ex);
                        return;
                    }

                    if (++i >= _to.Length)
                    {
                        rar.Complete(false);
                    }
                    else
                    {
                        BeginSendMessage(msg, i, rar);
                    }
                },
                null);
            }
            catch (Exception ex)
            {
                rar.Complete(i == 0, ex);
            }
        }
예제 #38
0
 public IAsyncResult BeginConnect(AsyncCallback callback, object state)
 {
     var result = new AsyncResult(callback, state);
     result.Complete();
     return result;
 }
예제 #39
0
        /// <summary>
        ///     Begins the message stream encryption handshaking process
        /// </summary>
        /// <param name="socket">The socket to perform handshaking with</param>
        /// <param name="callback">The callback.</param>
        /// <param name="state">The state.</param>
        /// <returns></returns>
        public virtual IAsyncResult BeginHandshake(IConnection socket, AsyncCallback callback, object state)
        {
            if (socket == null)
                throw new ArgumentNullException(nameof(socket));

            if (AsyncResult != null)
                throw new ArgumentException("BeginHandshake has already been called");

            AsyncResult = new AsyncResult(callback, state);

            try
            {
                _socket = socket;

                // Either "1 A->B: Diffie Hellman Ya, PadA" or "2 B->A: Diffie Hellman Yb, PadB"
                // These two steps will be done simultaneously to save time due to latency
                SendY();
                ReceiveY();
            }
            catch (Exception ex)
            {
                AsyncResult.Complete(ex);
            }
            return AsyncResult;
        }
예제 #40
0
 public void TestResult()
 {
     AsyncResult result;
      // null result
      result = new AsyncResult(null, null);
      Assert.IsFalse(result.IsFaulted);
      result.Complete(null);
      Assert.AreEqual(result.GetResult(), null);
      Assert.AreEqual(result.GetResult<String>(), null);
      Assert.IsTrue(result.IsCompleted);
      Assert.IsFalse(result.IsFaulted);
      // non-null result
      result = new AsyncResult(null, null);
      Assert.IsFalse(result.IsFaulted);
      result.Complete("complete");
      Assert.AreEqual(result.GetResult(), "complete");
      Assert.AreEqual(result.GetResult<String>(), "complete");
      try
      {
     result.GetResult<Int32>();
     Assert.Fail("InvalidCastException expected");
      }
      catch (InvalidCastException) { }
      Assert.IsTrue(result.IsCompleted);
      Assert.IsFalse(result.IsFaulted);
      // exception result
      result = new AsyncResult(null, null);
      Assert.IsFalse(result.IsFaulted);
      result.Complete(null, new Exception("exception"));
      try
      {
     result.GetResult();
     Assert.Fail("Exception expected");
      }
      catch (Exception e)
      {
     Assert.AreEqual(e.Message, "exception");
      }
      Assert.IsTrue(result.IsCompleted);
      Assert.IsTrue(result.IsFaulted);
      // exception with typed result
      result = new AsyncResult(null, null);
      Assert.IsFalse(result.IsFaulted);
      result.Complete("complete", new Exception("exception"));
      try
      {
     result.GetResult<String>();
     Assert.Fail("Exception expected");
      }
      catch (Exception e)
      {
     Assert.AreEqual(e.Message, "exception");
      }
      Assert.IsTrue(result.IsCompleted);
      Assert.IsTrue(result.IsFaulted);
      // exception with invalid typed result
      result = new AsyncResult(null, null);
      Assert.IsFalse(result.IsFaulted);
      result.Complete("complete", new Exception("exception"));
      try
      {
     result.GetResult<Int32>();
     Assert.Fail("Exception expected");
      }
      catch (Exception e)
      {
     Assert.AreEqual(e.Message, "exception");
      }
      Assert.IsTrue(result.IsCompleted);
      Assert.IsTrue(result.IsFaulted);
 }
예제 #41
0
파일: Manager.cs 프로젝트: yallie/zyan
		public static IAsyncResult BeginReadMessage(object guidOrServer, Connection connection, AsyncCallback callback, object asyncState)
		{
			lock (_listenersLockObject)
			{
				Debug.Assert(!_listeners.ContainsKey(guidOrServer), "Handler for this guid already registered.");

				var ar = new AsyncResult(connection, callback, asyncState);

				// process pending message
				Queue<ConnectionAndMessage> queue;
				if (pendingMessages.TryGetValue(guidOrServer, out queue))
				{
					if (queue.Count > 0)
					{
						var result = queue.Dequeue();
						ar.Complete(result.Connection, result.Message);
						return ar;
					}
				}

				// or start listening for incoming messages
				_listeners.Add(guidOrServer, ar);
				return ar;
			}
		}
 public when_asyncresult_is_used_with_operation_throwing_exception()
 {
     asyncResult =
         new AsyncResult<string>(ar => { }, null);
     Task.Factory.StartNew(() => asyncResult.Complete(true, new InvalidOperationException()));
 }
			public IAsyncResult BeginExecuteReader(AsyncCallback callback)
			{
				AsyncResult<IDataReader> asyncResult = new AsyncResult<IDataReader>(callback, this);

				Task.Factory.StartNew(() =>
				{
					try
					{
						IDataReader dataReader = ExecureEventLogReader();
						asyncResult.Complete(dataReader, false);
					}
					catch (Exception exc)
					{
						asyncResult.HandleException(exc, false);
					}
				});

				return asyncResult;
			}
예제 #44
0
 private void ExecuteAsync(GpgCommand command, Stream input, Stream output, AsyncResult result)
 {
     try
     {
         Execute(command, input, output);
         result.Complete();
     }
     catch(Exception ex)
     {
         result.Throw(ex);
     }
 }
예제 #45
0
 private void ProcessException(AsyncResult ar, SocketException ex)
 {
     if (ar.IsCompleted) return;
     Disconnect(false);
     ar.Complete(false, ex);
 }
예제 #46
0
파일: Manager.cs 프로젝트: yallie/zyan
		public static IAsyncResult BeginReadMessage(object guidOrServer, Connection connection, AsyncCallback callback, object asyncState)
		{
			lock (_listenersLockObject)
			{
				Debug.Assert(!_listeners.Contains(guidOrServer), "Handler for this guid already registered.");

				AsyncResult ar = new AsyncResult(connection, callback, asyncState);
				if (outstandingMessages.Contains(guidOrServer))
				{
					Stack outstanding = (Stack)outstandingMessages[guidOrServer];
					if (outstanding.Count > 0)
					{
						object[] result = (object[])outstanding.Pop();
						ar.Complete((Connection)result[0], (Message)result[1]);
						return ar;
					}
				}
				_listeners.Add(guidOrServer, ar);
				return ar;
			}
		}