예제 #1
0
        // Async patern

        internal /*public*/ IAsyncResult BeginAspCompatExecution(AsyncCallback cb, object extraData)
        {
            InternalSecurityPermissions.UnmanagedCode.Demand();

            if (IsInAspCompatMode)
            {
                // already in AspCompatMode -- execute synchronously
                bool      sync  = true;
                Exception error = _app.ExecuteStep(this, ref sync);
                _ar         = new HttpAsyncResult(cb, extraData, true, null, error);
                _syncCaller = true;
            }
            else
            {
                _ar         = new HttpAsyncResult(cb, extraData);
                _syncCaller = (cb == null);
                _rootedThis = GCHandle.Alloc(this);

                if (UnsafeNativeMethods.AspCompatProcessRequest(_execCallback, this) != 1)
                {
                    // failed to queue up the execution in ASP compat mode
                    _rootedThis.Free();
                    _ar.Complete(true, null, new HttpException(HttpRuntime.FormatResourceString(SR.Cannot_access_AspCompat)));
                }
            }

            return(_ar);
        }
예제 #2
0
        internal override IAsyncResult BeginExecuteUrl(string url, string method, string childHeaders, bool sendHeaders, bool addUserIndo, IntPtr token, string name, string authType, byte[] entity, AsyncCallback cb, object state)
        {
            if (((base._ecb == IntPtr.Zero) || (this._asyncResultOfExecuteUrl != null)) || (sendHeaders && this.HeadersSent()))
            {
                throw new InvalidOperationException(System.Web.SR.GetString("Cannot_execute_url_in_this_context"));
            }
            if (((entity != null) && (entity.Length > 0)) && (UnsafeNativeMethods.EcbGetExecUrlEntityInfo(entity.Length, entity, out this._entity) != 1))
            {
                throw new HttpException(System.Web.SR.GetString("Failed_to_execute_url"));
            }
            HttpAsyncResult result = new HttpAsyncResult(cb, state);

            this._asyncResultOfExecuteUrl      = result;
            this._executeUrlCompletionCallback = new ISAPIAsyncCompletionCallback(this.OnExecuteUrlCompletion);
            this._rootedThis = GCHandle.Alloc(this);
            if (UnsafeNativeMethods.EcbExecuteUrlUnicode(base._ecb, url, method, childHeaders, sendHeaders, addUserIndo, token, name, authType, this._entity, this._executeUrlCompletionCallback) != 1)
            {
                if (this._entity != IntPtr.Zero)
                {
                    UnsafeNativeMethods.EcbFreeExecUrlEntityInfo(this._entity);
                }
                this._rootedThis.Free();
                this._asyncResultOfExecuteUrl = null;
                throw new HttpException(System.Web.SR.GetString("Failed_to_execute_url"));
            }
            if (sendHeaders)
            {
                this._headersSentFromExecuteUrl = true;
            }
            return(result);
        }
예제 #3
0
        internal /*public*/ IAsyncResult BeginAspCompatExecution(AsyncCallback cb, object extraData)
        {
            SynchronizationContextUtil.ValidateModeForAspCompat();

            if (IsInAspCompatMode)
            {
                // already in AspCompatMode -- execute synchronously
                bool      sync  = true;
                Exception error = _app.ExecuteStep(this, ref sync);
                _ar         = new HttpAsyncResult(cb, extraData, true, null, error);
                _syncCaller = true;
            }
            else
            {
                _ar         = new HttpAsyncResult(cb, extraData);
                _syncCaller = (cb == null);
                _rootedThis = GCHandle.Alloc(this);

                // send requests from the same session to the same STA thread
                bool sharedActivity = (_sessionId != null);
                int  activityHash   = sharedActivity ? _sessionId.GetHashCode() : 0;

                if (UnsafeNativeMethods.AspCompatProcessRequest(_execCallback, this, sharedActivity, activityHash) != 1)
                {
                    // failed to queue up the execution in ASP compat mode
                    _rootedThis.Free();
                    _ar.Complete(true, null, new HttpException(SR.GetString(SR.Cannot_access_AspCompat)));
                }
            }

            return(_ar);
        }
예제 #4
0
        internal override void EndExecuteUrl(IAsyncResult result)
        {
            HttpAsyncResult result2 = result as HttpAsyncResult;

            if (result2 != null)
            {
                result2.End();
            }
        }
예제 #5
0
        private void OnExecuteUrlCompletion(IntPtr ecb, int byteCount, int error)
        {
            if (this._entity != IntPtr.Zero)
            {
                UnsafeNativeMethods.EcbFreeExecUrlEntityInfo(this._entity);
            }
            this._rootedThis.Free();
            HttpAsyncResult result = this._asyncResultOfExecuteUrl;

            this._asyncResultOfExecuteUrl = null;
            result.Complete(false, null, null);
        }
예제 #6
0
        protected override IAsyncResult BeginSendCore(ServiceRequest serviceRequest, ExecutionContext context, AsyncCallback callback, object state)
        {
            var request = HttpFactory.CreateWebRequest(serviceRequest, Configuration);

            var asyncResult = new HttpAsyncResult(callback, state)
            {
                WebRequest = request,
                Context    = context,
                Request    = serviceRequest
            };

            BeginSetRequestContent(request, serviceRequest, () => request.BeginGetResponse(OnGetResponseCompleted, asyncResult), Configuration, asyncResult);
            return(asyncResult);
        }
        internal HttpAsyncResult ExecuteTasks(AsyncCallback callback, Object extraData)
        {
            _failedToStart     = false;
            _timeoutEnd        = DateTime.UtcNow + _page.AsyncTimeout;
            _timeoutEndReached = false;
            _tasksStarted      = 0;
            _tasksCompleted    = 0;

            _asyncResult = new HttpAsyncResult(callback, extraData);

            bool waitUntilDone = (callback == null);

            if (waitUntilDone)
            {
                // when requested to wait for tasks, before starting tasks
                // make sure that the lock can be suspended.
                try {} finally {
                    try {
                        // disassociating allows other pending work to take place, and associating will block until that work is complete
                        _app.Context.SyncContext.DisassociateFromCurrentThread();
                        _app.Context.SyncContext.AssociateWithCurrentThread();
                    }
                    catch (SynchronizationLockException) {
                        _failedToStart = true;
                        throw new InvalidOperationException(SR.GetString(SR.Async_tasks_wrong_thread));
                    }
                }
            }

            _inProgress = true;

            try {
                // all work done here:
                ResumeTasks(waitUntilDone, true /*onCallerThread*/);
            }
            finally {
                if (waitUntilDone)
                {
                    _inProgress = false;
                }
            }

            return(_asyncResult);
        }
예제 #8
0
        internal HttpAsyncResult ExecuteTasks(AsyncCallback callback, object extraData)
        {
            this._failedToStart     = false;
            this._timeoutEnd        = DateTime.UtcNow + this._page.AsyncTimeout;
            this._timeoutEndReached = false;
            this._tasksStarted      = 0;
            this._tasksCompleted    = 0;
            this._asyncResult       = new HttpAsyncResult(callback, extraData);
            bool waitUntilDone = callback == null;

            if (waitUntilDone)
            {
                try
                {
                }
                finally
                {
                    try
                    {
                        Monitor.Exit(this._app);
                        Monitor.Enter(this._app);
                    }
                    catch (SynchronizationLockException)
                    {
                        this._failedToStart = true;
                        throw new InvalidOperationException(System.Web.SR.GetString("Async_tasks_wrong_thread"));
                    }
                }
            }
            this._inProgress = true;
            try
            {
                this.ResumeTasks(waitUntilDone, true);
            }
            finally
            {
                if (waitUntilDone)
                {
                    this._inProgress = false;
                }
            }
            return(this._asyncResult);
        }
예제 #9
0
 internal IAsyncResult BeginAspCompatExecution(AsyncCallback cb, object extraData)
 {
     if (IsInAspCompatMode)
     {
         bool      completedSynchronously = true;
         Exception error = this._app.ExecuteStep(this, ref completedSynchronously);
         this._ar         = new HttpAsyncResult(cb, extraData, true, null, error);
         this._syncCaller = true;
     }
     else
     {
         this._ar         = new HttpAsyncResult(cb, extraData);
         this._syncCaller = cb == null;
         this._rootedThis = GCHandle.Alloc(this);
         bool sharedActivity = this._sessionId != null;
         int  activityHash   = sharedActivity ? this._sessionId.GetHashCode() : 0;
         if (System.Web.UnsafeNativeMethods.AspCompatProcessRequest(this._execCallback, this, sharedActivity, activityHash) != 1)
         {
             this._rootedThis.Free();
             this._ar.Complete(true, null, new HttpException(System.Web.SR.GetString("Cannot_access_AspCompat")));
         }
     }
     return(this._ar);
 }
 private void ResetPerRequestFields()
 {
     this._rqSessionState                 = null;
     this._rqId                           = null;
     this._rqSessionItems                 = null;
     this._rqStaticObjects                = null;
     this._rqIsNewSession                 = false;
     this._rqSessionStateNotFound         = true;
     this._rqReadonly                     = false;
     this._rqItem                         = null;
     this._rqContext                      = null;
     this._rqAr                           = null;
     this._rqLockId                       = null;
     this._rqInCallback                   = 0;
     this._rqLastPollCompleted            = DateTime.MinValue;
     this._rqExecutionTimeout             = TimeSpan.Zero;
     this._rqAddedCookie                  = false;
     this._rqIdNew                        = false;
     this._rqActionFlags                  = SessionStateActions.None;
     this._rqIctx                         = null;
     this._rqChangeImpersonationRefCount  = 0;
     this._rqTimerThreadImpersonationIctx = null;
     this._rqSupportSessionIdReissue      = false;
 }
        private static void BeginSetRequestContent(HttpWebRequest webRequest, ServiceRequest serviceRequest,
                                                   OssAction asyncCallback, ClientConfiguration clientConfiguration, HttpAsyncResult result)
        {
            var data = serviceRequest.BuildRequestContent();

            if (data == null ||
                (serviceRequest.Method != HttpMethod.Put &&
                 serviceRequest.Method != HttpMethod.Post))
            {
                // Skip setting content body in this case.
                try
                {
                    asyncCallback();
                }
                catch (Exception e)
                {
                    result.WebRequest.Abort();
                    result.Complete(e);
                }

                return;
            }

            // Write data to the request stream.
            long userSetContentLength = -1;

            if (serviceRequest.Headers.ContainsKey(HttpHeaders.ContentLength))
            {
                userSetContentLength = long.Parse(serviceRequest.Headers[HttpHeaders.ContentLength]);
            }

            if (serviceRequest.UseChunkedEncoding || !data.CanSeek) // when data cannot seek, we have to use chunked encoding as there's no way to set the length
            {
                webRequest.SendChunked = true;
                webRequest.AllowWriteStreamBuffering = false; // when using chunked encoding, the data is likely big and thus not use write buffer;
            }
            else
            {
                long streamLength = data.Length - data.Position;
                webRequest.ContentLength = (userSetContentLength >= 0 &&
                                            userSetContentLength <= streamLength) ? userSetContentLength : streamLength;
                if (webRequest.ContentLength > clientConfiguration.DirectWriteStreamThreshold)
                {
                    webRequest.AllowWriteStreamBuffering = false;
                }
            }

            webRequest.BeginGetRequestStream(
                (ar) =>
            {
                try
                {
                    using (var requestStream = webRequest.EndGetRequestStream(ar))
                    {
                        if (!webRequest.SendChunked)
                        {
                            IoUtils.WriteTo(data, requestStream, webRequest.ContentLength);
                        }
                        else
                        {
                            IoUtils.WriteTo(data, requestStream);
                        }
                    }
                    asyncCallback();
                }
                catch (Exception e)
                {
                    result.WebRequest.Abort();
                    result.Complete(e);
                }
            }, null);
        }
예제 #12
0
        /*
         * Acquire session state
         */
        IAsyncResult BeginAcquireState(Object source, EventArgs e, AsyncCallback cb, Object extraData) {
            bool                requiresState;
            bool                isCompleted = true;
            bool                skipReadingId = false;

            Debug.Trace("SessionStateModuleOnAcquireState", "Beginning SessionStateModule::OnAcquireState");

            _acquireCalled = true;
            _releaseCalled = false;
            ResetPerRequestFields();

            _rqContext = ((HttpApplication)source).Context;
            _rqAr = new HttpAsyncResult(cb, extraData);

            ChangeImpersonation(_rqContext, false);

            try {
                if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Information, EtwTraceFlags.AppSvc)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_SESSION_DATA_BEGIN, _rqContext.WorkerRequest);

                /* Notify the store we are beginning to get process request */
                _store.InitializeRequest(_rqContext);

                /* determine if the request requires state at all */
                requiresState = _rqContext.RequiresSessionState;

                // SessionIDManager may need to do a redirect if cookieless setting is AutoDetect
                if (_idManager.InitializeRequest(_rqContext, false, out _rqSupportSessionIdReissue)) {
                    _rqAr.Complete(true, null, null);
                    if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Information, EtwTraceFlags.AppSvc)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_SESSION_DATA_END, _rqContext.WorkerRequest);
                    return _rqAr;
                }

                // See if we can skip reading the session id.  See inline doc of s_allowInProcOptimization
                // for details.
                if (s_allowInProcOptimization &&
                    !s_sessionEverSet &&
                     (!requiresState ||             // Case 1
                      !((SessionIDManager)_idManager).UseCookieless(_rqContext)) ) {  // Case 2

                    skipReadingId = true;

#if DBG
                    if (!requiresState) {
                        // Case 1
                        Debug.Trace("SessionStateModuleOnAcquireState", "Skip reading id because page has disabled session state");
                    }
                    else {
                        // Case 2
                        Debug.Trace("SessionStateModuleOnAcquireState", "Delay reading id because we're using InProc optimization, and we are not using cookieless");
                    }
#endif
                }
                else {
                    /* Get sessionid */
                    _rqId = _idManager.GetSessionID(_rqContext);
                    Debug.Trace("SessionStateModuleOnAcquireState", "Current request id=" + _rqId);
                }

                if (!requiresState) {
                    if (_rqId == null) {
                        Debug.Trace("SessionStateModuleOnAcquireState",
                                    "Handler does not require state, " +
                                    "session id skipped or no id found, " +
                                    "skipReadingId=" + skipReadingId +
                                    "\nReturning from SessionStateModule::OnAcquireState");
                    }
                    else {
                        Debug.Trace("SessionStateModuleOnAcquireState",
                                    "Handler does not require state, " +
                                    "resetting timeout for SessionId=" + _rqId +
                                    "\nReturning from SessionStateModule::OnAcquireState");

                        // Still need to update the sliding timeout to keep session alive.
                        // There is a plan to skip this for perf reason.  But it was postponed to
                        // after Whidbey.
                        _store.ResetItemTimeout(_rqContext, _rqId);
                    }

                    _rqAr.Complete(true, null, null);

                    if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Information, EtwTraceFlags.AppSvc)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_SESSION_DATA_END, _rqContext.WorkerRequest);
                    return _rqAr;
                }

                _rqExecutionTimeout = _rqContext.Timeout;

                // If the page is marked as DEBUG, HttpContext.Timeout will return a very large value (~1 year)
                // In this case, we want to use the executionTimeout value specified in the config to avoid
                // PollLockedSession to run forever.
                if (_rqExecutionTimeout == DEFAULT_DBG_EXECUTION_TIMEOUT) {
                    _rqExecutionTimeout = s_configExecutionTimeout;
                }

                /* determine if we need just read-only access */
                _rqReadonly = _rqContext.ReadOnlySessionState;

                if (_rqId != null) {
                    /* get the session state corresponding to this session id */
                    isCompleted = GetSessionStateItem();
                }
                else if (!skipReadingId) {
                    /* if there's no id yet, create it */
                    bool    redirected = CreateSessionId();

                    _rqIdNew = true;

                    if (redirected) {
                        if (s_configRegenerateExpiredSessionId) {
                            // See inline comments in CreateUninitializedSessionState()
                            CreateUninitializedSessionState();
                        }

                        _rqAr.Complete(true, null, null);

                        if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Information, EtwTraceFlags.AppSvc)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_SESSION_DATA_END, _rqContext.WorkerRequest);
                        return _rqAr;
                    }
                }

                if (isCompleted) {
                    CompleteAcquireState();
                    _rqAr.Complete(true, null, null);
                }

                return _rqAr;
            }
            finally {
                RestoreImpersonation();
            }
        }
예제 #13
0
        void ResetPerRequestFields() {
            Debug.Assert(_rqIctx == null, "_rqIctx == null");
            Debug.Assert(_rqChangeImpersonationRefCount == 0, "_rqChangeImpersonationRefCount == 0");

            _rqSessionState = null;
            _rqId = null;
            _rqSessionItems = null;
            _rqStaticObjects = null;
            _rqIsNewSession = false;
            _rqSessionStateNotFound = true;
            _rqReadonly = false;
            _rqItem = null;
            _rqContext = null;
            _rqAr = null;
            _rqLockId = null;
            _rqInCallback = 0;
            _rqLastPollCompleted = DateTime.MinValue;
            _rqExecutionTimeout = TimeSpan.Zero;
            _rqAddedCookie = false;
            _rqIdNew = false;
            _rqActionFlags = 0;
            _rqIctx = null;
            _rqChangeImpersonationRefCount = 0;
            _rqTimerThreadImpersonationIctx = null;
            _rqSupportSessionIdReissue = false;
        }
        private IAsyncResult BeginAcquireState(object source, EventArgs e, AsyncCallback cb, object extraData)
        {
            IAsyncResult result;
            bool         sessionStateItem = true;
            bool         flag3            = false;

            this._acquireCalled = true;
            this._releaseCalled = false;
            this.ResetPerRequestFields();
            this._rqContext = ((HttpApplication)source).Context;
            this._rqAr      = new HttpAsyncResult(cb, extraData);
            this.ChangeImpersonation(this._rqContext, false);
            try
            {
                if (EtwTrace.IsTraceEnabled(4, 8))
                {
                    EtwTrace.Trace(EtwTraceType.ETW_TYPE_SESSION_DATA_BEGIN, this._rqContext.WorkerRequest);
                }
                this._store.InitializeRequest(this._rqContext);
                bool requiresSessionState = this._rqContext.RequiresSessionState;
                if (this._idManager.InitializeRequest(this._rqContext, false, out this._rqSupportSessionIdReissue))
                {
                    this._rqAr.Complete(true, null, null);
                    if (EtwTrace.IsTraceEnabled(4, 8))
                    {
                        EtwTrace.Trace(EtwTraceType.ETW_TYPE_SESSION_DATA_END, this._rqContext.WorkerRequest);
                    }
                    return(this._rqAr);
                }
                if ((s_allowInProcOptimization && !s_sessionEverSet) && (!requiresSessionState || !((SessionIDManager)this._idManager).UseCookieless(this._rqContext)))
                {
                    flag3 = true;
                }
                else
                {
                    this._rqId = this._idManager.GetSessionID(this._rqContext);
                }
                if (!requiresSessionState)
                {
                    if (this._rqId != null)
                    {
                        this._store.ResetItemTimeout(this._rqContext, this._rqId);
                    }
                    this._rqAr.Complete(true, null, null);
                    if (EtwTrace.IsTraceEnabled(4, 8))
                    {
                        EtwTrace.Trace(EtwTraceType.ETW_TYPE_SESSION_DATA_END, this._rqContext.WorkerRequest);
                    }
                    return(this._rqAr);
                }
                this._rqExecutionTimeout = this._rqContext.Timeout;
                if (this._rqExecutionTimeout == DEFAULT_DBG_EXECUTION_TIMEOUT)
                {
                    this._rqExecutionTimeout = s_configExecutionTimeout;
                }
                this._rqReadonly = this._rqContext.ReadOnlySessionState;
                if (this._rqId != null)
                {
                    sessionStateItem = this.GetSessionStateItem();
                }
                else if (!flag3)
                {
                    bool flag4 = this.CreateSessionId();
                    this._rqIdNew = true;
                    if (flag4)
                    {
                        if (s_configRegenerateExpiredSessionId)
                        {
                            this.CreateUninitializedSessionState();
                        }
                        this._rqAr.Complete(true, null, null);
                        if (EtwTrace.IsTraceEnabled(4, 8))
                        {
                            EtwTrace.Trace(EtwTraceType.ETW_TYPE_SESSION_DATA_END, this._rqContext.WorkerRequest);
                        }
                        return(this._rqAr);
                    }
                }
                if (sessionStateItem)
                {
                    this.CompleteAcquireState();
                    this._rqAr.Complete(true, null, null);
                }
                result = this._rqAr;
            }
            finally
            {
                this.RestoreImpersonation();
            }
            return(result);
        }