Example #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);
        }
Example #2
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);
        }
        internal void TaskCompleted(bool onCallerThread)
        {
            int newTasksCompleted = Interlocked.Increment(ref _tasksCompleted);

            Debug.Trace("Async", "TaskManager.TaskCompleted: onCallerThread=" + onCallerThread +
                        ", _tasksCompleted=" + newTasksCompleted + ", _tasksStarted=" + _tasksStarted);

            if (newTasksCompleted < _tasksStarted)
            {
                // need to wait for more completions
                return;
            }

            // check if any tasks remain not started
            if (!AnyTasksRemain)
            {
                // can complete the caller - all done
                _inProgress = false;
                _asyncResult.Complete(onCallerThread, null /*result*/, AnyTaskError);
                return;
            }

            // need to resume executing tasks
            if (Thread.CurrentThread.IsThreadPoolThread)
            {
                // if on thread pool thread, use the current thread
                ResumeTasks(false /*waitUntilDone*/, onCallerThread);
            }
            else
            {
                // if on a non-threadpool thread, requeue
                ThreadPool.QueueUserWorkItem(_resumeTasksCallback);
            }
        }
Example #4
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);
        }
Example #5
0
 private void OnAspCompatCompletion()
 {
     _rootedThis.Free();
     _ar.Complete(false, null, _error); // resume the application execution
 }
        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);
        }
Example #7
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();
            }
        }