public void Increment(NetworkingPerfCounterName perfCounter, long amount)
 {
     if (this.CounterAvailable())
     {
         try
         {
             CounterPair pair = this.counters[(int)perfCounter];
             pair.InstanceCounter.IncrementBy(amount);
             pair.GlobalCounter.IncrementBy(amount);
         }
         catch (InvalidOperationException exception)
         {
             if (Logging.On)
             {
                 Logging.Exception(Logging.Web, "NetworkingPerfCounters", "Increment", exception);
             }
         }
         catch (Win32Exception exception2)
         {
             if (Logging.On)
             {
                 Logging.Exception(Logging.Web, "NetworkingPerfCounters", "Increment", exception2);
             }
         }
     }
 }
 public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state)
 {
     try
     {
         if (this.Aborted)
         {
             throw ExceptionHelper.RequestAbortedException;
         }
         lock (this)
         {
             if (this.m_readPending)
             {
                 Exception exception = new InvalidOperationException(SR.GetString("net_repcall"));
                 throw exception;
             }
             this.m_readPending = true;
         }
         this.m_WriteAResult = new LazyAsyncResult(this, state, callback);
         ThreadPool.QueueUserWorkItem(s_GetResponseCallback, this.m_WriteAResult);
     }
     catch (Exception exception2)
     {
         if (Logging.On)
         {
             Logging.Exception(Logging.Web, this, "BeginGetResponse", exception2);
         }
         throw;
     }
     return(this.m_WriteAResult);
 }
예제 #3
0
        public override WebResponse GetResponse()
        {
            GlobalLog.Enter("FileWebRequest::GetResponse");

            m_syncHint = true;

            IAsyncResult result;

            try {
                result = BeginGetResponse(null, null);

                if ((Timeout != System.Threading.Timeout.Infinite) && !result.IsCompleted)
                {
                    if (!result.AsyncWaitHandle.WaitOne(Timeout, false) || !result.IsCompleted)
                    {
                        if (m_response != null)
                        {
                            m_response.Close();
                        }
                        Exception e = new WebException(NetRes.GetWebStatusString(WebExceptionStatus.Timeout), WebExceptionStatus.Timeout);
                        GlobalLog.LeaveException("FileWebRequest::GetResponse", e);
                        throw e;
                    }
                }
            } catch (Exception exception) {
                if (Logging.On)
                {
                    Logging.Exception(Logging.Web, this, "GetResponse", exception);
                }
                throw;
            } finally {
                GlobalLog.Leave("FileWebRequest::GetResponse");
            }
            return(EndGetResponse(result));
        }
        public override Stream EndGetRequestStream(IAsyncResult asyncResult)
        {
            Stream stream;

            try
            {
                LazyAsyncResult result = asyncResult as LazyAsyncResult;
                if ((asyncResult == null) || (result == null))
                {
                    Exception exception = (asyncResult == null) ? new ArgumentNullException("asyncResult") : new ArgumentException(SR.GetString("InvalidAsyncResult"), "asyncResult");
                    throw exception;
                }
                object obj2 = result.InternalWaitForCompletion();
                if (obj2 is Exception)
                {
                    throw ((Exception)obj2);
                }
                stream = (Stream)obj2;
                this.m_writePending = false;
            }
            catch (Exception exception2)
            {
                if (Logging.On)
                {
                    Logging.Exception(Logging.Web, this, "EndGetRequestStream", exception2);
                }
                throw;
            }
            return(stream);
        }
        public override WebResponse EndGetResponse(IAsyncResult asyncResult)
        {
            WebResponse response;

            try
            {
                LazyAsyncResult result = asyncResult as LazyAsyncResult;
                if ((asyncResult == null) || (result == null))
                {
                    Exception exception = (asyncResult == null) ? new ArgumentNullException("asyncResult") : new ArgumentException(SR.GetString("InvalidAsyncResult"), "asyncResult");
                    throw exception;
                }
                object obj2 = result.InternalWaitForCompletion();
                if (obj2 is Exception)
                {
                    throw ((Exception)obj2);
                }
                response           = (WebResponse)obj2;
                this.m_readPending = false;
            }
            catch (Exception exception2)
            {
                if (Logging.On)
                {
                    Logging.Exception(Logging.Web, this, "EndGetResponse", exception2);
                }
                throw;
            }
            return(response);
        }
        public override WebResponse GetResponse()
        {
            IAsyncResult result;

            this.m_syncHint = true;
            try
            {
                result = this.BeginGetResponse(null, null);
                if (((this.Timeout != -1) && !result.IsCompleted) && (!result.AsyncWaitHandle.WaitOne(this.Timeout, false) || !result.IsCompleted))
                {
                    if (this.m_response != null)
                    {
                        this.m_response.Close();
                    }
                    Exception exception = new WebException(NetRes.GetWebStatusString(WebExceptionStatus.Timeout), WebExceptionStatus.Timeout);
                    throw exception;
                }
            }
            catch (Exception exception2)
            {
                if (Logging.On)
                {
                    Logging.Exception(Logging.Web, this, "GetResponse", exception2);
                }
                throw;
            }
            return(this.EndGetResponse(result));
        }
예제 #7
0
        public override WebResponse EndGetResponse(IAsyncResult asyncResult)
        {
            GlobalLog.Enter("FileWebRequest::EndGetResponse");

            WebResponse response;

            try {
                ContextAwareResult ar = asyncResult as ContextAwareResult;
                if (asyncResult == null || ar == null)
                {
                    Exception e = asyncResult == null? new ArgumentNullException("asyncResult"): new ArgumentException(SR.GetString(SR.InvalidAsyncResult), "asyncResult");
                    GlobalLog.LeaveException("FileWebRequest::EndGetRequestStream", e);
                    throw e;
                }


                object result = ar.InternalWaitForCompletion();
                if (result is Exception)
                {
                    throw (Exception)result;
                }
                response      = (WebResponse)result;
                m_readPending = false;
            } catch (Exception exception) {
                if (Logging.On)
                {
                    Logging.Exception(Logging.Web, this, "EndGetResponse", exception);
                }
                throw;
            } finally {
                GlobalLog.Leave("FileWebRequest::EndGetResponse");
            }
            return(response);
        }
 public void Increment(NetworkingPerfCounterName perfCounter, long amount)
 {
     if (CounterAvailable())
     {
         try
         {
             CounterPair cp = counters[(int)perfCounter];
             Debug.Assert(cp != null);
             cp.InstanceCounter.IncrementBy(amount);
             cp.GlobalCounter.IncrementBy(amount);
         }
         // in case there is something wrong with the counter instance, just log and continue
         catch (InvalidOperationException e)
         {
             if (Logging.On)
             {
                 Logging.Exception(Logging.Web, "NetworkingPerfCounters", "Increment", e);
             }
         }
         catch (Win32Exception e)
         {
             if (Logging.On)
             {
                 Logging.Exception(Logging.Web, "NetworkingPerfCounters", "Increment", e);
             }
         }
     }
 }
예제 #9
0
        public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state)
        {
            GlobalLog.Enter("FileWebRequest::BeginGetRequestStream");

            try {
                if (Aborted)
                {
                    throw ExceptionHelper.RequestAbortedException;
                }
                if (!CanGetRequestStream())
                {
                    Exception e = new ProtocolViolationException(SR.GetString(SR.net_nouploadonget));
                    GlobalLog.LeaveException("FileWebRequest::BeginGetRequestStream", e);
                    throw e;
                }
                if (m_response != null)
                {
                    Exception e = new InvalidOperationException(SR.GetString(SR.net_reqsubmitted));
                    GlobalLog.LeaveException("FileWebRequest::BeginGetRequestStream", e);
                    throw e;
                }
                lock (this) {
                    if (m_writePending)
                    {
                        Exception e = new InvalidOperationException(SR.GetString(SR.net_repcall));
                        GlobalLog.LeaveException("FileWebRequest::BeginGetRequestStream", e);
                        throw e;
                    }
                    m_writePending = true;
                }

                //we need to force the capture of the identity and context to make sure the
                //posted callback doesn't inavertently gain access to something it shouldn't.
                m_ReadAResult = new LazyAsyncResult(this, state, callback);
                ThreadPool.QueueUserWorkItem(s_GetRequestStreamCallback, m_ReadAResult);
            } catch (Exception exception) {
                if (Logging.On)
                {
                    Logging.Exception(Logging.Web, this, "BeginGetRequestStream", exception);
                }
                throw;
            } finally {
                GlobalLog.Leave("FileWebRequest::BeginGetRequestSteam");
            }

            string suri;

            if (FrameworkEventSource.Log.IsEnabled(EventLevel.Verbose, FrameworkEventSource.Keywords.NetClient))
            {
                suri = this.RequestUri.ToString();
            }
            else
            {
                suri = this.RequestUri.OriginalString;
            }
            FrameworkEventSource.Log.BeginGetRequestStream(this, suri);

            return(m_ReadAResult);
        }
예제 #10
0
        public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state)
        {
            GlobalLog.Enter("FileWebRequest::BeginGetRequestStream");
#if !MONO
            bool success = true;
#endif
            try {
                if (Aborted)
                {
                    throw ExceptionHelper.RequestAbortedException;
                }
                if (!CanGetRequestStream())
                {
                    Exception e = new ProtocolViolationException(SR.GetString(SR.net_nouploadonget));
                    GlobalLog.LeaveException("FileWebRequest::BeginGetRequestStream", e);
                    throw e;
                }
                if (m_response != null)
                {
                    Exception e = new InvalidOperationException(SR.GetString(SR.net_reqsubmitted));
                    GlobalLog.LeaveException("FileWebRequest::BeginGetRequestStream", e);
                    throw e;
                }
                lock (this) {
                    if (m_writePending)
                    {
                        Exception e = new InvalidOperationException(SR.GetString(SR.net_repcall));
                        GlobalLog.LeaveException("FileWebRequest::BeginGetRequestStream", e);
                        throw e;
                    }
                    m_writePending = true;
                }

                //we need to force the capture of the identity and context to make sure the
                //posted callback doesn't inavertently gain access to something it shouldn't.
                m_ReadAResult = new LazyAsyncResult(this, state, callback);
                ThreadPool.QueueUserWorkItem(s_GetRequestStreamCallback, m_ReadAResult);
            } catch (Exception exception) {
#if !MONO
                success = false;
#endif
                if (Logging.On)
                {
                    Logging.Exception(Logging.Web, this, "BeginGetRequestStream", exception);
                }
                throw;
            } finally {
#if !MONO
                if (FrameworkEventSource.Log.IsEnabled())
                {
                    LogBeginGetRequestStream(success, synchronous: false);
                }
#endif
                GlobalLog.Leave("FileWebRequest::BeginGetRequestSteam");
            }

            return(m_ReadAResult);
        }
예제 #11
0
        public override void Abort()
        {
            GlobalLog.Enter("FileWebRequest::Abort");
            if (Logging.On)
            {
                Logging.PrintWarning(Logging.Web, NetRes.GetWebStatusString("net_requestaborted", WebExceptionStatus.RequestCanceled));
            }
            try {
                if (Interlocked.Increment(ref m_Aborted) == 1)
                {
                    LazyAsyncResult readAResult  = m_ReadAResult;
                    LazyAsyncResult writeAResult = m_WriteAResult;

                    WebException webException = new WebException(NetRes.GetWebStatusString("net_requestaborted", WebExceptionStatus.RequestCanceled), WebExceptionStatus.RequestCanceled);

                    Stream requestStream = m_stream;

                    if (readAResult != null && !readAResult.IsCompleted)
                    {
                        readAResult.InvokeCallback(webException);
                    }
                    if (writeAResult != null && !writeAResult.IsCompleted)
                    {
                        writeAResult.InvokeCallback(webException);
                    }

                    if (requestStream != null)
                    {
                        if (requestStream is ICloseEx)
                        {
                            ((ICloseEx)requestStream).CloseEx(CloseExState.Abort);
                        }
                        else
                        {
                            requestStream.Close();
                        }
                    }

                    if (m_response != null)
                    {
                        ((ICloseEx)m_response).CloseEx(CloseExState.Abort);
                    }
                }
            } catch (Exception exception) {
                if (Logging.On)
                {
                    Logging.Exception(Logging.Web, this, "Abort", exception);
                }
                throw;
            } finally {
                GlobalLog.Leave("FileWebRequest::Abort");
            }
        }
예제 #12
0
        public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state)
        {
            GlobalLog.Enter("FileWebRequest::BeginGetRequestStream");

            try {
                if (Aborted)
                {
                    throw ExceptionHelper.RequestAbortedException;
                }
                if (!CanGetRequestStream())
                {
                    Exception e = new ProtocolViolationException(SR.GetString(SR.net_nouploadonget));
                    GlobalLog.LeaveException("FileWebRequest::BeginGetRequestStream", e);
                    throw e;
                }
                if (m_response != null)
                {
                    Exception e = new InvalidOperationException(SR.GetString(SR.net_reqsubmitted));
                    GlobalLog.LeaveException("FileWebRequest::BeginGetRequestStream", e);
                    throw e;
                }
                lock (this) {
                    if (m_writePending)
                    {
                        Exception e = new InvalidOperationException(SR.GetString(SR.net_repcall));
                        GlobalLog.LeaveException("FileWebRequest::BeginGetRequestStream", e);
                        throw e;
                    }
                    m_writePending = true;
                }

                //we need to force the capture of the identity and context to make sure the
                //posted callback doesn't inavertently gain access to something it shouldn't.
                m_ReadAResult = new ContextAwareResult(true, true, true, this, state, callback);
                lock (m_ReadAResult.StartPostingAsyncOp())
                {
                    ThreadPool.UnsafeQueueUserWorkItem(s_GetRequestStreamCallback, m_ReadAResult);
                    m_ReadAResult.FinishPostingAsyncOp();
                }
            } catch (Exception exception) {
                if (Logging.On)
                {
                    Logging.Exception(Logging.Web, this, "BeginGetRequestStream", exception);
                }
                throw;
            } finally {
                GlobalLog.Leave("FileWebRequest::BeginGetRequestSteam");
            }
            return(m_ReadAResult);
        }
예제 #13
0
        public override WebResponse EndGetResponse(IAsyncResult asyncResult)
        {
            GlobalLog.Enter("FileWebRequest::EndGetResponse");

            WebResponse response;

#if !MONO
            bool success = false;
#endif
            try {
                LazyAsyncResult ar = asyncResult as LazyAsyncResult;
                if (asyncResult == null || ar == null)
                {
                    Exception e = asyncResult == null? new ArgumentNullException("asyncResult"): new ArgumentException(SR.GetString(SR.InvalidAsyncResult), "asyncResult");
                    GlobalLog.LeaveException("FileWebRequest::EndGetRequestStream", e);
                    throw e;
                }


                object result = ar.InternalWaitForCompletion();
                if (result is Exception)
                {
                    throw (Exception)result;
                }
                response      = (WebResponse)result;
                m_readPending = false;
#if !MONO
                success = true;
#endif
            } catch (Exception exception) {
                if (Logging.On)
                {
                    Logging.Exception(Logging.Web, this, "EndGetResponse", exception);
                }
                throw;
            } finally {
                GlobalLog.Leave("FileWebRequest::EndGetResponse");

#if !MONO
                // there is no statusCode in FileWebRequest object, defaulting it to zero.
                if (FrameworkEventSource.Log.IsEnabled())
                {
                    LogEndGetResponse(success, synchronous: false, statusCode: 0);
                }
#endif
            }

            return(response);
        }
예제 #14
0
        public override int EndRead(IAsyncResult asyncResult)
        {
            if (Logging.On)
            {
                Logging.Enter(Logging.HttpListener, this, "EndRead", "");
            }
            GlobalLog.Print("HttpRequestStream#" + ValidationHelper.HashString(this) + "::EndRead() asyncResult#" + ValidationHelper.HashString(asyncResult));
            if (asyncResult == null)
            {
                throw new ArgumentNullException("asyncResult");
            }
            HttpRequestStreamAsyncResult castedAsyncResult = asyncResult as HttpRequestStreamAsyncResult;

            if (castedAsyncResult == null || 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;
            // wait & then check for errors
            object    returnValue = castedAsyncResult.InternalWaitForCompletion();
            Exception exception   = returnValue as Exception;

            if (exception != null)
            {
                GlobalLog.Print("HttpRequestStream#" + ValidationHelper.HashString(this) + "::EndRead() rethrowing exception:" + exception);
                if (Logging.On)
                {
                    Logging.Exception(Logging.HttpListener, this, "EndRead", exception);
                }
                throw exception;
            }
            //


            uint dataRead = (uint)returnValue;

            UpdateAfterRead((uint)castedAsyncResult.ErrorCode, dataRead);
            GlobalLog.Print("HttpRequestStream#" + ValidationHelper.HashString(this) + "::EndRead() returning returnValue:" + ValidationHelper.ToString(returnValue));
            if (Logging.On)
            {
                Logging.Exit(Logging.HttpListener, this, "EndRead", "");
            }

            return((int)dataRead + (int)castedAsyncResult.m_dataAlreadyRead);
        }
        // Need to check for Environment.HasShutdownStarted.  This flag is ONLY
        // set when the CLR is running the GC Finalize thread and thus it is invalid
        // to access the static performanceCounter objects and their methods.
        private void Cleanup()
        {
            // In cases where Cleanup() gets called simultaneously on different threads,
            // we use the lock to make sure it gets executed only once.
            lock (lockObject)
            {
                if (!cleanupCalled)
                {
                    cleanupCalled = true;

                    // counters may be null if Initialize() throws before counters gets created
                    if (counters != null)
                    {
                        foreach (CounterPair cp in counters)
                        {
                            // cp != null check: if the loop creating the counters in Initialize() throws
                            // an excpetion, some CounterPairs may not be created yet, thus the null check below.
                            if (!Environment.HasShutdownStarted && cp != null)
                            {
                                try
                                {
                                    cp.InstanceCounter.RemoveInstance();
                                }
                                // in case there is something wrong with the counter instance, just log.
                                catch (InvalidOperationException e)
                                {
                                    if (Logging.On)
                                    {
                                        Logging.Exception(Logging.Web, "NetworkingPerfCounters",
                                                          "Cleanup", e);
                                    }
                                }
                                catch (Win32Exception e)
                                {
                                    if (Logging.On)
                                    {
                                        Logging.Exception(Logging.Web, "NetworkingPerfCounters",
                                                          "Cleanup", e);
                                    }
                                }
                            }
                        }
                    }

                    // No need to clean up global counters.
                }
            }
        }
예제 #16
0
        public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state)
        {
            GlobalLog.Enter("FileWebRequest::BeginGetResponse");

            try {
                if (Aborted)
                {
                    throw ExceptionHelper.RequestAbortedException;
                }
                lock (this) {
                    if (m_readPending)
                    {
                        Exception e = new InvalidOperationException(SR.GetString(SR.net_repcall));
                        GlobalLog.LeaveException("FileWebRequest::BeginGetResponse", e);
                        throw e;
                    }
                    m_readPending = true;
                }

                m_WriteAResult = new LazyAsyncResult(this, state, callback);
                ThreadPool.QueueUserWorkItem(s_GetResponseCallback, m_WriteAResult);
            } catch (Exception exception) {
                if (Logging.On)
                {
                    Logging.Exception(Logging.Web, this, "BeginGetResponse", exception);
                }
                throw;
            } finally {
                GlobalLog.Leave("FileWebRequest::BeginGetResponse");
            }

            string suri;

            if (FrameworkEventSource.Log.IsEnabled(EventLevel.Verbose, FrameworkEventSource.Keywords.NetClient))
            {
                suri = this.RequestUri.ToString();
            }
            else
            {
                suri = this.RequestUri.OriginalString;
            }
            if (FrameworkEventSource.Log.IsEnabled())
            {
                LogBeginGetResponse(suri);
            }

            return(m_WriteAResult);
        }
 public override void Abort()
 {
     if (Logging.On)
     {
         Logging.PrintWarning(Logging.Web, NetRes.GetWebStatusString("net_requestaborted", WebExceptionStatus.RequestCanceled));
     }
     try
     {
         if (Interlocked.Increment(ref this.m_Aborted) == 1)
         {
             LazyAsyncResult readAResult  = this.m_ReadAResult;
             LazyAsyncResult writeAResult = this.m_WriteAResult;
             WebException    result       = new WebException(NetRes.GetWebStatusString("net_requestaborted", WebExceptionStatus.RequestCanceled), WebExceptionStatus.RequestCanceled);
             Stream          stream       = this.m_stream;
             if ((readAResult != null) && !readAResult.IsCompleted)
             {
                 readAResult.InvokeCallback(result);
             }
             if ((writeAResult != null) && !writeAResult.IsCompleted)
             {
                 writeAResult.InvokeCallback(result);
             }
             if (stream != null)
             {
                 if (stream is ICloseEx)
                 {
                     ((ICloseEx)stream).CloseEx(CloseExState.Abort);
                 }
                 else
                 {
                     stream.Close();
                 }
             }
             if (this.m_response != null)
             {
                 ((ICloseEx)this.m_response).CloseEx(CloseExState.Abort);
             }
         }
     }
     catch (Exception exception2)
     {
         if (Logging.On)
         {
             Logging.Exception(Logging.Web, this, "Abort", exception2);
         }
         throw;
     }
 }
예제 #18
0
        public override void EndWrite(IAsyncResult asyncResult)
        {
            if (Logging.On)
            {
                Logging.Enter(Logging.HttpListener, this, "EndWrite", "");
            }
            GlobalLog.Print("HttpResponseStream#" + ValidationHelper.HashString(this) + "::EndWrite() asyncResult#" + ValidationHelper.HashString(asyncResult));
            if (asyncResult == null)
            {
                throw new ArgumentNullException("asyncResult");
            }
            HttpResponseStreamAsyncResult castedAsyncResult = asyncResult as HttpResponseStreamAsyncResult;

            if (castedAsyncResult == null || 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, "EndWrite"));
            }
            castedAsyncResult.EndCalled = true;
            // wait & then check for errors
            object returnValue = castedAsyncResult.InternalWaitForCompletion();

            Exception exception = returnValue as Exception;

            if (exception != null)
            {
                GlobalLog.Print("HttpResponseStream#" + ValidationHelper.HashString(this) + "::EndWrite() rethrowing exception:" + exception);
                if (Logging.On)
                {
                    Logging.Exception(Logging.HttpListener, this, "EndWrite", exception);
                }
                m_Closed = true;
                m_HttpContext.Abort();
                throw exception;
            }
            //


            GlobalLog.Print("HttpResponseStream#" + ValidationHelper.HashString(this) + "::EndWrite()");
            if (Logging.On)
            {
                Logging.Exit(Logging.HttpListener, this, "EndWrite", "");
            }
        }
예제 #19
0
        public override Stream EndGetRequestStream(IAsyncResult asyncResult)
        {
            GlobalLog.Enter("FileWebRequest::EndGetRequestStream");

            Stream stream;

#if !MONO
            bool success = false;
#endif
            try {
                LazyAsyncResult ar = asyncResult as LazyAsyncResult;
                if (asyncResult == null || ar == null)
                {
                    Exception e = asyncResult == null? new ArgumentNullException("asyncResult"): new ArgumentException(SR.GetString(SR.InvalidAsyncResult), "asyncResult");
                    GlobalLog.LeaveException("FileWebRequest::EndGetRequestStream", e);
                    throw e;
                }

                object result = ar.InternalWaitForCompletion();
                if (result is Exception)
                {
                    throw (Exception)result;
                }
                stream         = (Stream)result;
                m_writePending = false;
#if !MONO
                success = true;
#endif
            } catch (Exception exception) {
                if (Logging.On)
                {
                    Logging.Exception(Logging.Web, this, "EndGetRequestStream", exception);
                }
                throw;
            } finally {
                GlobalLog.Leave("FileWebRequest::EndGetRequestStream");
#if !MONO
                if (FrameworkEventSource.Log.IsEnabled())
                {
                    LogEndGetRequestStream(success, synchronous: false);
                }
#endif
            }

            return(stream);
        }
예제 #20
0
        public override IAsyncResult BeginGetResponse(AsyncCallback callback, object state)
        {
            GlobalLog.Enter("FileWebRequest::BeginGetResponse");
#if !MONO
            bool success = true;
#endif

            try {
                if (Aborted)
                {
                    throw ExceptionHelper.RequestAbortedException;
                }
                lock (this) {
                    if (m_readPending)
                    {
                        Exception e = new InvalidOperationException(SR.GetString(SR.net_repcall));
                        GlobalLog.LeaveException("FileWebRequest::BeginGetResponse", e);
                        throw e;
                    }
                    m_readPending = true;
                }

                m_WriteAResult = new LazyAsyncResult(this, state, callback);
                ThreadPool.QueueUserWorkItem(s_GetResponseCallback, m_WriteAResult);
            } catch (Exception exception) {
#if !MONO
                success = false;
#endif
                if (Logging.On)
                {
                    Logging.Exception(Logging.Web, this, "BeginGetResponse", exception);
                }
                throw;
            } finally {
#if !MONO
                if (FrameworkEventSource.Log.IsEnabled())
                {
                    LogBeginGetResponse(success, synchronous: false);
                }
#endif
                GlobalLog.Leave("FileWebRequest::BeginGetResponse");
            }

            return(m_WriteAResult);
        }
예제 #21
0
        public override int EndRead(IAsyncResult asyncResult)
        {
            if (Logging.On)
            {
                Logging.Enter(Logging.HttpListener, this, "EndRead", "");
            }
            if (asyncResult == null)
            {
                throw new ArgumentNullException("asyncResult");
            }
            HttpRequestStreamAsyncResult result = asyncResult as HttpRequestStreamAsyncResult;

            if ((result == null) || (result.AsyncObject != this))
            {
                throw new ArgumentException(SR.GetString("net_io_invalidasyncresult"), "asyncResult");
            }
            if (result.EndCalled)
            {
                throw new InvalidOperationException(SR.GetString("net_io_invalidendcall", new object[] { "EndRead" }));
            }
            result.EndCalled = true;
            object    obj2 = result.InternalWaitForCompletion();
            Exception e    = obj2 as Exception;

            if (e != null)
            {
                if (Logging.On)
                {
                    Logging.Exception(Logging.HttpListener, this, "EndRead", e);
                }
                throw e;
            }
            uint dataRead = (uint)obj2;

            this.UpdateAfterRead((uint)result.ErrorCode, dataRead);
            if (Logging.On)
            {
                Logging.Exit(Logging.HttpListener, this, "EndRead", "");
            }
            return((int)(dataRead + result.m_dataAlreadyRead));
        }
예제 #22
0
        internal static IPHostEntry InternalGetHostByAddress(IPAddress address, bool includeIPv6)
        {
            SocketError success = SocketError.Success;
            Exception   e       = null;

            if (Socket.LegacySupportsIPv6 || (includeIPv6 && ComNetOS.IsPostWin2K))
            {
                string name = TryGetNameInfo(address, out success);
                if (success == SocketError.Success)
                {
                    IPHostEntry entry;
                    success = TryGetAddrInfo(name, out entry);
                    if ((success != SocketError.Success) && Logging.On)
                    {
                        Logging.Exception(Logging.Sockets, "DNS", "InternalGetHostByAddress", new SocketException(success));
                    }
                    return(entry);
                }
                e = new SocketException(success);
            }
            else
            {
                if (address.AddressFamily == AddressFamily.InterNetworkV6)
                {
                    throw new SocketException(SocketError.ProtocolNotSupported);
                }
                int    addr          = (int)address.m_Address;
                IntPtr nativePointer = UnsafeNclNativeMethods.OSSOCK.gethostbyaddr(ref addr, Marshal.SizeOf(typeof(int)), ProtocolFamily.InterNetwork);
                if (nativePointer != IntPtr.Zero)
                {
                    return(NativeToHostEntry(nativePointer));
                }
                e = new SocketException();
            }
            if (Logging.On)
            {
                Logging.Exception(Logging.Sockets, "DNS", "InternalGetHostByAddress", e);
            }
            throw e;
        }
 public override IAsyncResult BeginGetRequestStream(AsyncCallback callback, object state)
 {
     try
     {
         if (this.Aborted)
         {
             throw ExceptionHelper.RequestAbortedException;
         }
         if (!this.CanGetRequestStream())
         {
             Exception exception = new ProtocolViolationException(SR.GetString("net_nouploadonget"));
             throw exception;
         }
         if (this.m_response != null)
         {
             Exception exception2 = new InvalidOperationException(SR.GetString("net_reqsubmitted"));
             throw exception2;
         }
         lock (this)
         {
             if (this.m_writePending)
             {
                 Exception exception3 = new InvalidOperationException(SR.GetString("net_repcall"));
                 throw exception3;
             }
             this.m_writePending = true;
         }
         this.m_ReadAResult = new LazyAsyncResult(this, state, callback);
         ThreadPool.QueueUserWorkItem(s_GetRequestStreamCallback, this.m_ReadAResult);
     }
     catch (Exception exception4)
     {
         if (Logging.On)
         {
             Logging.Exception(Logging.Web, this, "BeginGetRequestStream", exception4);
         }
         throw;
     }
     return(this.m_ReadAResult);
 }
예제 #24
0
        public override void EndWrite(IAsyncResult asyncResult)
        {
            if (Logging.On)
            {
                Logging.Enter(Logging.HttpListener, this, "EndWrite", "");
            }
            if (asyncResult == null)
            {
                throw new ArgumentNullException("asyncResult");
            }
            HttpResponseStreamAsyncResult result = asyncResult as HttpResponseStreamAsyncResult;

            if ((result == null) || (result.AsyncObject != this))
            {
                throw new ArgumentException(SR.GetString("net_io_invalidasyncresult"), "asyncResult");
            }
            if (result.EndCalled)
            {
                throw new InvalidOperationException(SR.GetString("net_io_invalidendcall", new object[] { "EndWrite" }));
            }
            result.EndCalled = true;
            object    obj2 = result.InternalWaitForCompletion();
            Exception e    = obj2 as Exception;

            if (e != null)
            {
                if (Logging.On)
                {
                    Logging.Exception(Logging.HttpListener, this, "EndWrite", e);
                }
                this.m_HttpContext.Abort();
                throw e;
            }
            this.UpdateAfterWrite((uint)obj2);
            if (Logging.On)
            {
                Logging.Exit(Logging.HttpListener, this, "EndWrite", "");
            }
        }
 private void Cleanup()
 {
     lock (lockObject)
     {
         if (!this.cleanupCalled)
         {
             this.cleanupCalled = true;
             if (this.counters != null)
             {
                 foreach (CounterPair pair in this.counters)
                 {
                     if (!Environment.HasShutdownStarted && (pair != null))
                     {
                         try
                         {
                             pair.InstanceCounter.RemoveInstance();
                         }
                         catch (InvalidOperationException exception)
                         {
                             if (Logging.On)
                             {
                                 Logging.Exception(Logging.Web, "NetworkingPerfCounters", "Cleanup", exception);
                             }
                         }
                         catch (Win32Exception exception2)
                         {
                             if (Logging.On)
                             {
                                 Logging.Exception(Logging.Web, "NetworkingPerfCounters", "Cleanup", exception2);
                             }
                         }
                     }
                 }
             }
         }
     }
 }
예제 #26
0
        public override void Write(byte[] buffer, int offset, int size)
        {
            if (Logging.On)
            {
                Logging.Enter(Logging.HttpListener, this, "Write", "");
            }
            GlobalLog.Print("HttpResponseStream#" + ValidationHelper.HashString(this) + "::Write() buffer.Length:" + buffer.Length + " size:" + size + " offset:" + offset);
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }
            if (offset < 0 || offset > buffer.Length)
            {
                throw new ArgumentOutOfRangeException("offset");
            }
            if (size < 0 || size > buffer.Length - offset)
            {
                throw new ArgumentOutOfRangeException("size");
            }
            UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS flags = ComputeLeftToWrite();
            if (m_Closed || (size == 0 && m_LeftToWrite != 0))
            {
                if (Logging.On)
                {
                    Logging.Exit(Logging.HttpListener, this, "Write", "");
                }
                return;
            }
            if (m_LeftToWrite >= 0 && size > m_LeftToWrite)
            {
                throw new ProtocolViolationException(SR.GetString(SR.net_entitytoobig));
            }

            uint          statusCode;
            uint          dataToWrite     = (uint)size;
            SafeLocalFree bufferAsIntPtr  = null;
            IntPtr        pBufferAsIntPtr = IntPtr.Zero;
            bool          sentHeaders     = m_HttpContext.Response.SentHeaders;

            try {
                if (size == 0)
                {
                    statusCode = m_HttpContext.Response.SendHeaders(null, null, flags, false);
                }
                else
                {
                    fixed(byte *pDataBuffer = buffer)
                    {
                        byte *pBuffer = pDataBuffer;

                        if (m_HttpContext.Response.BoundaryType == BoundaryType.Chunked)
                        {
                            //


                            string chunkHeader = size.ToString("x", CultureInfo.InvariantCulture);
                            dataToWrite     = dataToWrite + (uint)(chunkHeader.Length + 4);
                            bufferAsIntPtr  = SafeLocalFree.LocalAlloc((int)dataToWrite);
                            pBufferAsIntPtr = bufferAsIntPtr.DangerousGetHandle();
                            for (int i = 0; i < chunkHeader.Length; i++)
                            {
                                Marshal.WriteByte(pBufferAsIntPtr, i, (byte)chunkHeader[i]);
                            }
                            Marshal.WriteInt16(pBufferAsIntPtr, chunkHeader.Length, 0x0A0D);
                            Marshal.Copy(buffer, offset, IntPtrHelper.Add(pBufferAsIntPtr, chunkHeader.Length + 2), size);
                            Marshal.WriteInt16(pBufferAsIntPtr, (int)(dataToWrite - 2), 0x0A0D);
                            pBuffer = (byte *)pBufferAsIntPtr;
                            offset  = 0;
                        }
                        UnsafeNclNativeMethods.HttpApi.HTTP_DATA_CHUNK dataChunk = new UnsafeNclNativeMethods.HttpApi.HTTP_DATA_CHUNK();
                        dataChunk.DataChunkType = UnsafeNclNativeMethods.HttpApi.HTTP_DATA_CHUNK_TYPE.HttpDataChunkFromMemory;
                        dataChunk.pBuffer       = (byte *)(pBuffer + offset);
                        dataChunk.BufferLength  = dataToWrite;

                        flags |= m_LeftToWrite == size ? UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS.NONE : UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS.HTTP_SEND_RESPONSE_FLAG_MORE_DATA;
                        if (!sentHeaders)
                        {
                            statusCode = m_HttpContext.Response.SendHeaders(&dataChunk, null, flags, false);
                        }
                        else
                        {
                            GlobalLog.Print("HttpResponseStream#" + ValidationHelper.HashString(this) + "::Write() calling UnsafeNclNativeMethods.HttpApi.HttpSendResponseEntityBody");

                            statusCode =
                                UnsafeNclNativeMethods.HttpApi.HttpSendResponseEntityBody(
                                    m_HttpContext.RequestQueueHandle,
                                    m_HttpContext.RequestId,
                                    (uint)flags,
                                    1,
                                    &dataChunk,
                                    null,
                                    SafeLocalFree.Zero,
                                    0,
                                    null,
                                    null);

                            GlobalLog.Print("HttpResponseStream#" + ValidationHelper.HashString(this) + "::Write() call to UnsafeNclNativeMethods.HttpApi.HttpSendResponseEntityBody returned:" + statusCode);
                            if (m_HttpContext.Listener.IgnoreWriteExceptions)
                            {
                                GlobalLog.Print("HttpResponseStream#" + ValidationHelper.HashString(this) + "::Write() suppressing error");
                                statusCode = UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS;
                            }
                        }
                    }
                }
            }
            finally {
                if (bufferAsIntPtr != null)
                {
                    // free unmanaged buffer
                    bufferAsIntPtr.Close();
                }
            }

            if (statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS && statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_HANDLE_EOF)
            {
                Exception exception = new HttpListenerException((int)statusCode);
                if (Logging.On)
                {
                    Logging.Exception(Logging.HttpListener, this, "Write", exception);
                }
                m_Closed = true;
                m_HttpContext.Abort();
                throw exception;
            }
            UpdateAfterWrite(dataToWrite);
            if (Logging.On)
            {
                Logging.Dump(Logging.HttpListener, this, "Write", buffer, offset, (int)dataToWrite);
            }
            if (Logging.On)
            {
                Logging.Exit(Logging.HttpListener, this, "Write", "");
            }
        }
예제 #27
0
        protected override void Dispose(bool disposing)
        {
            if (Logging.On)
            {
                Logging.Enter(Logging.HttpListener, this, "Close", "");
            }

            try {
                if (disposing)
                {
                    GlobalLog.Print("HttpResponseStream#" + ValidationHelper.HashString(this) + "::Close() m_Closed:" + m_Closed);
                    if (m_Closed)
                    {
                        if (Logging.On)
                        {
                            Logging.Exit(Logging.HttpListener, this, "Close", "");
                        }
                        return;
                    }
                    m_Closed = true;
                    UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS flags = ComputeLeftToWrite();
                    if (m_LeftToWrite > 0 && !m_InOpaqueMode)
                    {
                        throw new InvalidOperationException(SR.GetString(SR.net_io_notenoughbyteswritten));
                    }
                    bool sentHeaders = m_HttpContext.Response.SentHeaders;
                    if (sentHeaders && m_LeftToWrite == 0)
                    {
                        if (Logging.On)
                        {
                            Logging.Exit(Logging.HttpListener, this, "Close", "");
                        }
                        return;
                    }

                    uint statusCode = 0;
                    if ((m_HttpContext.Response.BoundaryType == BoundaryType.Chunked || m_HttpContext.Response.BoundaryType == BoundaryType.None) && (String.Compare(m_HttpContext.Request.HttpMethod, "HEAD", StringComparison.OrdinalIgnoreCase) != 0))
                    {
                        if (m_HttpContext.Response.BoundaryType == BoundaryType.None)
                        {
                            flags |= UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS.HTTP_SEND_RESPONSE_FLAG_DISCONNECT;
                        }
                        fixed(void *pBuffer = NclConstants.ChunkTerminator)
                        {
                            UnsafeNclNativeMethods.HttpApi.HTTP_DATA_CHUNK *pDataChunk = null;
                            if (m_HttpContext.Response.BoundaryType == BoundaryType.Chunked)
                            {
                                UnsafeNclNativeMethods.HttpApi.HTTP_DATA_CHUNK dataChunk = new UnsafeNclNativeMethods.HttpApi.HTTP_DATA_CHUNK();
                                dataChunk.DataChunkType = UnsafeNclNativeMethods.HttpApi.HTTP_DATA_CHUNK_TYPE.HttpDataChunkFromMemory;
                                dataChunk.pBuffer       = (byte *)pBuffer;
                                dataChunk.BufferLength  = (uint)NclConstants.ChunkTerminator.Length;
                                pDataChunk = &dataChunk;
                            }
                            if (!sentHeaders)
                            {
                                statusCode = m_HttpContext.Response.SendHeaders(pDataChunk, null, flags, false);
                            }
                            else
                            {
                                GlobalLog.Print("HttpResponseStream#" + ValidationHelper.HashString(this) + "::Close() calling UnsafeNclNativeMethods.HttpApi.HttpSendResponseEntityBody");

                                statusCode =
                                    UnsafeNclNativeMethods.HttpApi.HttpSendResponseEntityBody(
                                        m_HttpContext.RequestQueueHandle,
                                        m_HttpContext.RequestId,
                                        (uint)flags,
                                        pDataChunk != null ? (ushort)1 : (ushort)0,
                                        pDataChunk,
                                        null,
                                        SafeLocalFree.Zero,
                                        0,
                                        null,
                                        null);

                                GlobalLog.Print("HttpResponseStream#" + ValidationHelper.HashString(this) + "::Close() call to UnsafeNclNativeMethods.HttpApi.HttpSendResponseEntityBody returned:" + statusCode);
                                if (m_HttpContext.Listener.IgnoreWriteExceptions)
                                {
                                    GlobalLog.Print("HttpResponseStream#" + ValidationHelper.HashString(this) + "::Close() suppressing error");
                                    statusCode = UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS;
                                }
                            }
                        }
                    }
                    else
                    {
                        if (!sentHeaders)
                        {
                            statusCode = m_HttpContext.Response.SendHeaders(null, null, flags, false);
                        }
                    }
                    if (statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS && statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_HANDLE_EOF)
                    {
                        Exception exception = new HttpListenerException((int)statusCode);
                        if (Logging.On)
                        {
                            Logging.Exception(Logging.HttpListener, this, "Close", exception);
                        }
                        m_HttpContext.Abort();
                        throw exception;
                    }
                    m_LeftToWrite = 0;
                }
            }
            finally {
                base.Dispose(disposing);
            }
            if (Logging.On)
            {
                Logging.Exit(Logging.HttpListener, this, "Dispose", "");
            }
        }
예제 #28
0
        } // GetHostByAddress
        
        // Does internal IPAddress reverse and then forward lookups (for Legacy and current public methods).
        // Legacy methods do not include IPv6, unless configed to by Socket.LegacySupportsIPv6 and Socket.OSSupportsIPv6.
        internal static IPHostEntry InternalGetHostByAddress(IPAddress address, bool includeIPv6)
        {
            GlobalLog.Print("Dns.InternalGetHostByAddress: " + address.ToString());
            //
            // IPv6 Changes: We need to use the new getnameinfo / getaddrinfo functions
            //               for resolution of IPv6 addresses.
            //

            SocketError errorCode = SocketError.Success;
            Exception exception = null;
            if ( Socket.LegacySupportsIPv6 || includeIPv6) {
                //
                // Try to get the data for the host from it's address
                //
                // We need to call getnameinfo first, because getaddrinfo w/ the ipaddress string
                // will only return that address and not the full list.

                // Do a reverse lookup to get the host name.
                string name = TryGetNameInfo(address, out errorCode);
                if(errorCode == SocketError.Success) {

                    // Do the forward lookup to get the IPs for that host name
                    IPHostEntry hostEntry;
                    errorCode = TryGetAddrInfo(name, out hostEntry);
                    if (errorCode == SocketError.Success)
                        return hostEntry;

                    // Log failure
                    if (Logging.On) Logging.Exception(Logging.Sockets, "DNS", 
                        "InternalGetHostByAddress", new SocketException(errorCode));

                    // One of two things happened:
                    // 1. There was a ptr record in dns, but not a corollary A/AAA record.
                    // 2. The IP was a local (non-loopback) IP that resolved to a connection specific dns suffix.
                    //    - Workaround, Check "Use this connection's dns suffix in dns registration" on that network
                    //      adapter's advanced dns settings.

                    // Just return the resolved host name and no IPs.
                    return hostEntry;
                }
                exception = new SocketException(errorCode);
            }

            //
            // If IPv6 is not enabled (maybe config switch) but we've been
            // given an IPv6 address then we need to bail out now.
            //
            else {
                if ( address.AddressFamily == AddressFamily.InterNetworkV6 ) {
                    //
                    // Protocol not supported
                    //
                    throw new SocketException(SocketError.ProtocolNotSupported);
                }
                //
                // Use gethostbyaddr() to try to resolve the IP address
                //
                // End IPv6 Changes
                //
                int addressAsInt = unchecked((int)address.m_Address);
    
    #if BIGENDIAN
                addressAsInt = (int)( ((uint)addressAsInt << 24) | (((uint)addressAsInt & 0x0000FF00) << 8) |
                    (((uint)addressAsInt >> 8) & 0x0000FF00) | ((uint)addressAsInt >> 24) );
    #endif
    
                IntPtr nativePointer =
                    UnsafeNclNativeMethods.OSSOCK.gethostbyaddr(
                        ref addressAsInt,
                        Marshal.SizeOf(typeof(int)),
                        ProtocolFamily.InterNetwork);
    
    
                if (nativePointer != IntPtr.Zero) {
                    return NativeToHostEntry(nativePointer);
                }
                exception = new SocketException();
            }

            if (Logging.On) Logging.Exception(Logging.Sockets, "DNS", "InternalGetHostByAddress", exception);
            throw exception;
        } // InternalGetHostByAddress
예제 #29
0
파일: DNS.cs 프로젝트: thiagodin/corefx
        } // GetHostByName

        // Does internal IPAddress reverse and then forward lookups (for Legacy and current public methods).
        internal static IPHostEntry InternalGetHostByAddress(IPAddress address, bool includeIPv6)
        {
            GlobalLog.Print("Dns.InternalGetHostByAddress: " + address.ToString());
            //
            // IPv6 Changes: We need to use the new getnameinfo / getaddrinfo functions
            //               for resolution of IPv6 addresses.
            //

            if (SocketProtocolSupportPal.OSSupportsIPv6 || includeIPv6)
            {
                //
                // Try to get the data for the host from it's address
                //
                // We need to call getnameinfo first, because getaddrinfo w/ the ipaddress string
                // will only return that address and not the full list.

                // Do a reverse lookup to get the host name.
                SocketError errorCode;
                int         nativeErrorCode;
                string      name = NameResolutionPal.TryGetNameInfo(address, out errorCode, out nativeErrorCode);
                if (errorCode == SocketError.Success)
                {
                    // Do the forward lookup to get the IPs for that host name
                    IPHostEntry hostEntry;
                    errorCode = NameResolutionPal.TryGetAddrInfo(name, out hostEntry, out nativeErrorCode);
                    if (errorCode == SocketError.Success)
                    {
                        return(hostEntry);
                    }

                    if (Logging.On)
                    {
                        Logging.Exception(Logging.Sockets, "DNS",
                                          "InternalGetHostByAddress", new InternalSocketException(errorCode, nativeErrorCode));
                    }

                    // One of two things happened:
                    // 1. There was a ptr record in dns, but not a corollary A/AAA record.
                    // 2. The IP was a local (non-loopback) IP that resolved to a connection specific dns suffix.
                    //    - Workaround, Check "Use this connection's dns suffix in dns registration" on that network
                    //      adapter's advanced dns settings.

                    // Just return the resolved host name and no IPs.
                    return(hostEntry);
                }
                throw new InternalSocketException(errorCode, nativeErrorCode);
            }

            //
            // If IPv6 is not enabled (maybe config switch) but we've been
            // given an IPv6 address then we need to bail out now.
            //
            else
            {
                if (address.AddressFamily == AddressFamily.InterNetworkV6)
                {
                    //
                    // Protocol not supported
                    //
                    throw new SocketException((int)SocketError.ProtocolNotSupported);
                }
                //
                // Use gethostbyaddr() to try to resolve the IP address
                //
                // End IPv6 Changes
                //
                return(NameResolutionPal.GetHostByAddr(address));
            }
        } // InternalGetHostByAddress
예제 #30
0
        public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, object state)
        {
            GlobalLog.Print("HttpResponseStream#" + ValidationHelper.HashString(this) + "::BeginWrite() buffer.Length:" + buffer.Length + " size:" + size + " offset:" + offset);
            if (buffer == null)
            {
                throw new ArgumentNullException("buffer");
            }
            if (offset < 0 || offset > buffer.Length)
            {
                throw new ArgumentOutOfRangeException("offset");
            }
            if (size < 0 || size > buffer.Length - offset)
            {
                throw new ArgumentOutOfRangeException("size");
            }
            UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS flags = ComputeLeftToWrite();
            if (m_Closed || (size == 0 && m_LeftToWrite != 0))
            {
                if (Logging.On)
                {
                    Logging.Exit(Logging.HttpListener, this, "BeginWrite", "");
                }
                HttpResponseStreamAsyncResult result = new HttpResponseStreamAsyncResult(this, state, callback);
                result.InvokeCallback((uint)0);
                return(result);
            }
            if (m_LeftToWrite >= 0 && size > m_LeftToWrite)
            {
                throw new ProtocolViolationException(SR.GetString(SR.net_entitytoobig));
            }

            uint statusCode;
            uint bytesSent = 0;

            flags |= m_LeftToWrite == size ? UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS.NONE : UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS.HTTP_SEND_RESPONSE_FLAG_MORE_DATA;
            bool sentHeaders = m_HttpContext.Response.SentHeaders;
            HttpResponseStreamAsyncResult asyncResult = new HttpResponseStreamAsyncResult(this, state, callback, buffer, offset, size, m_HttpContext.Response.BoundaryType == BoundaryType.Chunked, sentHeaders);

            // Update m_LeftToWrite now so we can queue up additional BeginWrite's without waiting for EndWrite.
            UpdateAfterWrite((uint)((m_HttpContext.Response.BoundaryType == BoundaryType.Chunked) ? 0 : size));

            try {
                if (!sentHeaders)
                {
                    statusCode = m_HttpContext.Response.SendHeaders(null, asyncResult, flags, false);
                }
                else
                {
                    GlobalLog.Print("HttpResponseStream#" + ValidationHelper.HashString(this) + "::BeginWrite() calling UnsafeNclNativeMethods.HttpApi.HttpSendResponseEntityBody");

                    m_HttpContext.EnsureBoundHandle();
                    statusCode =
                        UnsafeNclNativeMethods.HttpApi.HttpSendResponseEntityBody(
                            m_HttpContext.RequestQueueHandle,
                            m_HttpContext.RequestId,
                            (uint)flags,
                            asyncResult.dataChunkCount,
                            asyncResult.pDataChunks,
                            &bytesSent,
                            SafeLocalFree.Zero,
                            0,
                            asyncResult.m_pOverlapped,
                            null);

                    GlobalLog.Print("HttpResponseStream#" + ValidationHelper.HashString(this) + "::BeginWrite() call to UnsafeNclNativeMethods.HttpApi.HttpSendResponseEntityBody returned:" + statusCode);
                }
            }
            catch (Exception e) {
                if (Logging.On)
                {
                    Logging.Exception(Logging.HttpListener, this, "BeginWrite", e);
                }
                asyncResult.InternalCleanup();
                m_Closed = true;
                m_HttpContext.Abort();
                throw;
            }

            if (statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS && statusCode != UnsafeNclNativeMethods.ErrorCodes.ERROR_IO_PENDING)
            {
                asyncResult.InternalCleanup();
                if (m_HttpContext.Listener.IgnoreWriteExceptions && sentHeaders)
                {
                    GlobalLog.Print("HttpResponseStream#" + ValidationHelper.HashString(this) + "::BeginWrite() suppressing error");
                }
                else
                {
                    Exception exception = new HttpListenerException((int)statusCode);
                    if (Logging.On)
                    {
                        Logging.Exception(Logging.HttpListener, this, "BeginWrite", exception);
                    }
                    m_Closed = true;
                    m_HttpContext.Abort();
                    throw exception;
                }
            }

            if (statusCode == UnsafeNclNativeMethods.ErrorCodes.ERROR_SUCCESS && HttpListener.SkipIOCPCallbackOnSuccess)
            {
                // IO operation completed synchronously - callback won't be called to signal completion.
                asyncResult.IOCompleted(statusCode, bytesSent);
            }

            // Last write, cache it for special cancelation handling.
            if ((flags & UnsafeNclNativeMethods.HttpApi.HTTP_FLAGS.HTTP_SEND_RESPONSE_FLAG_MORE_DATA) == 0)
            {
                m_LastWrite = asyncResult;
            }

            if (Logging.On)
            {
                Logging.Exit(Logging.HttpListener, this, "BeginWrite", "");
            }
            return(asyncResult);
        }