Esempio n. 1
0
        internal virtual void HandleAsyncEnd(IAsyncResult ar, bool turnProgressOff)
        {
            if (!ar.GetType().IsSubclassOf(typeof(AsyncResultBase)) && !ar.GetType().Equals(typeof(AsyncResultBase)))
            {
                throw new ArgumentException("asyncResult was not returned by a call to End* method.", "asyncResult");
            }
            AsyncResultBase base2 = (AsyncResultBase)ar;

            if (base2.IsHandled)
            {
                throw new InvalidOperationException("End* method was previously called for the asynchronous operation.");
            }
            if (!base2.IsCompleted)
            {
                base2.AsyncWaitHandle.WaitOne();
            }
            base2.IsHandled = true;
            if (turnProgressOff)
            {
                this.SetProgress(false);
            }
            if (base2.Exception != null)
            {
                throw base2.Exception;
            }
        }
Esempio n. 2
0
        virtual internal void HandleAsyncEnd(IAsyncResult ar, bool turnProgressOff)
        {
            if ((false == ar.GetType().IsSubclassOf(typeof(AsyncResultBase))) &&
                (false == ar.GetType().Equals(typeof(AsyncResultBase))))
            {
                throw new ArgumentException("asyncResult was not returned by a call to End* method.", "asyncResult");
            }

            AsyncResultBase stateObj = (AsyncResultBase)ar;

            if (stateObj.IsHandled)
            {
                throw new InvalidOperationException("End* method was previously called for the asynchronous operation.");
            }

            if (false == stateObj.IsCompleted)
            {
                stateObj.AsyncWaitHandle.WaitOne();
            }

            stateObj.IsHandled = true;

            if (turnProgressOff)
            {
                SetProgress(false);
            }

            if (null != stateObj.Exception)
            {
                //dumpActivityException(stateObj);
                throw stateObj.Exception;
            }
        }
        internal void EndProcessAuthentication(IAsyncResult result)
        {
            if (result == null)
            {
                throw new ArgumentNullException("asyncResult");
            }

            LazyAsyncResult lazyResult = result as LazyAsyncResult;

            if (lazyResult == null)
            {
                throw new ArgumentException(SR.Format(SR.net_io_async_result, result.GetType().FullName), "asyncResult");
            }

            if (Interlocked.Exchange(ref _nestedAuth, 0) == 0)
            {
                throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndAuthenticate"));
            }

            // No "artificial" timeouts implemented so far, InnerStream controls that.
            lazyResult.InternalWaitForCompletion();

            Exception e = lazyResult.Result as Exception;

            if (e != null)
            {
                // Round-trip it through the SetException().
                e = SetException(e);
                throw e;
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Ermittelt das Ergebnis eines asynchronen Aufrufs.
        /// </summary>
        /// <typeparam name="T">Der Datentyp des Ergebnisses.</typeparam>
        /// <param name="request">Die Steuereinheit zum Aufruf.</param>
        /// <returns>Das Ergebnis des Aufrufs oder <i>null</i>, wenn es sich nicht um
        /// eine Funktion handelte.</returns>
        public static T EndRequest <T>(IAsyncResult request)
        {
            // Validate
            if (request == null)
            {
                throw new ArgumentNullException("request");
            }

            // Change type
            var myRequest = request as _AsyncControl;

            if (myRequest == null)
            {
                throw new ArgumentException(request.GetType().FullName, "request");
            }

            // Wait until it finishes
            request.AsyncWaitHandle.WaitOne();

            // Get the server
            var server = (ServerImplementation)request.AsyncState;

            // Report the result
            return(server.GetResult <T>());
        }
Esempio n. 5
0
        internal void EndWrite(IAsyncResult asyncResult)
        {
            if (asyncResult == null)
            {
                throw new ArgumentNullException(nameof(asyncResult));
            }

            LazyAsyncResult lazyResult = asyncResult as LazyAsyncResult;

            if (lazyResult == null)
            {
                throw new ArgumentException(SR.Format(SR.net_io_async_result, asyncResult.GetType().FullName), nameof(asyncResult));
            }

            if (Interlocked.Exchange(ref _nestedWrite, 0) == 0)
            {
                throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndWrite"));
            }

            // No "artificial" timeouts implemented so far, InnerStream controls timeout.
            lazyResult.InternalWaitForCompletion();

            if (lazyResult.Result is Exception e)
            {
                if (e is IOException)
                {
                    ExceptionDispatchInfo.Capture(e).Throw();
                }

                throw new IOException(SR.net_io_write, e);
            }
        }
Esempio n. 6
0
        //
        //
        internal int EndRead(IAsyncResult asyncResult)
        {
            if (asyncResult == null)
            {
                throw new ArgumentNullException("asyncResult");
            }

            BufferAsyncResult bufferResult = asyncResult as BufferAsyncResult;

            if (bufferResult == null)
            {
                throw new ArgumentException(SR.GetString(SR.net_io_async_result, asyncResult.GetType().FullName), "asyncResult");
            }

            if (Interlocked.Exchange(ref _NestedRead, 0) == 0)
            {
                throw new InvalidOperationException(SR.GetString(SR.net_io_invalidendcall, "EndRead"));
            }

            // No "artificial" timeouts implemented so far, InnerStream controls timeout.
            bufferResult.InternalWaitForCompletion();

            if (bufferResult.Result is Exception)
            {
                if (bufferResult.Result is IOException)
                {
                    throw (Exception)bufferResult.Result;
                }
                throw new IOException(SR.GetString(SR.net_io_read), (Exception)bufferResult.Result);
            }
            return((int)bufferResult.Result);
        }
Esempio n. 7
0
        internal void ValidateAsyncResult(IAsyncResult ar, string endMethod)
        {
            if (ar == null)
            {
                throw new ArgumentException("result passed is null!");
            }
            if (!(ar is SqlAsyncResult))
            {
                throw new ArgumentException(String.Format("cannot test validity of types {0}",
                                                          ar.GetType()));
            }
            SqlAsyncResult result = (SqlAsyncResult)ar;

            if (result.EndMethod != endMethod)
            {
                throw new InvalidOperationException(String.Format("Mismatched {0} called for AsyncResult. " +
                                                                  "Expected call to {1} but {0} is called instead.",
                                                                  endMethod, result.EndMethod));
            }
            if (result.Ended)
            {
                throw new InvalidOperationException(String.Format("The method {0} cannot be called " +
                                                                  "more than once for the same AsyncResult.", endMethod));
            }
        }
Esempio n. 8
0
        //
        //
        internal void EndWrite(IAsyncResult asyncResult)
        {
            if (asyncResult == null)
            {
                throw new ArgumentNullException("asyncResult");
            }

            LazyAsyncResult lazyResult = asyncResult as LazyAsyncResult;

            if (lazyResult == null)
            {
                throw new ArgumentException(SR.GetString(SR.net_io_async_result, asyncResult.GetType().FullName), "asyncResult");
            }

            if (Interlocked.Exchange(ref _NestedWrite, 0) == 0)
            {
                throw new InvalidOperationException(SR.GetString(SR.net_io_invalidendcall, "EndWrite"));
            }

            // No "artificial" timeouts implemented so far, InnerStream controls timeout.
            lazyResult.InternalWaitForCompletion();

            if (lazyResult.Result is Exception)
            {
                if (lazyResult.Result is IOException)
                {
                    throw (Exception)lazyResult.Result;
                }
                throw new IOException(SR.GetString(SR.net_io_write), (Exception)lazyResult.Result);
            }
        }
Esempio n. 9
0
    public static int Main(string[] args)
    {
        result = 0;
        debug  = (args.Length > 0);
        if (debug)
        {
            Thread.CurrentThread.Name = "Main";
            Console.WriteLine(">Thread.Name: {0}", Thread.CurrentThread.Name);
        }

        Program      p  = new Program();
        Test         t  = new Test(p.TestInstance);
        IAsyncResult ar = t.BeginInvoke(null, null);

        if (debug)
        {
            Console.WriteLine("\tIAsyncResult type is {0}", ar.GetType());
        }

        t.EndInvoke(ar);

        if (debug)
        {
            Console.WriteLine("<Thread.Name: {0}", Thread.CurrentThread.Name);
        }

        return(result);
    }
Esempio n. 10
0
        static internal void VerifyAsyncResult(IAsyncResult ar,
                                               Type arType,
                                               string metName)
        {
            if (null == ar)
            {
                throw new ArgumentNullException("asyncResult", "The value cannot be null.");
            }

            if (null == metName)
            {
                metName = "End*";
            }

            if (false == ar.GetType().Equals(arType))
            {
                throw new ArgumentException("asyncResult was not returned by a call to the " +
                                            metName + " method.", "asyncResult");
            }

            AsyncResultBase stateObj = (AsyncResultBase)ar;

            if (stateObj.IsHandled)
            {
                throw new InvalidOperationException(metName + " was previously called for the asynchronous operation.");
            }
        }
Esempio n. 11
0
 protected static void ThrowInvalidAsyncResult(IAsyncResult result)
 {
     throw new InvalidOperationException(
               string.Format(
                   CultureInfo.CurrentCulture,
                   Resources.Error_IncorrectImplOfIAsyncResultReturningBadValues,
                   result.GetType()));
 }
Esempio n. 12
0
 protected static void ThrowInvalidAsyncResult(IAsyncResult result)
 {
     throw new InvalidOperationException(
               string.Format(
                   CultureInfo.CurrentCulture,
                   "An incorrect implementation of the IAsyncResult interface ({0}) may be returning incorrect values " +
                   "from the CompletedSynchronously property or calling the AsyncCallback more than once.",
                   result.GetType()));
 }
Esempio n. 13
0
        internal IAsyncResult BeginExecute(int timeout, string command, AsyncCallback cb, object state)
        {
            _arType = null;
            IAsyncResult ar = _cc.BeginSendCommandEx(timeout, command, cb, state);

            if (null != ar)
            {
                _arType = ar.GetType();
            }
            return(ar);
        }
Esempio n. 14
0
    SocketError GetAsysnErrorCode(IAsyncResult ar)
    {
        SocketError error = SocketError.SocketError;

        System.Reflection.PropertyInfo propinfo = ar.GetType().GetProperty("ErrorCode");
        if (propinfo != null)
        {
            error = (SocketError)propinfo.GetValue(ar, null);
        }
        return(error);
    }
Esempio n. 15
0
        /// <summary>
        /// AsyncCallback implementation used in asynchronous invocations.
        /// </summary>
        /// <param name="ar">IAsyncResult instance.</param>
        internal static void AsyncCallbackMethod(IAsyncResult ar)
        {
#if NETSTANDARD
            var asyncDelegate = ar.GetType().GetRuntimeProperty("AsyncDelegate").GetValue(ar);
            asyncDelegate.GetType().GetTypeInfo().GetDeclaredMethod("EndInvoke").Invoke(asyncDelegate, new[] { ar });
#else
            var result = (AsyncResult)ar;
            result.AsyncDelegate.GetType().GetMethod("EndInvoke").Invoke(result.AsyncDelegate, new[] { ar });
#endif
            ((SevenZipBase)ar.AsyncState).ReleaseContext();
        }
Esempio n. 16
0
 internal void EndChannelClose(IAsyncResult result)
 {
     if (typeof(CompletedAsyncResult).IsAssignableFrom(result.GetType()))
     {
         CompletedAsyncResult.End(result);
     }
     else
     {
         InnerChannel.EndClose(result);
     }
 }
Esempio n. 17
0
 internal void EndFactoryClose(IAsyncResult result)
 {
     if (typeof(CompletedAsyncResult).IsAssignableFrom(result.GetType()))
     {
         CompletedAsyncResult.End(result);
     }
     else
     {
         _channelFactory.EndClose(result);
     }
 }
Esempio n. 18
0
        /// <summary>
        /// AsyncCallback implementation used in asynchronous invocations.
        /// </summary>
        /// <param name="ar">IAsyncResult instance.</param>
        internal static void AsyncCallbackMethod(IAsyncResult ar)
        {
            object value = ar.GetType().GetRuntimeProperty("AsyncDelegate").GetValue(ar);

            IntrospectionExtensions.GetTypeInfo(value.GetType())
            .GetDeclaredMethod("EndInvoke").Invoke(value, new IAsyncResult[]
            {
                ar
            });
            ((SevenZipBase)ar.AsyncState).ReleaseContext();
        }
Esempio n. 19
0
        protected static void ThrowInvalidAsyncResult(IAsyncResult result)
        {
            if (result == null)
            {
                throw Error.ArgumentNull("result");
            }

            throw Error.InvalidOperation(
                      SRResources.InvalidAsyncResultImplementation,
                      result.GetType()
                      );
        }
Esempio n. 20
0
		internal void EndShutdown (IAsyncResult asyncResult)
		{
			if (asyncResult == null)
				throw new ArgumentNullException ("asyncResult");

			var shutdownResult = asyncResult as ShutdownAsyncResult;
			if (shutdownResult == null)
				throw new ArgumentException (SR.GetString (SR.net_io_async_result, asyncResult.GetType ().FullName), "asyncResult");

			if (shutdownResult.SentShutdown)
				SecureStream.EndShutdown (shutdownResult);
		}
Esempio n. 21
0
        static void Main(string[] args)
        {
            BrokenProxy  bp                  = new BrokenProxy(typeof(IRandomInterface));
            var          instance            = (IRandomInterface)bp.GetTransparentProxy();
            Func <int>   doSomethingDelegate = instance.DoSomething;
            IAsyncResult notAnIAsyncResult   = doSomethingDelegate.BeginInvoke(null, null);

            var interfaces = notAnIAsyncResult.GetType().GetInterfaces();

            Console.WriteLine(!interfaces.Any() ? "No interfaces on notAnIAsyncResult" : "Interfaces");
            Console.WriteLine(notAnIAsyncResult is IAsyncResult);             // Should be false, is it?!
            Console.WriteLine(((NotAnIAsyncResult)notAnIAsyncResult).SomeProperty);
            Console.WriteLine(((IAsyncResult)notAnIAsyncResult).IsCompleted); // No way this works.
        }
Esempio n. 22
0
            private void OnAsync(IAsyncResult r)
            {
                try
                {
                    if (m_isRequest)
                    {
                        m_stream = m_owner.m_request.EndGetRequestStream(r);
                    }
                    else
                    {
                        m_response = m_owner.m_request.EndGetResponse(r);
                    }
                }
                catch (Exception ex)
                {
                    if (m_timedout)
                    {
                        m_exception = new WebException(string.Format("{0} timed out", m_isRequest ? "GetRequestStream" : "GetResponse"), ex, WebExceptionStatus.Timeout, ex is WebException exception ? exception.Response : null);
                    }
                    else
                    {
                        // Workaround for: https://bugzilla.xamarin.com/show_bug.cgi?id=28287
                        var wex = ex;
                        if (ex is WebException exception && exception.Response == null)
                        {
                            WebResponse resp = null;

                            try { resp = (WebResponse)r.GetType().GetProperty("Response", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).GetValue(r); }
                            catch {}

                            if (resp == null)
                            {
                                try { resp = (WebResponse)m_owner.m_request.GetType().GetField("webResponse", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).GetValue(m_owner.m_request); }
                                catch { }
                            }

                            if (resp != null)
                            {
                                wex = new WebException(exception.Message, exception.InnerException, exception.Status, resp);
                            }
                        }

                        m_exception = wex;
                    }
                }
                finally
                {
                    m_event.Set();
                }
            }
Esempio n. 23
0
        private int EndRead(IAsyncResult asyncResult)
        {
#if DEBUG
            using (GlobalLog.SetThreadKind(ThreadKinds.User))
            {
#endif
            _negoState.CheckThrow(true);

            if (!_negoState.CanGetSecureStream)
            {
                return(InnerStreamAPM.EndRead(asyncResult));
            }


            if (asyncResult == null)
            {
                throw new ArgumentNullException("asyncResult");
            }

            BufferAsyncResult bufferResult = asyncResult as BufferAsyncResult;
            if (bufferResult == null)
            {
                throw new ArgumentException(SR.Format(SR.net_io_async_result, asyncResult.GetType().FullName), "asyncResult");
            }

            if (Interlocked.Exchange(ref _NestedRead, 0) == 0)
            {
                throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndRead"));
            }

            // No "artificial" timeouts implemented so far, InnerStream controls timeout.
            bufferResult.InternalWaitForCompletion();

            if (bufferResult.Result is Exception)
            {
                if (bufferResult.Result is IOException)
                {
                    throw (Exception)bufferResult.Result;
                }

                throw new IOException(SR.net_io_read, (Exception)bufferResult.Result);
            }

            return((int)bufferResult.Result);

#if DEBUG
        }
#endif
        }
Esempio n. 24
0
        public override int EndRead(IAsyncResult asyncResult)
        {
#if DEBUG
            using (DebugThreadTracking.SetThreadKind(ThreadKinds.User))
            {
#endif
            _negoState.CheckThrow(true);

            if (!_negoState.CanGetSecureStream)
            {
                return(TaskToApm.End <int>(asyncResult));
            }


            if (asyncResult == null)
            {
                throw new ArgumentNullException(nameof(asyncResult));
            }

            BufferAsyncResult?bufferResult = asyncResult as BufferAsyncResult;
            if (bufferResult == null)
            {
                throw new ArgumentException(SR.Format(SR.net_io_async_result, asyncResult.GetType().FullName), nameof(asyncResult));
            }

            if (Interlocked.Exchange(ref _NestedRead, 0) == 0)
            {
                throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndRead"));
            }

            // No "artificial" timeouts implemented so far, InnerStream controls timeout.
            bufferResult.InternalWaitForCompletion();

            if (bufferResult.Result is Exception e)
            {
                if (e is IOException)
                {
                    ExceptionDispatchInfo.Throw(e);
                }

                throw new IOException(SR.net_io_read, e);
            }

            return(bufferResult.Int32Result);

#if DEBUG
        }
#endif
        }
        private void StateChangedEventInvoke(IAsyncResult iar)
        {
            var asyncDelegate = iar.GetType().GetRuntimeProperty("AsyncDelegate");

            var invoke = asyncDelegate?.GetValue(iar) as EventHandler <StateChangedEventArgs>;

            try
            {
                invoke?.EndInvoke(iar);
            }
            catch (Exception exception)
            {
                Debug.WriteLine(exception);
            }
        }
Esempio n. 26
0
        /// <summary>
        /// Waits for the invocation of a delegate to complete, and returns the result of the delegate. This may only be called once for a given <see cref="IAsyncResult"/> object.
        /// </summary>
        /// <param name="result">The <see cref="IAsyncResult"/> returned from a call to <see cref="BeginInvoke"/>.</param>
        /// <returns>The result of the delegate. May not be <c>null</c>.</returns>
        /// <remarks>
        /// <para>If the delegate raised an exception, then this method will raise a <see cref="System.Reflection.TargetInvocationException"/> with that exception as the <see cref="Exception.InnerException"/> property.</para>
        /// </remarks>
        public object EndInvoke(IAsyncResult result)
        {
            Contract.Assume(result != null);
            Contract.Assume(result.GetType() == typeof(AsyncResult));

            // (This method may be invoked from any thread)
            AsyncResult asyncResult = (AsyncResult)result;

            asyncResult.WaitForAndDispose();
            if (asyncResult.Error != null)
            {
                throw asyncResult.Error;
            }

            return(asyncResult.ReturnValue);
        }
Esempio n. 27
0
        public override void EndWrite(IAsyncResult asyncResult)
        {
#if DEBUG
            using (DebugThreadTracking.SetThreadKind(ThreadKinds.User))
            {
#endif
            _negoState.CheckThrow(true);

            if (!_negoState.CanGetSecureStream)
            {
                InnerStream.EndWrite(asyncResult);
                return;
            }

            if (asyncResult == null)
            {
                throw new ArgumentNullException(nameof(asyncResult));
            }

            BufferAsyncResult bufferResult = asyncResult as BufferAsyncResult;
            if (bufferResult == null)
            {
                throw new ArgumentException(SR.Format(SR.net_io_async_result, asyncResult.GetType().FullName), nameof(asyncResult));
            }

            if (Interlocked.Exchange(ref _NestedWrite, 0) == 0)
            {
                throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndWrite"));
            }

            // No "artificial" timeouts implemented so far, InnerStream controls timeout.
            bufferResult.InternalWaitForCompletion();

            if (bufferResult.Result is Exception)
            {
                if (bufferResult.Result is IOException)
                {
                    throw (Exception)bufferResult.Result;
                }

                throw new IOException(SR.net_io_write, (Exception)bufferResult.Result);
            }
#if DEBUG
        }
#endif
        }
Esempio n. 28
0
        internal void EndShutdown(IAsyncResult asyncResult)
        {
            if (asyncResult == null)
            {
                throw new ArgumentNullException("asyncResult");
            }

            var shutdownResult = asyncResult as ShutdownAsyncResult;

            if (shutdownResult == null)
            {
                throw new ArgumentException(SR.GetString(SR.net_io_async_result, asyncResult.GetType().FullName), "asyncResult");
            }

            if (shutdownResult.SentShutdown)
            {
                SecureStream.EndShutdown(shutdownResult);
            }
        }
Esempio n. 29
0
        internal void EndRenegotiate(IAsyncResult result)
        {
            if (result == null)
            {
                throw new ArgumentNullException("asyncResult");
            }

            LazyAsyncResult lazyResult = result as LazyAsyncResult;

            if (lazyResult == null)
            {
                throw new ArgumentException(SR.GetString(SR.net_io_async_result, result.GetType().FullName), "asyncResult");
            }

            if (Interlocked.Exchange(ref _NestedAuth, 0) == 0)
            {
                throw new InvalidOperationException(SR.GetString(SR.net_io_invalidendcall, "EndRenegotiate"));
            }

            SecureStream.EndRenegotiate(lazyResult);
        }
Esempio n. 30
0
        private void endReceive(IAsyncResult r)
        {
            try
            {
                if (this.transportState == TransportState.closed)
                {
                    return;
                }
                StateObject state = new StateObject();
                Type        type  = r.GetType();
                System.Reflection.FieldInfo fieldInfo = type.GetField("Buffer");
                if (fieldInfo != null)
                {
                    state.buffer = (byte[])fieldInfo.GetValue(r);
                }

                int length = this.outStream.EndRead(r);
                if (length > 0)
                {
                    processBytes(state.buffer, 0, length);
                    //Receive next message
                    if (this.transportState != TransportState.closed)
                    {
                        receive();
                    }
                }
                else
                {
                    this.onDisconnect();
                }
            }
            catch (Exception e)
            {
                this.onReceiveError.Invoke(e);
            }
        }
            public new static DispatchContext End(IAsyncResult ar)
            {
                AsyncResult.End(ar);

                DispatchRequestAsyncResult dcar = ar as DispatchRequestAsyncResult;
                if (dcar == null)
                {
                    throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID2004, typeof(DispatchRequestAsyncResult), ar.GetType()));
                }
                return dcar.DispatchContext;
            }
 internal void EndProcessAuthentication(IAsyncResult result)
 {
     if (result == null)
     {
         throw new ArgumentNullException("asyncResult");
     }
     LazyAsyncResult result2 = result as LazyAsyncResult;
     if (result2 == null)
     {
         throw new ArgumentException(SR.GetString("net_io_async_result", new object[] { result.GetType().FullName }), "asyncResult");
     }
     if (Interlocked.Exchange(ref this._NestedAuth, 0) == 0)
     {
         throw new InvalidOperationException(SR.GetString("net_io_invalidendcall", new object[] { "EndAuthenticate" }));
     }
     result2.InternalWaitForCompletion();
     Exception e = result2.Result as Exception;
     if (e != null)
     {
         throw this.SetException(e);
     }
 }
Esempio n. 33
0
        // IO COMPLETION CALLBACK
        //
        // This callback is responsible for getting the complete protocol frame.
        // 1. it reads the header.
        // 2. it determines the frame size.
        // 3. loops while not all frame received or an error.
        //
        private void ReadFrameComplete(IAsyncResult transportResult)
        {
            do
            {
                if (!(transportResult.AsyncState is WorkerAsyncResult))
                {
                    if (GlobalLog.IsEnabled)
                    {
                        GlobalLog.AssertFormat("StreamFramer::ReadFrameComplete|The state expected to be WorkerAsyncResult, received:{0}.", transportResult.GetType().FullName);
                    }

                    Debug.Fail("StreamFramer::ReadFrameComplete|The state expected to be WorkerAsyncResult, received:" + transportResult.GetType().FullName + ".");
                }

                WorkerAsyncResult workerResult = (WorkerAsyncResult)transportResult.AsyncState;

                int bytesRead = _transport.EndRead(transportResult);
                workerResult.Offset += bytesRead;

                if (!(workerResult.Offset <= workerResult.End))
                {
                    if (GlobalLog.IsEnabled)
                    {
                        GlobalLog.AssertFormat("StreamFramer::ReadFrameCallback|WRONG: offset - end = {0}", workerResult.Offset - workerResult.End);
                    }

                    Debug.Fail("StreamFramer::ReadFrameCallback|WRONG: offset - end = " + (workerResult.Offset - workerResult.End));
                }

                if (bytesRead <= 0)
                {
                    // (by design) This indicates the stream has receives EOF
                    // If we are in the middle of a Frame - fail, otherwise - produce EOF
                    object result = null;
                    if (!workerResult.HeaderDone && workerResult.Offset == 0)
                    {
                        result = (object)-1;
                    }
                    else
                    {
                        result = new System.IO.IOException(SR.net_frame_read_io);
                    }

                    workerResult.InvokeCallback(result);
                    return;
                }

                if (workerResult.Offset >= workerResult.End)
                {
                    if (!workerResult.HeaderDone)
                    {
                        workerResult.HeaderDone = true;
                        // This indicates the header has been read successfully
                        _curReadHeader.CopyFrom(workerResult.Buffer, 0, _readVerifier);
                        int payloadSize = _curReadHeader.PayloadSize;
                        if (payloadSize < 0)
                        {
                            // Let's call user callback and he call us back and we will throw
                            workerResult.InvokeCallback(new System.IO.IOException(SR.Format(SR.net_frame_read_size)));
                        }

                        if (payloadSize == 0)
                        {
                            // report empty frame (NOT eof!) to the caller, he might be interested in
                            workerResult.InvokeCallback(0);
                            return;
                        }

                        if (payloadSize > _curReadHeader.MaxMessageSize)
                        {
                            throw new InvalidOperationException(SR.Format(SR.net_frame_size,
                                                                            _curReadHeader.MaxMessageSize.ToString(NumberFormatInfo.InvariantInfo),
                                                                            payloadSize.ToString(NumberFormatInfo.InvariantInfo)));
                        }

                        // Start reading the remaining frame data (note header does not count).
                        byte[] frame = new byte[payloadSize];
                        // Save the ref of the data block
                        workerResult.Buffer = frame;
                        workerResult.End = frame.Length;
                        workerResult.Offset = 0;

                        // Transport.BeginRead below will pickup those changes.
                    }
                    else
                    {
                        workerResult.HeaderDone = false; // Reset for optional object reuse.
                        workerResult.InvokeCallback(workerResult.End);
                        return;
                    }
                }

                // This means we need more data to complete the data block.
                transportResult = _transport.BeginRead(workerResult.Buffer, workerResult.Offset, workerResult.End - workerResult.Offset,
                                            _readFrameCallback, workerResult);
            } while (transportResult.CompletedSynchronously);
        }
Esempio n. 34
0
        /*++
            EndRead - Finishes off the Read for the Connection
            EndReadWithoutValidation

            This method completes the async call created from BeginRead,
            it attempts to determine how many bytes were actually read,
            and if any errors occured.

            Input:
                asyncResult - created by BeginRead

            Returns:
                int - size of bytes read, or < 0 on error

        --*/

        public override int EndRead(IAsyncResult asyncResult) {
#if DEBUG
            using (GlobalLog.SetThreadKind(ThreadKinds.User)) {
#endif
            if (Logging.On) Logging.Enter(Logging.Web, this, "EndRead", "");

            //
            // parameter validation
            //
            if (asyncResult==null) {
                throw new ArgumentNullException("asyncResult");
            }

            int bytesTransferred;
            bool zeroLengthRead = false;
            if ((asyncResult.GetType() == typeof(NestedSingleAsyncResult)) || m_Chunked)
            {
                LazyAsyncResult castedAsyncResult = (LazyAsyncResult)asyncResult;
                if (castedAsyncResult.AsyncObject != this)
                {
                    throw new ArgumentException(SR.GetString(SR.net_io_invalidasyncresult), "asyncResult");
                }
                if (castedAsyncResult.EndCalled)
                {
                    throw new InvalidOperationException(SR.GetString(SR.net_io_invalidendcall, "EndRead"));
                }
                castedAsyncResult.EndCalled = true;

                if (ErrorInStream)
                {
                    GlobalLog.LeaveException("ConnectStream::EndRead", m_ErrorException);
                    throw m_ErrorException;
                }

                object result = castedAsyncResult.InternalWaitForCompletion();

                Exception errorException = result as Exception;
                if (errorException != null)
                {
                    IOError(errorException, false);
                    bytesTransferred = -1;
                }
                else
                {
                    // If it's a NestedSingleAsyncResult, we completed it ourselves with our own result.
                    if (result == null)
                    {
                        bytesTransferred = 0;
                    }
                    else if (result == ZeroLengthRead)
                    {
                        bytesTransferred = 0;
                        zeroLengthRead = true;
                    }
                    else
                    {
                        try
                        {
                            bytesTransferred = (int) result;

                            if (m_Chunked && (bytesTransferred == 0))
                            {
                                m_ChunkEofRecvd = true;
                                CallDone();
                            }
                        }
                        catch (InvalidCastException)
                        {
                            bytesTransferred = -1;
                        }
                    }
                }
            }
            else
            {
                // If it's not a NestedSingleAsyncResult, we forwarded directly to the Connection and need to call EndRead.
                try
                {
                    bytesTransferred = m_Connection.EndRead(asyncResult);
                }
                catch (Exception exception)
                {
                    if (NclUtilities.IsFatal(exception)) throw;

                    IOError(exception, false);
                    bytesTransferred = -1;
                }
            }

            bytesTransferred = EndReadWithoutValidation(bytesTransferred, zeroLengthRead);

            Interlocked.CompareExchange(ref m_CallNesting, Nesting.Idle, Nesting.IoInProgress);
            GlobalLog.Print("EndRead() callNesting: " + m_CallNesting.ToString());

            if(Logging.On)Logging.Exit(Logging.Web, this, "EndRead", bytesTransferred);
            if (m_ErrorException != null) {
                throw (m_ErrorException);
            }

            return bytesTransferred;
#if DEBUG
            }
#endif
        }
Esempio n. 35
0
        internal void EndProcessAuthentication(IAsyncResult result)
        {
            if (result == null)
            {
                throw new ArgumentNullException("asyncResult");
            }

            LazyAsyncResult lazyResult = result as LazyAsyncResult;
            if (lazyResult == null)
            {
                throw new ArgumentException(SR.Format(SR.net_io_async_result, result.GetType().FullName), "asyncResult");
            }

            if (Interlocked.Exchange(ref _nestedAuth, 0) == 0)
            {
                throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndAuthenticate"));
            }

            InternalEndProcessAuthentication(lazyResult);

            // Connection is completed at this point.
            if (SecurityEventSource.Log.IsEnabled())
            {
                SecurityEventSource.Log.SspiSelectedCipherSuite("EndProcessAuthentication",
                    SslProtocol,
                    CipherAlgorithm,
                    CipherStrength,
                    HashAlgorithm,
                    HashStrength,
                    KeyExchangeAlgorithm,
                    KeyExchangeStrength);
            }
        }
        public override int EndRead(IAsyncResult asyncResult) {

            if (Interlocked.Decrement(ref m_ReadNesting) != 0) {
                Interlocked.Increment(ref m_ReadNesting);
                throw new InvalidOperationException(SR.GetString(SR.net_io_invalidendcall, "EndRead"));
            }

            if (asyncResult == null) {
                throw new ArgumentNullException("asyncResult");
            }

            InnerAsyncResult myResult = asyncResult as InnerAsyncResult;

            if (myResult == null) {
                // We are just passing IO down, although m_HeadEOF should be always true here.
                GlobalLog.Assert(m_HeadEOF, "CombinedReadStream::EndRead|m_HeadEOF is false and asyncResult is not of InnerAsyncResult type {0).", asyncResult.GetType().FullName);
                return m_HeadEOF? m_TailStream.EndRead(asyncResult): m_HeadStream.EndRead(asyncResult);
            }

            // this is our wrapped AsyncResult
            myResult.InternalWaitForCompletion();

            // Exception?
            if (myResult.Result is Exception) {
                throw (Exception)(myResult.Result);
            }

            // Report the count read
            return (int)myResult.Result;
        }
Esempio n. 37
0
            private void OnAsync(IAsyncResult r)
            {
                try
                {
                    if (m_isRequest)
                        m_stream = m_owner.m_request.EndGetRequestStream(r);
                    else
                        m_response = m_owner.m_request.EndGetResponse(r);
                }
                catch (Exception ex)
                {
                    if (m_timedout)
                        m_exception = new WebException(string.Format("{0} timed out", m_isRequest ? "GetRequestStream" : "GetResponse"), ex, WebExceptionStatus.Timeout, ex is WebException ? ((WebException)ex).Response : null);
                    else
                    {
                        // Workaround for: https://bugzilla.xamarin.com/show_bug.cgi?id=28287
                        var wex = ex;
                        if (ex is WebException && ((WebException)ex).Response == null)
                        {
                            WebResponse resp = null;

                            try { resp = (WebResponse)r.GetType().GetProperty("Response", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).GetValue(r); }
                            catch {}

                            if (resp == null)
                                try { resp = (WebResponse)m_owner.m_request.GetType().GetField("webResponse", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).GetValue(m_owner.m_request); }
                                catch { }

                            if (resp != null)
                                wex = new WebException(ex.Message, ex.InnerException, ((WebException)ex).Status, resp);
                        }

                        m_exception = wex;


                    }
                }
                finally
                {
                    m_event.Set();
                }
            }
Esempio n. 38
0
        internal void EndProcessAuthentication(IAsyncResult result)
        {
            if (result == null)
            {
                throw new ArgumentNullException("asyncResult");
            }

            LazyAsyncResult lazyResult = result as LazyAsyncResult;
            if (lazyResult == null)
            {
                throw new ArgumentException(SR.Format(SR.net_io_async_result, result.GetType().FullName), "asyncResult");
            }

            if (Interlocked.Exchange(ref _nestedAuth, 0) == 0)
            {
                throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndAuthenticate"));
            }

            // No "artificial" timeouts implemented so far, InnerStream controls that.
            lazyResult.InternalWaitForCompletion();

            Exception e = lazyResult.Result as Exception;

            if (e != null)
            {
                // Round-trip it through the SetException().
                e = SetException(e);
                throw e;
            }
        }
Esempio n. 39
0
        public override int EndRead(IAsyncResult asyncResult)
        {
#if DEBUG
            using (DebugThreadTracking.SetThreadKind(ThreadKinds.User))
            {
#endif
                _negoState.CheckThrow(true);

                if (!_negoState.CanGetSecureStream)
                {
                    return InnerStream.EndRead(asyncResult);
                }


                if (asyncResult == null)
                {
                    throw new ArgumentNullException(nameof(asyncResult));
                }

                BufferAsyncResult bufferResult = asyncResult as BufferAsyncResult;
                if (bufferResult == null)
                {
                    throw new ArgumentException(SR.Format(SR.net_io_async_result, asyncResult.GetType().FullName), nameof(asyncResult));
                }

                if (Interlocked.Exchange(ref _NestedRead, 0) == 0)
                {
                    throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndRead"));
                }

                // No "artificial" timeouts implemented so far, InnerStream controls timeout.
                bufferResult.InternalWaitForCompletion();

                if (bufferResult.Result is Exception)
                {
                    if (bufferResult.Result is IOException)
                    {
                        throw (Exception)bufferResult.Result;
                    }

                    throw new IOException(SR.net_io_read, (Exception)bufferResult.Result);
                }

                return bufferResult.Int32Result;
#if DEBUG
            }
#endif
        }
Esempio n. 40
0
        static internal void VerifyAsyncResult(IAsyncResult ar, 
            Type arType,
            string metName)
        {
            if(null == ar)
                throw new ArgumentNullException("asyncResult", "The value cannot be null.");

            if(null == metName)
                metName = "End*";

            if(false == ar.GetType().Equals(arType))
                throw new ArgumentException("asyncResult was not returned by a call to the " + 
                    metName + " method.", "asyncResult");

            AsyncResultBase stateObj = (AsyncResultBase)ar;
            if(stateObj.IsHandled)
                throw new InvalidOperationException(metName + " was previously called for the asynchronous operation.");
        }
        /// <summary>
        /// Completes an Asynchronous call to the STS.
        /// </summary>
        /// <param name="ar">IAsyncResult that was returned by the call to the Asynchronous Begin method.</param>
        /// <param name="requestAction">Request SOAP Action.</param>
        /// <param name="responseAction">Response SOAP Action.</param>
        /// <param name="trustNamespace">Namespace URI of the current trust version.</param>
        /// <returns>Message that contains the serialized RST message.</returns>
        /// <exception cref="ArgumentNullException">One of the argument is null.</exception>
        protected virtual Message EndProcessCore(IAsyncResult ar, string requestAction, string responseAction, string trustNamespace)
        {
            if (ar == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("ar");
            }

            ProcessCoreAsyncResult asyncResult = ar as ProcessCoreAsyncResult;
            if (asyncResult == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.GetString(SR.ID2004, typeof(ProcessCoreAsyncResult), ar.GetType()), "ar"));
            }

            Message message = null;
            try
            {
                message = ProcessCoreAsyncResult.End(ar);
            }
            catch (Exception ex)
            {
                if (!HandleException(ex, trustNamespace, requestAction, asyncResult.MessageVersion.Envelope))
                {
                    throw;
                }
            }

            return message;
        }
Esempio n. 42
0
        internal int EndRead(IAsyncResult asyncResult)
        {
            if (asyncResult == null)
            {
                throw new ArgumentNullException(nameof(asyncResult));
            }

            BufferAsyncResult bufferResult = asyncResult as BufferAsyncResult;
            if (bufferResult == null)
            {
                throw new ArgumentException(SR.Format(SR.net_io_async_result, asyncResult.GetType().FullName), nameof(asyncResult));
            }

            if (Interlocked.Exchange(ref _nestedRead, 0) == 0)
            {
                throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndRead"));
            }

            // No "artificial" timeouts implemented so far, InnerStream controls timeout.
            bufferResult.InternalWaitForCompletion();

            if (bufferResult.Result is Exception)
            {
                if (bufferResult.Result is IOException)
                {
                    throw (Exception)bufferResult.Result;
                }

                throw new IOException(SR.net_io_read, (Exception)bufferResult.Result);
            }

            return (int)bufferResult.Result;
        }
Esempio n. 43
0
        internal void EndWrite(IAsyncResult asyncResult)
        {
            if (asyncResult == null)
            {
                throw new ArgumentNullException(nameof(asyncResult));
            }

            LazyAsyncResult lazyResult = asyncResult as LazyAsyncResult;
            if (lazyResult == null)
            {
                throw new ArgumentException(SR.Format(SR.net_io_async_result, asyncResult.GetType().FullName), nameof(asyncResult));
            }

            if (Interlocked.Exchange(ref _nestedWrite, 0) == 0)
            {
                throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndWrite"));
            }

            // No "artificial" timeouts implemented so far, InnerStream controls timeout.
            lazyResult.InternalWaitForCompletion();

            if (lazyResult.Result is Exception)
            {
                if (lazyResult.Result is IOException)
                {
                    throw (Exception)lazyResult.Result;
                }

                throw new IOException(SR.net_io_write, (Exception)lazyResult.Result);
            }
        }
Esempio n. 44
0
        virtual internal void HandleAsyncEnd(IAsyncResult ar, bool turnProgressOff)
        {
            if((false == ar.GetType().IsSubclassOf(typeof(AsyncResultBase))) &&
                (false == ar.GetType().Equals(typeof(AsyncResultBase))))
                throw new ArgumentException("asyncResult was not returned by a call to End* method.", "asyncResult");

            AsyncResultBase stateObj = (AsyncResultBase)ar;
            if(stateObj.IsHandled)
                throw new InvalidOperationException("End* method was previously called for the asynchronous operation.");

            if(false == stateObj.IsCompleted)
                stateObj.AsyncWaitHandle.WaitOne();

            stateObj.IsHandled = true;

            if(turnProgressOff)
                SetProgress(false);    

            if(null != stateObj.Exception)
            {
                //dumpActivityException(stateObj);
                throw stateObj.Exception;
            }
        }
Esempio n. 45
0
		internal void EndRenegotiate (IAsyncResult result)
		{
			if (result == null)
				throw new ArgumentNullException ("asyncResult");

			LazyAsyncResult lazyResult = result as LazyAsyncResult;
			if (lazyResult == null)
				throw new ArgumentException (SR.GetString (SR.net_io_async_result, result.GetType ().FullName), "asyncResult");

			if (Interlocked.Exchange (ref _NestedAuth, 0) == 0)
				throw new InvalidOperationException (SR.GetString (SR.net_io_invalidendcall, "EndRenegotiate"));

			SecureStream.EndRenegotiate (lazyResult);
		}
 internal void EndWrite(IAsyncResult asyncResult)
 {
     if (asyncResult == null)
     {
         throw new ArgumentNullException("asyncResult");
     }
     LazyAsyncResult result = asyncResult as LazyAsyncResult;
     if (result == null)
     {
         throw new ArgumentException(SR.GetString("net_io_async_result", new object[] { asyncResult.GetType().FullName }), "asyncResult");
     }
     if (Interlocked.Exchange(ref this._NestedWrite, 0) == 0)
     {
         throw new InvalidOperationException(SR.GetString("net_io_invalidendcall", new object[] { "EndWrite" }));
     }
     result.InternalWaitForCompletion();
     if (result.Result is Exception)
     {
         if (result.Result is IOException)
         {
             throw ((Exception) result.Result);
         }
         throw new IOException(SR.GetString("net_io_write"), (Exception) result.Result);
     }
 }
        /// <summary>
        /// Waits for the invocation of a delegate to complete, and returns the result of the delegate. This may only be called once for a given <see cref="IAsyncResult"/> object.
        /// </summary>
        /// <param name="result">The <see cref="IAsyncResult"/> returned from a call to <see cref="BeginInvoke"/>.</param>
        /// <returns>The result of the delegate. May not be <c>null</c>.</returns>
        /// <remarks>
        /// <para>If the delegate raised an exception, then this method will raise a <see cref="System.Reflection.TargetInvocationException"/> with that exception as the <see cref="Exception.InnerException"/> property.</para>
        /// </remarks>
        public object EndInvoke(IAsyncResult result)
        {
            Contract.Assume(result != null);
            Contract.Assume(result.GetType() == typeof(AsyncResult));

            // (This method may be invoked from any thread)
            AsyncResult asyncResult = (AsyncResult)result;
            asyncResult.WaitForAndDispose();
            if (asyncResult.Error != null)
            {
                throw asyncResult.Error;
            }

            return asyncResult.ReturnValue;
        }
Esempio n. 48
0
        private void EndWrite(IAsyncResult asyncResult)
        {
#if DEBUG
            using (GlobalLog.SetThreadKind(ThreadKinds.User))
            {
#endif
                _negoState.CheckThrow(true);

                if (!_negoState.CanGetSecureStream)
                {
                    InnerStream.EndWrite(asyncResult);
                    return;
                }

                if (asyncResult == null)
                {
                    throw new ArgumentNullException(nameof(asyncResult));
                }

                BufferAsyncResult bufferResult = asyncResult as BufferAsyncResult;
                if (bufferResult == null)
                {
                    throw new ArgumentException(SR.Format(SR.net_io_async_result, asyncResult.GetType().FullName), nameof(asyncResult));
                }

                if (Interlocked.Exchange(ref _NestedWrite, 0) == 0)
                {
                    throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndWrite"));
                }

                // No "artificial" timeouts implemented so far, InnerStream controls timeout.
                bufferResult.InternalWaitForCompletion();

                if (bufferResult.Result is Exception)
                {
                    if (bufferResult.Result is IOException)
                    {
                        throw (Exception)bufferResult.Result;
                    }

                    throw new IOException(SR.net_io_write, (Exception)bufferResult.Result);
                }
#if DEBUG
            }
#endif
        }
 /// <summary>
 /// В конце асинхронной операции надо убедиться, что она завершена,
 /// и если нужно, обработать исключения
 /// </summary>
 /// <param name="asyncResult">состояние асинхронной операции в виде <see cref="IAsyncResult" /></param>
 /// <returns>Результат выполнения асинхронной операции. В нашем случае это
 /// Task.Result для <see cref="Task{TResult}" /> и Task.Wait() для <see cref="Task" /></returns>
 public override object EndExecute(IAsyncResult asyncResult)
 {
     // TODO: надо что-то тут сделать с асинхронными эксепшнами
     return
         _taskValueExtractors.GetOrAdd(asyncResult.GetType(), createTaskValueExtractor)(asyncResult);
 }
        public override int EndRead(IAsyncResult asyncResult) {

            if (Interlocked.Decrement(ref m_ReadNesting) != 0) {
                Interlocked.Increment(ref m_ReadNesting);
                throw new InvalidOperationException(SR.GetString(SR.net_io_invalidendcall, "EndRead"));
            }

            if (asyncResult == null) {
                throw new ArgumentNullException("asyncResult");
            }

            InnerAsyncResult myResult = asyncResult as InnerAsyncResult;

            if (myResult == null) {
                // We are just passing IO down, although the shadow stream should be dead for now.
                GlobalLog.Assert(m_ShadowStreamIsDead, "ForwardingReadStream::EndRead|m_ShadowStreamIsDead is false and asyncResult is not of InnerAsyncResult type {0}.", asyncResult.GetType().FullName);
                int bytes = m_OriginalStream.EndRead(asyncResult);
                if (bytes == 0)
                    m_SeenReadEOF = true;
            }

            // this is our wrapped AsyncResult
            bool suceess = false;
            try {
                myResult.InternalWaitForCompletion();
                // Exception?
                if (myResult.Result is Exception)
                    throw (Exception)(myResult.Result);
                suceess = true;
            }
            finally {
                if (!suceess && !m_ShadowStreamIsDead) {
                    m_ShadowStreamIsDead = true;
                    if (m_ShadowStream is ICloseEx)
                        ((ICloseEx)m_ShadowStream).CloseEx(CloseExState.Abort | CloseExState.Silent);
                    else
                        m_ShadowStream.Close();
                }
            }

            // Report the read count
            return (int)myResult.Result;
        }
Esempio n. 51
0
        private void ReadFrameCallback(IAsyncResult transportResult)
        {
            if (!(transportResult.AsyncState is WorkerAsyncResult))
            {
                if (GlobalLog.IsEnabled)
                {
                    GlobalLog.Assert("StreamFramer::ReadFrameCallback|The state expected to be WorkerAsyncResult, received:{0}.", transportResult.GetType().FullName);
                }

                Debug.Fail("StreamFramer::ReadFrameCallback|The state expected to be WorkerAsyncResult, received:" + transportResult.GetType().FullName + ".");
            }

            if (transportResult.CompletedSynchronously)
            {
                return;
            }

            WorkerAsyncResult workerResult = (WorkerAsyncResult)transportResult.AsyncState;

            try
            {
                ReadFrameComplete(transportResult);
            }
            catch (Exception e)
            {
                if (e is OutOfMemoryException)
                {
                    throw;
                }

                if (!(e is IOException))
                {
                    e = new System.IO.IOException(SR.Format(SR.net_io_readfailure, e.Message), e);
                }

                workerResult.InvokeCallback(e);
            }
        }
        private void ReadCallback(IAsyncResult transportResult) {
            GlobalLog.Assert(transportResult.AsyncState is InnerAsyncResult, "InnerAsyncResult::ReadCallback|The state expected to be of type InnerAsyncResult, received {0}.", transportResult.GetType().FullName);
            if (transportResult.CompletedSynchronously)
            {
                return;
            }

            InnerAsyncResult userResult = transportResult.AsyncState as InnerAsyncResult;
            try {
                // Complete transport IO, in this callback that is always the head stream
                int count;
                if (!m_HeadEOF) {
                    count = m_HeadStream.EndRead(transportResult);
                    m_HeadLength += count;
                }
                else {
                    count = m_TailStream.EndRead(transportResult);
                }


                //check on EOF condition
                if (!m_HeadEOF && count == 0 && userResult.Count != 0) {
                    //Got a first stream EOF
                    m_HeadEOF = true;
                    m_HeadStream.Close();
                    IAsyncResult ar = m_TailStream.BeginRead(userResult.Buffer, userResult.Offset, userResult.Count, m_ReadCallback, userResult);
                    if (!ar.CompletedSynchronously) {
                        return;
                    }
                    count = m_TailStream.EndRead(ar);
                }
                // just complete user IO
                userResult.Buffer = null;
                userResult.InvokeCallback(count);
            }
            catch (Exception e) {
                //ASYNC: try to swallow even serious exceptions (nothing to loose?)
                if (userResult.InternalPeekCompleted)
                    throw;

                userResult.InvokeCallback(e);
            }
            catch {
                //ASYNC: try to swallow even serious exceptions (nothing to loose?)
                if (userResult.InternalPeekCompleted)
                    throw;

                userResult.InvokeCallback(new Exception(SR.GetString(SR.net_nonClsCompliantException)));
            }
        }
Esempio n. 53
0
 protected static void ThrowInvalidAsyncResult(IAsyncResult result)
 {
     throw new InvalidOperationException(CommonResources.GetString(CommonResources.InvalidAsyncResultImplementation, result.GetType()));
 }
        private void ReadCallback(IAsyncResult transportResult) {
            GlobalLog.Assert(transportResult.AsyncState is InnerAsyncResult, "InnerAsyncResult::ReadCallback|The state expected to be of type InnerAsyncResult, received {0}.", transportResult.GetType().FullName);
            if (transportResult.CompletedSynchronously)
            {
                return;
            }

            // Recover our asyncResult
            InnerAsyncResult userResult = transportResult.AsyncState as InnerAsyncResult;

            ReadComplete(transportResult);
        }
Esempio n. 55
0
        private void ReadFrameCallback(IAsyncResult transportResult)
        {
            GlobalLog.Assert(transportResult.AsyncState is WorkerAsyncResult, "StreamFramer::ReadFrameCallback|The state expected to be WorkerAsyncResult, received:{0}.", transportResult.GetType().FullName);
            if (transportResult.CompletedSynchronously)
            {
                return;
            }

            WorkerAsyncResult workerResult = (WorkerAsyncResult) transportResult.AsyncState;

            try
            {
                ReadFrameComplete(transportResult);
            }
            catch (Exception e) {
                if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) {
                    throw;
                }

                if (!(e is IOException)) {
                    e = new System.IO.IOException(SR.GetString(SR.net_io_readfailure, e.Message), e);
                }

                // Let's call user callback and he call us back and we will throw
                workerResult.InvokeCallback(e);
            }
        }
            public new static Message End(IAsyncResult ar)
            {
                AsyncResult.End(ar);

                ProcessCoreAsyncResult pcar = ar as ProcessCoreAsyncResult;
                if (pcar == null)
                {
                    throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID2004, typeof(ProcessCoreAsyncResult), ar.GetType()));
                }

                //
                // Create the response Message object with the appropriate action.
                //
                return Message.CreateMessage(OperationContext.Current.RequestContext.RequestMessage.Version,
                                              pcar.DispatchContext.ResponseAction,
                                              new WSTrustResponseBodyWriter(pcar.DispatchContext.ResponseMessage,
                                                                             pcar.ResponseSerializer,
                                                                             pcar.SerializationContext));
            }
Esempio n. 57
0
		internal void ValidateAsyncResult (IAsyncResult ar, string endMethod)
		{
			if (ar == null)
				throw new ArgumentException ("result passed is null!");
			if (! (ar is SqlAsyncResult))
				throw new ArgumentException (String.Format ("cannot test validity of types {0}",
					ar.GetType ()));
			SqlAsyncResult result = (SqlAsyncResult) ar;
			if (result.EndMethod != endMethod)
				throw new InvalidOperationException (String.Format ("Mismatched {0} called for AsyncResult. " + 
					"Expected call to {1} but {0} is called instead.",
					endMethod, result.EndMethod));
			if (result.Ended)
				throw new InvalidOperationException (String.Format ("The method {0} cannot be called " + 
					"more than once for the same AsyncResult.", endMethod));
		}
Esempio n. 58
0
        internal void EndProcessAuthentication(IAsyncResult result)
        {
            if (result == null)
            {
                throw new ArgumentNullException("asyncResult");
            }

            LazyAsyncResult lazyResult = result as LazyAsyncResult;
            if (lazyResult == null)
            {
                throw new ArgumentException(SR.Format(SR.net_io_async_result, result.GetType().FullName), "asyncResult");
            }

            if (Interlocked.Exchange(ref _nestedAuth, 0) == 0)
            {
                throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, "EndAuthenticate"));
            }

            InternalEndProcessAuthentication(lazyResult);

            // Connection is completed at this point.
            if (Logging.On)
            {
                Logging.PrintInfo(Logging.Web, SR.Format(SR.net_log_sspi_selected_cipher_suite,
                    "EndProcessAuthentication",
                    SslProtocol,
                    CipherAlgorithm,
                    CipherStrength,
                    HashAlgorithm,
                    HashStrength,
                    KeyExchangeAlgorithm,
                    KeyExchangeStrength));
            }
        }
Esempio n. 59
0
 private void Receive(IAsyncResult ar)
 {
     try
     {
         if (!_connected || _states.State is ClosedState)
         {
             return;
         }
         Logger.Debug(this, ar.GetType().FullName);
         int rx = _stream.EndRead(ar);
         _stream.BeginRead(_buff, 0, _buff.Length, new AsyncCallback(Receive), null);
         if (!_encrypting)
             ProtocolParser.Parse(_buff, rx);
     }
     catch (SocketException e)
     {
         Logger.DebugFormat(this, "Socket Exception: {0}", e);
     }
     catch (InvalidOperationException e)
     {
         Logger.DebugFormat(this, "Invalid Operation: {0}", e);
     }
 }
        /// <summary>
        /// Ends the async call of Issue request. This would finally return the RequestSecurityTokenResponse.
        /// </summary>
        /// <param name="result">The async result returned from the BeginIssue method.</param>
        /// <returns>The security token response.</returns>
        public virtual RSTR EndIssue(IAsyncResult result)
        {
            if (result == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("result");
            }

            if (!(result is TypedAsyncResult<RSTR>))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID2012, typeof(TypedAsyncResult<RSTR>), result.GetType())));
            }

            return TypedAsyncResult<RSTR>.End(result);
        }