public FakeHttpContext() { this.Request = new FakeRequest(this.fakeWorkerRequest); this.conextBackup = HttpContext.Current; this.Switchers.Add(new FakeHostEnvironment()); HttpContext.Current = new HttpContext(this.fakeWorkerRequest); HttpContext.Current.Request.Browser = new HttpBrowserCapabilities { Capabilities = new Hashtable() }; var sessionContainer = new HttpSessionStateContainer( "id", new SessionStateItemCollection(), new HttpStaticObjectsCollection(), 10, true, HttpCookieMode.AutoDetect, SessionStateMode.InProc, false); HttpContext.Current.Items["AspSession"] = typeof(HttpSessionState).GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, null, CallingConventions.Standard, new[] { typeof(HttpSessionStateContainer) }, null).Invoke(new object[] { sessionContainer }); }
/// <summary> /// 主要用於設定 SessionID. /// </summary> /// <param name="sessionId">The session identifier.</param> /// <returns>HttpContext.</returns> public static HttpContext FakeHttpContext(string sessionId = "id") { // Step 1: Setup the HTTP Request var httpRequest = new HttpRequest(string.Empty, "http://localhost/", string.Empty); // Step 2: Setup the HTTP Response var httpResponce = new HttpResponse(new StringWriter()); // Step 3: Setup the Http Context var httpContext = new HttpContext(httpRequest, httpResponce); var sessionContainer = new HttpSessionStateContainer( sessionId, new SessionStateItemCollection(), new HttpStaticObjectsCollection(), 10, true, HttpCookieMode.AutoDetect, SessionStateMode.InProc, false); httpContext.Items["AspSession"] = typeof(HttpSessionState).GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, null, CallingConventions.Standard, new[] { typeof(HttpSessionStateContainer) }, null).Invoke(new object[] { sessionContainer }); return httpContext; }
public static HttpContext FakeHttpContext() { using (var stringWriter = new StringWriter()) { var httpRequest = new HttpRequest("", "http://abc", ""); var httpResponse = new HttpResponse(stringWriter); var httpContext = new HttpContext(httpRequest, httpResponse); var sessionContainer = new HttpSessionStateContainer( "id", new SessionStateItemCollection(), new HttpStaticObjectsCollection(), 10, true, HttpCookieMode.AutoDetect, SessionStateMode.InProc, false); httpContext.Items["AspSession"] = typeof(HttpSessionState).GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, null, CallingConventions.Standard, new[] {typeof(HttpSessionStateContainer)}, null) .Invoke(new object[] {sessionContainer}); return httpContext; } }
public static HttpContext GetHttpContext( string queryString = "" ) { HttpRequest request = new HttpRequest( "", "http://www.test.ing", queryString ); var httpContext = new HttpContext( request, new HttpResponse( new StringWriter() ) ); var field = request.GetType().GetField( "_referrer", BindingFlags.Instance | BindingFlags.NonPublic ); field.SetValue( request, new Uri( "http://localhost" ) ); var sessionContainer = new HttpSessionStateContainer( "id", new SessionStateItemCollection(), new HttpStaticObjectsCollection(), 10, true, HttpCookieMode.AutoDetect, SessionStateMode.InProc, false ); httpContext.Items[ "AspSession" ] = typeof ( HttpSessionState ) .GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, null, CallingConventions.Standard, new[] { typeof ( HttpSessionStateContainer ) }, null ) .Invoke( new object[] { sessionContainer } ); return httpContext; }
internal void InitStateStoreItem(bool addToContext) { this.ChangeImpersonation(this._rqContext, false); try { if (this._rqItem == null) { this._rqItem = this._store.CreateNewStoreData(this._rqContext, s_timeout); } this._rqSessionItems = this._rqItem.Items; if (this._rqSessionItems == null) { throw new HttpException(System.Web.SR.GetString("Null_value_for_SessionStateItemCollection")); } this._rqStaticObjects = this._rqItem.StaticObjects; this._rqSessionItems.Dirty = false; this._rqSessionState = new HttpSessionStateContainer(this, this._rqId, this._rqSessionItems, this._rqStaticObjects, this._rqItem.Timeout, this._rqIsNewSession, s_configCookieless, s_configMode, this._rqReadonly); if (addToContext) { SessionStateUtility.AddHttpSessionStateToContext(this._rqContext, this._rqSessionState); } } finally { this.RestoreImpersonation(); } }
void OnReleaseRequestState(object o, EventArgs args) { Trace.WriteLine("SessionStateModule.OnReleaseRequestState (hash " + this.GetHashCode().ToString("x") + ")"); HttpApplication application = (HttpApplication)o; HttpContext context = application.Context; if (!(context.Handler is IRequiresSessionState)) { return; } Trace.WriteLine("\tsessionId == " + container.SessionID); Trace.WriteLine("\trequest path == " + context.Request.FilePath); Trace.WriteLine("\tHandler (" + context.Handler + ") requires session state"); try { if (!container.IsAbandoned) { Trace.WriteLine("\tnot abandoned"); if (!container.IsReadOnly) { Trace.WriteLine("\tnot read only, storing and releasing"); handler.SetAndReleaseItemExclusive(context, container.SessionID, storeData, storeLockId, storeIsNew); } else { Trace.WriteLine("\tread only, releasing"); handler.ReleaseItemExclusive(context, container.SessionID, storeLockId); } handler.ResetItemTimeout(context, container.SessionID); } else { handler.ReleaseItemExclusive(context, container.SessionID, storeLockId); handler.RemoveItem(context, container.SessionID, storeLockId, storeData); if (supportsExpiration) #if TARGET_J2EE {; } else #else {// Make sure the expiration handler is not called after we will have raised // the session end event. handler.SetItemExpireCallback(null); } #endif { SessionStateUtility.RaiseSessionEnd(container, this, args); } } SessionStateUtility.RemoveHttpSessionStateFromContext(context); } finally { container = null; storeData = null; } }
private FakeHttpContext() { var request = new SimpleWorkerRequest("/test", @"c:\inetpub", "test.html", null, Console.Out); var context = new HttpContext(request); var stateContainer = new HttpSessionStateContainer(Guid.NewGuid().ToString(), new SessionStateItemCollection(), new HttpStaticObjectsCollection(), 60000, false, HttpCookieMode.UseCookies, SessionStateMode.InProc, false); SessionStateUtility.AddHttpSessionStateToContext(context, stateContainer); HttpContext.Current = context; }
private void CompleteAcquireState() { bool flag = false; try { if (this._rqItem != null) { this._rqSessionStateNotFound = false; if ((this._rqActionFlags & SessionStateActions.InitializeItem) != SessionStateActions.None) { this._rqIsNewSession = true; } else { this._rqIsNewSession = false; } } else { this._rqIsNewSession = true; this._rqSessionStateNotFound = true; if (s_allowDelayedStateStoreItemCreation) { flag = true; } if ((!this._rqIdNew && s_configRegenerateExpiredSessionId) && (this._rqSupportSessionIdReissue && this.CreateSessionId())) { this.CreateUninitializedSessionState(); return; } } if (flag) { SessionStateUtility.AddDelayedHttpSessionStateToContext(this._rqContext, this); this._rqSessionState = s_delayedSessionState; } else { this.InitStateStoreItem(true); } if (this._rqIsNewSession) { this.OnStart(EventArgs.Empty); } } finally { if (EtwTrace.IsTraceEnabled(4, 8)) { EtwTrace.Trace(EtwTraceType.ETW_TYPE_SESSION_DATA_END, this._rqContext.WorkerRequest); } } }
internal void RaiseSessionOnEnd(string id, SessionStateStoreData item) { HttpSessionStateContainer container = new HttpSessionStateContainer(id, item.Items, item.StaticObjects, item.Timeout, false, SessionStateModule.s_configCookieless, SessionStateModule.s_configMode, true); HttpSessionState sessionState = new HttpSessionState(container); if (HttpRuntime.ShutdownInProgress) { this.RaiseOnEnd(sessionState); } else { SessionOnEndTargetWorkItem item2 = new SessionOnEndTargetWorkItem(this, sessionState); WorkItem.PostInternal(new WorkItemCallback(item2.RaiseOnEndCallback)); } }
/// <summary> /// Mocks the HTTP request context. /// </summary> public static void MockHttpRequestContext() { var httpRequest = new HttpRequest(string.Empty, LocalHostAddress, string.Empty); httpRequest.Cookies.Add(new HttpCookie(UserName, null)); using (StringWriter stringWriter = new StringWriter(CultureInfo.CurrentCulture)) { var httpResponce = new HttpResponse(stringWriter); var httpContext = new HttpContext(httpRequest, httpResponce); var sessionContainer = new HttpSessionStateContainer(IdConstant, new SessionStateItemCollection(), new HttpStaticObjectsCollection(), 10, true, HttpCookieMode.UseCookies, SessionStateMode.InProc, false); httpContext.Items[AspSessionConstant] = typeof(HttpSessionState).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, CallingConventions.Standard, new[] { typeof(HttpSessionStateContainer) }, null).Invoke(new object[] { sessionContainer }); HttpContext.Current = httpContext; HttpContext.Current.Session.Add(SessionDataConstant, null); } }
/// <summary> /// Get mocked http context for testing /// </summary> /// <returns></returns> public static HttpContext GetMockedHttpContext() { var httpRequest = new HttpRequest("", "http://localhost/", ""); var stringWriter = new StringWriter(); var httpResponse = new HttpResponse(stringWriter); var httpContext = new HttpContext(httpRequest, httpResponse); var sessionContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(), new HttpStaticObjectsCollection(), 10, true, HttpCookieMode.AutoDetect, SessionStateMode.InProc, false); SessionStateUtility.AddHttpSessionStateToContext(httpContext, sessionContainer); return httpContext; }
public void TestInit() { this._queue = MockRepository.GenerateMock<IQueue>(); this._knownUser = MockRepository.GenerateMock<IKnownUser>(); this._request = new HttpRequest("test.aspx", "http://test.com/test.aspx", null); this._response = new HttpResponse(new StringWriter()); HttpContext.Current = new HttpContext(this._request, this._response); var sessionContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(), new HttpStaticObjectsCollection(), 10, true, HttpCookieMode.AutoDetect, SessionStateMode.InProc, false); SessionStateUtility.AddHttpSessionStateToContext(HttpContext.Current, sessionContainer); SessionValidateResultRepository.Clear(); }
public MockHttpContext(string page, string query) { Thread.GetDomain().SetData( ThreadDataKeyAppPath, ThreadDataKeyAppPathValue); Thread.GetDomain().SetData( ThreadDataKeyAppVPath, ThreadDataKeyAppVPathValue); SimpleWorkerRequest request = new SimpleWorkerRequest(page, query, new StringWriter()); _context = new HttpContext(request); HttpSessionStateContainer container = new HttpSessionStateContainer( Guid.NewGuid().ToString("N"), new SessionStateItemCollection(), new HttpStaticObjectsCollection(), 5, true, HttpCookieMode.AutoDetect, SessionStateMode.InProc, false); HttpSessionState state = Activator.CreateInstance( typeof(HttpSessionState), BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.CreateInstance, null, new object[] { container }, CultureInfo.CurrentCulture) as HttpSessionState; _context.Items["AspSession"] = state; }
public void MyTestInitialize() { var request = new HttpRequest("", "http://example.com/", ""); var response = new HttpResponse(TextWriter.Null); HttpContext.Current = new HttpContext(request, response); var sessionStateContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(), new HttpStaticObjectsCollection(), 10, true, HttpCookieMode.AutoDetect, SessionStateMode.InProc, false); SessionStateUtility.AddHttpSessionStateToContext(HttpContext.Current, sessionStateContainer); _serviceController = new ServicesController(); var httpContext = new HttpContextWrapper(HttpContext.Current); _serviceController.ControllerContext = new ControllerContext(httpContext, new RouteData(), _serviceController); CurrentUser.SetInstance(Utility.GetUserName()); _user = CurrentUser.AsRosettianUser(); }
public HttpContextBuilder WithSession() { var sessionContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(), new HttpStaticObjectsCollection(), 10, true, HttpCookieMode.AutoDetect, SessionStateMode.InProc, false); _instance.Items["AspSession"] = typeof(HttpSessionState).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, CallingConventions.Standard, new[] {typeof(HttpSessionStateContainer)}, null) .Invoke(new object[] {sessionContainer}); return this; }
public static HttpContext Create(string page, string queryString = "") { var request = new HttpRequest(page, "http://bugfreak.co", queryString); var response = new HttpResponse(new StringWriter()); var httpContext = new HttpContext(request, response); var sessionContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(), new HttpStaticObjectsCollection(), 10, true, HttpCookieMode.AutoDetect, SessionStateMode.InProc, false); httpContext.Items["AspSession"] = typeof(HttpSessionState).GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, null, CallingConventions.Standard, new[] { typeof(HttpSessionStateContainer) }, null) .Invoke(new object[] { sessionContainer }); return httpContext; }
/// <summary> /// Method creates http context /// </summary> /// <param name="fileName">File name</param> /// <param name="url">URL for file</param> /// <param name="queryString">Query string for context</param> /// <returns>It returns object of HttpContext class</returns> public static HttpContext CreateHttpContext(string fileName, string url, string queryString) { var sb = new StringBuilder(); var sw = new StringWriter(sb); var httpResponse = new HttpResponse(sw); var httpRequest = new HttpRequest(fileName, url, queryString); var httpContext = new HttpContext(httpRequest, httpResponse); var sessionContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(), new HttpStaticObjectsCollection(), 10, true, HttpCookieMode.AutoDetect, SessionStateMode.InProc, false); httpContext.Items["AspSession"] = typeof(HttpSessionState).GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, null, CallingConventions.Standard, new[] { typeof(HttpSessionStateContainer) }, null) .Invoke(new object[] { sessionContainer }); return httpContext; }
public static HttpSessionState GetMockHttpSessionState() { HttpSessionState state = null; HttpStaticObjectsCollection staticObjects = new HttpStaticObjectsCollection(); SessionStateItemCollection itemCollection = new SessionStateItemCollection(); IHttpSessionState sessionStateContainer = new HttpSessionStateContainer(Guid.NewGuid().ToString("N"), itemCollection, staticObjects, 1, true, HttpCookieMode.UseUri, SessionStateMode.InProc, false); state = Activator.CreateInstance( typeof(HttpSessionState), BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.CreateInstance, null, new object[] { sessionStateContainer }, CultureInfo.CurrentCulture) as HttpSessionState; return state; }
/// <summary> /// 创建一个模拟的 MVC 控制器。 /// </summary> /// <typeparam name="TController">控制的数据类型。</typeparam> /// <param name="user">当前已授权的登录用户。</param> /// <param name="mockFactoryCallback">模拟的执行器工厂回调函数。</param> /// <returns>返回一个控制器的实例。</returns> public static TController Create <TController>(object user, Action <MockExecutorFactory> mockFactoryCallback = null) where TController : Web.Mvc.Controller, new() { var httpRequest = new HttpRequest(string.Empty, "http://www.aoite.com/", string.Empty); var stringWriter = new IO.StringWriter(); var httpResponce = new HttpResponse(stringWriter); var httpContext = new HttpContext(httpRequest, httpResponce); var sessionContainer = new SessionState.HttpSessionStateContainer("id", new SessionState.SessionStateItemCollection(), new HttpStaticObjectsCollection(), 10, true, HttpCookieMode.AutoDetect, SessionState.SessionStateMode.InProc, false); httpContext.Items["AspSession"] = typeof(SessionState.HttpSessionState).GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, null, CallingConventions.Standard, new[] { typeof(SessionState.HttpSessionStateContainer) }, null) .Invoke(new object[] { sessionContainer }); HttpContext.Current = httpContext; var appFactoryType = typeof(HttpContext).Assembly.GetType("System.Web.HttpApplicationFactory"); object appFactory = DynamicFactory.CreateFieldGetter(appFactoryType.GetField("_theApplicationFactory", BindingFlags.NonPublic | BindingFlags.Static))(null); DynamicFactory.CreateFieldSetter(appFactoryType.GetField("_state", BindingFlags.NonPublic | BindingFlags.Instance))(appFactory, HttpContext.Current.Application); var identityStore = new MockSessionIdentityStore(user); var container = ServiceFactory.CreateContainer(identityStore, mockFactoryCallback); container.Add <IIdentityStore>(identityStore); Webx.Container = container; TController c = new TController(); c.ControllerContext = new Web.Mvc.ControllerContext(new Routing.RequestContext(new HttpContextWrapper(httpContext), new Routing.RouteData()), c); return(c); }
public static void setSession() { // set the session variable var httpRequest = new HttpRequest("", "http://www.localhost.com/", ""); var stringWriter = new StringWriter(); var httpResponce = new HttpResponse(stringWriter); var httpContext = new HttpContext(httpRequest, httpResponce); var sessionContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(), new HttpStaticObjectsCollection(), 10, true, HttpCookieMode.AutoDetect, SessionStateMode.InProc, false); httpContext.Items["AspSession"] = typeof(HttpSessionState).GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, null, CallingConventions.Standard, new[] { typeof(HttpSessionStateContainer) }, null) .Invoke(new object[] { sessionContainer }); HttpContext.Current = httpContext; SessionObjects.UserID = 1; }
public void MyTestInitialize() { var request = new HttpRequest("", "http://example.com/", ""); var response = new HttpResponse(TextWriter.Null); HttpContext.Current = new HttpContext(request, response); var sessionStateContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(), new HttpStaticObjectsCollection(), 10, true, HttpCookieMode.AutoDetect, SessionStateMode.InProc, false); SessionStateUtility.AddHttpSessionStateToContext(HttpContext.Current, sessionStateContainer); _subscriberController = new SubscriberController(); var httpContext = new HttpContextWrapper(HttpContext.Current); _subscriberController.ControllerContext = new ControllerContext(httpContext, new RouteData(), _subscriberController); var windowsIdentity = WindowsIdentity.GetCurrent(); var userName = string.Empty; if (windowsIdentity != null) { userName = windowsIdentity.Name.Split('\\')[1]; } CurrentUser.SetInstance(userName); _user = CurrentUser.AsRosettianUser(); }
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; }
public void Add_GroupUser() { Guid guidToken = Guid.NewGuid(); SecurityToken token = new SecurityToken() { SecurityTokenId = 1, Token = guidToken, ActualID = 1 }; securityTokenRepository.Setup(x => x.Get(It.IsAny<Expression<Func<SecurityToken, bool>>>())).Returns(token); MemoryUser user = new MemoryUser("adarsh"); ApplicationUser applicationUser = getApplicationUser(); var userContext = new UserInfo { UserId = user.Id, DisplayName = user.UserName, UserIdentifier = applicationUser.Email, RoleName = Enum.GetName(typeof(UserRoles), applicationUser.RoleId) }; var testTicket = new FormsAuthenticationTicket( 1, user.Id, DateTime.Now, DateTime.Now.Add(FormsAuthentication.Timeout), false, userContext.ToString()); EmailRequestController controller = new EmailRequestController(securityTokenService, groupUserService, supportService, groupInvitationService); controllerContext.SetupGet(x => x.HttpContext.User).Returns(principal.Object); controllerContext.SetupGet(p => p.HttpContext.Request.IsAuthenticated).Returns(true); controller.ControllerContext = controllerContext.Object; contextBase.SetupGet(x => x.Request).Returns(httpRequest.Object); contextBase.SetupGet(x => x.Response).Returns(httpResponse.Object); genericPrincipal.Setup(x => x.Identity).Returns(identity.Object); contextBase.SetupGet(a => a.Response.Cookies).Returns(new HttpCookieCollection()); var formsAuthentication = new DefaultFormsAuthentication(); formsAuthentication.SetAuthCookie(contextBase.Object, testTicket); HttpCookie authCookie = contextBase.Object.Response.Cookies[FormsAuthentication.FormsCookieName]; var ticket = formsAuthentication.Decrypt(authCookie.Value); var goalsetterUser = new SocialGoalUser(ticket); principal.Setup(x => x.Identity).Returns(goalsetterUser); var httprequest = new HttpRequest("", "http://yoursite/", ""); var stringWriter = new StringWriter(); var httpResponce = new HttpResponse(stringWriter); var httpContext = new HttpContext(httprequest, httpResponce); var sessionContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(), new HttpStaticObjectsCollection(), 10, true, HttpCookieMode.AutoDetect, SessionStateMode.InProc, false); httpContext.Items["AspSession"] = typeof(HttpSessionState).GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, null, CallingConventions.Standard, new[] { typeof(HttpSessionStateContainer) }, null) .Invoke(new object[] { sessionContainer }); HttpContext.Current = httpContext; //HttpContext.Current.Request.Session["somevalue"]; controller.TempData = tempData.Object; controller.TempData["grToken"] = guidToken; var result = controller.AddGroupUser() as RedirectToRouteResult; Assert.AreEqual("Index", result.RouteValues["action"]); }
void OnReleaseRequestState (object o, EventArgs args) { Trace.WriteLine ("SessionStateModule.OnReleaseRequestState (hash " + this.GetHashCode ().ToString ("x") + ")"); HttpApplication application = (HttpApplication) o; HttpContext context = application.Context; if (!(context.Handler is IRequiresSessionState)) return; Trace.WriteLine ("\tsessionId == " + container.SessionID); Trace.WriteLine ("\trequest path == " + context.Request.FilePath); Trace.WriteLine ("\tHandler (" + context.Handler + ") requires session state"); try { if (!container.IsAbandoned) { Trace.WriteLine ("\tnot abandoned"); if (!container.IsReadOnly) { Trace.WriteLine ("\tnot read only, storing and releasing"); handler.SetAndReleaseItemExclusive (context, container.SessionID, storeData, storeLockId, storeIsNew); } else { Trace.WriteLine ("\tread only, releasing"); handler.ReleaseItemExclusive (context, container.SessionID, storeLockId); } handler.ResetItemTimeout (context, container.SessionID); } else { handler.ReleaseItemExclusive (context, container.SessionID, storeLockId); handler.RemoveItem (context, container.SessionID, storeLockId, storeData); if (supportsExpiration) // Make sure the expiration handler is not called after we will have raised // the session end event. handler.SetItemExpireCallback (null); SessionStateUtility.RaiseSessionEnd (container, this, args); } SessionStateUtility.RemoveHttpSessionStateFromContext (context); } finally { container = null; storeData = null; } }
void OnAcquireRequestState (object o, EventArgs args) { Trace.WriteLine ("SessionStateModule.OnAcquireRequestState (hash " + this.GetHashCode ().ToString ("x") + ")"); HttpApplication application = (HttpApplication) o; HttpContext context = application.Context; if (!(context.Handler is IRequiresSessionState)) { Trace.WriteLine ("Handler (" + context.Handler + ") does not require session state"); return; } bool isReadOnly = (context.Handler is IReadOnlySessionState); bool supportSessionIDReissue; if (idManager.InitializeRequest (context, false, out supportSessionIDReissue)) return; // Redirected, will come back here in a while string sessionId = idManager.GetSessionID (context); handler.InitializeRequest (context); storeData = GetStoreData (context, sessionId, isReadOnly); storeIsNew = false; if (storeData == null && !storeLocked) { storeIsNew = true; sessionId = idManager.CreateSessionID (context); Trace.WriteLine ("New session ID allocated: " + sessionId); bool redirected; bool cookieAdded; idManager.SaveSessionID (context, sessionId, out redirected, out cookieAdded); if (redirected) { if (supportSessionIDReissue) handler.CreateUninitializedItem (context, sessionId, (int)config.Timeout.TotalMinutes); context.Response.End (); return; } else storeData = handler.CreateNewStoreData (context, (int)config.Timeout.TotalMinutes); } else if (storeData == null && storeLocked) { WaitForStoreUnlock (context, sessionId, isReadOnly); } else if (storeData != null && !storeLocked && storeSessionAction == SessionStateActions.InitializeItem && IsCookieLess (context, config)) { storeData = handler.CreateNewStoreData (context, (int)config.Timeout.TotalMinutes); } container = CreateContainer (sessionId, storeData, storeIsNew, isReadOnly); SessionStateUtility.AddHttpSessionStateToContext (app.Context, container); if (storeIsNew) { OnSessionStart (); HttpSessionState hss = app.Session; if (hss != null) storeData.Timeout = hss.Timeout; } // Whenever a container is abandoned, we temporarily disable the expire call back. // So in this case we are quite sure we have a brand new container, so we make sure it works again. supportsExpiration = handler.SetItemExpireCallback (OnSessionExpired); }
public void LogOff() { var userManager = new UserManager<ApplicationUser>(new TestUserStore()); var mockAuthenticationManager = new Mock<IAuthenticationManager>(); mockAuthenticationManager.Setup(am => am.SignOut()); mockAuthenticationManager.Setup(am => am.SignIn()); AccountController controller = new AccountController(userService, userProfileService, goalService, updateService, commentService, followRequestService, followUserService, securityTokenService, userManager); controller.AuthenticationManager = mockAuthenticationManager.Object; var httprequest = new HttpRequest("", "http://localhost/", ""); var stringWriter = new StringWriter(); var httpResponce = new HttpResponse(stringWriter); var httpContext = new HttpContext(httprequest, httpResponce); var sessionContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(), new HttpStaticObjectsCollection(), 10, true, HttpCookieMode.AutoDetect, SessionStateMode.InProc, false); httpContext.Items["AspSession"] = typeof(HttpSessionState).GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, null, CallingConventions.Standard, new[] { typeof(HttpSessionStateContainer) }, null) .Invoke(new object[] { sessionContainer }); HttpContext.Current = httpContext; var result = controller.LogOff() as RedirectToRouteResult; Assert.AreEqual("Index", result.RouteValues["action"]); }
/// <summary> /// GetHttpSession method - used for integration tests that need the HTTP Context object to be set up. /// </summary> /// <returns>HttpContext</returns> public System.Web.HttpContext GetHttpSession() { var request = new HttpRequest("", "http://example.com/", ""); var response = new HttpResponse(TextWriter.Null); HttpContext.Current = new HttpContext(request, response); var sessionStateContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(), new HttpStaticObjectsCollection(), 10, true, HttpCookieMode.AutoDetect, SessionStateMode.InProc, false); SessionStateUtility.AddHttpSessionStateToContext(HttpContext.Current, sessionStateContainer); return HttpContext.Current; }
private static HttpSessionState CreateSessionState(string key, object state) { string id = key.Substring(CACHEKEYPREFIXLENGTH); ISessionStateItemCollection sessionItems = (ISessionStateItemCollection)ExpressionEvaluator.GetValue(state, "_sessionItems"); HttpStaticObjectsCollection staticObjects = (HttpStaticObjectsCollection)ExpressionEvaluator.GetValue(state, "_staticObjects"); int timeout = (int)ExpressionEvaluator.GetValue(state, "_timeout"); TypeRegistry.RegisterType("SessionStateModule", typeof(SessionStateModule)); HttpCookieMode cookieMode = (HttpCookieMode)ExpressionEvaluator.GetValue(null, "SessionStateModule.s_configCookieless"); SessionStateMode stateMode = (SessionStateMode)ExpressionEvaluator.GetValue(null, "SessionStateModule.s_configMode"); HttpSessionStateContainer container = new HttpSessionStateContainer( id , sessionItems , staticObjects , timeout , false , cookieMode , stateMode , true ); return (HttpSessionState)Activator.CreateInstance( typeof(HttpSessionState) , BindingFlags.Instance | BindingFlags.NonPublic , null , new object[] { container } , CultureInfo.InvariantCulture ); }
internal void InitStateStoreItem(bool addToContext) { Debug.Assert(_rqId != null || s_allowInProcOptimization, "_rqId != null || s_allowInProcOptimization"); ChangeImpersonation(_rqContext, false); try { if (_rqItem == null) { Debug.Trace("InitStateStoreItem", "Creating new session state"); _rqItem = _store.CreateNewStoreData(_rqContext, s_timeout); } _rqSessionItems = _rqItem.Items; if (_rqSessionItems == null) { throw new HttpException(SR.GetString(SR.Null_value_for_SessionStateItemCollection)); } // No check for null because we allow our custom provider to return a null StaticObjects. _rqStaticObjects = _rqItem.StaticObjects; _rqSessionItems.Dirty = false; _rqSessionState = new HttpSessionStateContainer( this, _rqId, // could be null if we're using InProc optimization _rqSessionItems, _rqStaticObjects, _rqItem.Timeout, _rqIsNewSession, s_configCookieless, s_configMode, _rqReadonly); if (addToContext) { SessionStateUtility.AddHttpSessionStateToContext(_rqContext, _rqSessionState); } } finally { RestoreImpersonation(); } }
internal void RaiseSessionOnEnd(String id, SessionStateStoreData item) { HttpSessionStateContainer sessionStateContainer = new HttpSessionStateContainer( id, item.Items, item.StaticObjects, item.Timeout, false, SessionStateModule.s_configCookieless, SessionStateModule.s_configMode, true); HttpSessionState sessionState = new HttpSessionState(sessionStateContainer); if (HttpRuntime.ShutdownInProgress) { // call directly when shutting down RaiseOnEnd(sessionState); } else { // post via thread pool SessionOnEndTargetWorkItem workItem = new SessionOnEndTargetWorkItem(this, sessionState); WorkItem.PostInternal(new WorkItemCallback(workItem.RaiseOnEndCallback)); } }
void OnAcquireRequestState(object o, EventArgs args) { Trace.WriteLine("SessionStateModule.OnAcquireRequestState (hash " + this.GetHashCode().ToString("x") + ")"); HttpApplication application = (HttpApplication)o; HttpContext context = application.Context; if (!(context.Handler is IRequiresSessionState)) { Trace.WriteLine("Handler (" + context.Handler + ") does not require session state"); return; } bool isReadOnly = (context.Handler is IReadOnlySessionState); bool supportSessionIDReissue; if (idManager.InitializeRequest(context, false, out supportSessionIDReissue)) { return; // Redirected, will come back here in a while } string sessionId = idManager.GetSessionID(context); handler.InitializeRequest(context); storeData = GetStoreData(context, sessionId, isReadOnly); storeIsNew = false; if (storeData == null && !storeLocked) { storeIsNew = true; sessionId = idManager.CreateSessionID(context); Trace.WriteLine("New session ID allocated: " + sessionId); bool redirected; bool cookieAdded; idManager.SaveSessionID(context, sessionId, out redirected, out cookieAdded); if (redirected) { if (supportSessionIDReissue) { handler.CreateUninitializedItem(context, sessionId, (int)config.Timeout.TotalMinutes); } context.Response.End(); return; } else { storeData = handler.CreateNewStoreData(context, (int)config.Timeout.TotalMinutes); } } else if (storeData == null && storeLocked) { WaitForStoreUnlock(context, sessionId, isReadOnly); } else if (storeData != null && !storeLocked && storeSessionAction == SessionStateActions.InitializeItem && IsCookieLess(context, config)) { storeData = handler.CreateNewStoreData(context, (int)config.Timeout.TotalMinutes); } container = CreateContainer(sessionId, storeData, storeIsNew, isReadOnly); SessionStateUtility.AddHttpSessionStateToContext(app.Context, container); if (storeIsNew) { OnSessionStart(); HttpSessionState hss = app.Session; if (hss != null) { storeData.Timeout = hss.Timeout; } } // Whenever a container is abandoned, we temporarily disable the expire call back. // So in this case we are quite sure we have a brand new container, so we make sure it works again. supportsExpiration = handler.SetItemExpireCallback(OnSessionExpired); }
public void MyTestInitialize() { var testAssemblyLocation = AppDomain.CurrentDomain.BaseDirectory; // Determine if we are running all of the tests either locally or on the build machine if (testAssemblyLocation.EndsWith(_endOfPathWhenRunningAllTestsLocallyOrOnBuildServer)) { if (testAssemblyLocation.Contains(_buildServerPathFragment)) { ProductionCodeXMLFileLocation = Path.Combine(testAssemblyLocation, _pathToAddWhenRunningAllTestsOnBuildServer); } else { ProductionCodeXMLFileLocation = Path.Combine(testAssemblyLocation, _pathToAddWhenRunningAllTestsLocally); } } else if (testAssemblyLocation.Contains(_pathToSearchWhenRunningIndividualTests)) { ProductionCodeXMLFileLocation = Path.Combine(testAssemblyLocation, _pathToAddWhenRunningIndividualTests); } else { Assert.Fail("Path {0} does not match existing rules", testAssemblyLocation); } if (!File.Exists(ProductionCodeXMLFileLocation)) { Assert.Fail("File {0} does not exist", ProductionCodeXMLFileLocation); } // This isn't using Microsoft Fakes as I couldn't find a direct // way to fake out all of the things that were needed. // Before adding this, the Init method (private method in // the NavigationMenu.cs file) was blowing up. // After adding this, the Init method doesn't blow up but // the Xdoc public property is null. var request = new HttpRequest("", "http://example.com/", ""); var response = new HttpResponse(TextWriter.Null); HttpContext.Current = new HttpContext(request, response); var sessionStateContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(), new HttpStaticObjectsCollection(), 10, true, HttpCookieMode.AutoDetect, SessionStateMode.InProc, false); SessionStateUtility.AddHttpSessionStateToContext(HttpContext.Current, sessionStateContainer); }
public void Login_Get_View_If_Guid_Is_NotNull() { var userManager = new UserManager<ApplicationUser>(new TestUserStore()); //mocking QueryString var querystring = new NameValueCollection { { "guid", "got_value" } }; var querystring1 = new NameValueCollection { { "reg", "value" } }; Guid goalIdToken = Guid.NewGuid(); // Guid controllerContext.SetupGet(p => p.HttpContext.Request.QueryString).Returns(querystring); //controllerContext.SetupGet(p => p.HttpContext.Request.QueryString).Returns(querystring1); controllerContext.SetupGet(p => p.HttpContext.Session).Returns(httpSession.Object); AccountController controller = new AccountController(userService, userProfileService, goalService, updateService, commentService, followRequestService, followUserService, securityTokenService, userManager); controller.ControllerContext = controllerContext.Object; var httprequest = new HttpRequest("", "http://localhost/", ""); var stringWriter = new StringWriter(); var httpResponce = new HttpResponse(stringWriter); var httpContext = new HttpContext(httprequest, httpResponce); // Mocking HttpContext.Current var sessionContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(), new HttpStaticObjectsCollection(), 10, true, HttpCookieMode.AutoDetect, SessionStateMode.InProc, false); httpContext.Items["AspSession"] = typeof(HttpSessionState).GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, null, CallingConventions.Standard, new[] { typeof(HttpSessionStateContainer) }, null) .Invoke(new object[] { sessionContainer }); HttpContext.Current = httpContext; ViewResult rslt = controller.Login("abcd") as ViewResult; Assert.IsNotNull(rslt); }
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; }
public void RegisterTest() { var userManager = new UserManager<ApplicationUser>(new TestUserStore()); AccountController controller = new AccountController(userService, userProfileService, goalService, updateService, commentService, followRequestService, followUserService, securityTokenService, userManager); var mockAuthenticationManager = new Mock<IAuthenticationManager>(); mockAuthenticationManager.Setup(am => am.SignOut()); mockAuthenticationManager.Setup(am => am.SignIn()); controller.AuthenticationManager = mockAuthenticationManager.Object; var httprequest = new HttpRequest("", "http://localhost/", ""); var stringWriter = new StringWriter(); var httpResponce = new HttpResponse(stringWriter); var httpContext = new HttpContext(httprequest, httpResponce); var sessionContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(), new HttpStaticObjectsCollection(), 10, true, HttpCookieMode.AutoDetect, SessionStateMode.InProc, false); httpContext.Items["AspSession"] = typeof(HttpSessionState).GetConstructor( BindingFlags.NonPublic | BindingFlags.Instance, null, CallingConventions.Standard, new[] { typeof(HttpSessionStateContainer) }, null) .Invoke(new object[] { sessionContainer }); HttpContext.Current = httpContext; var result = controller.Register(new RegisterViewModel { UserName = "******", Password = "******", ConfirmPassword = "******" }).Result; Assert.IsNotNull(result); var addedUser = userManager.FindByName("adarsh"); Assert.IsNotNull(addedUser); Assert.AreEqual("adarsh", addedUser.UserName); }
// Called when AcquireState is done. This function will add the returned // SessionStateStore item to the request context. void CompleteAcquireState() { Debug.Trace("SessionStateModuleOnAcquireState", "Item retrieved=" + (_rqItem != null).ToString(CultureInfo.InvariantCulture)); bool delayInitStateStoreItem = false; Debug.Assert(!(s_allowDelayedStateStoreItemCreation && s_configRegenerateExpiredSessionId), "!(s_allowDelayedStateStoreItemCreation && s_configRegenerateExpiredSessionId)"); try { if (_rqItem != null) { _rqSessionStateNotFound = false; if ((_rqActionFlags & SessionStateActions.InitializeItem) != 0) { Debug.Trace("SessionStateModuleOnAcquireState", "Initialize an uninit item"); _rqIsNewSession = true; } else { _rqIsNewSession = false; } } else { _rqIsNewSession = true; _rqSessionStateNotFound = true; if (s_allowDelayedStateStoreItemCreation) { Debug.Trace("SessionStateModuleOnAcquireState", "Delay creating new session state"); delayInitStateStoreItem = true; } // We couldn't find the session state. if (!_rqIdNew && // If the request has a session id, that means the session state has expired s_configRegenerateExpiredSessionId && // And we're asked to regenerate expired session _rqSupportSessionIdReissue) { // And this request support session id reissue // We will generate a new session id for this expired session state bool redirected = CreateSessionId(); Debug.Trace("SessionStateModuleOnAcquireState", "Complete re-creating new id; redirected=" + redirected); if (redirected) { Debug.Trace("SessionStateModuleOnAcquireState", "Will redirect because we've reissued a new id and it's cookieless"); CreateUninitializedSessionState(); return; } } } if (delayInitStateStoreItem) { SessionStateUtility.AddDelayedHttpSessionStateToContext(_rqContext, this); _rqSessionState = s_delayedSessionState; } else { InitStateStoreItem(true); } if (_rqIsNewSession) { Debug.Trace("SessionStateModuleOnAcquireState", "Calling OnStart"); OnStart(EventArgs.Empty); } } finally { if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Information, EtwTraceFlags.AppSvc)) EtwTrace.Trace(EtwTraceType.ETW_TYPE_SESSION_DATA_END, _rqContext.WorkerRequest); } #if DBG if (_rqIsNewSession) { if (_rqId == null) { Debug.Assert(s_allowInProcOptimization, "s_allowInProcOptimization"); Debug.Trace("SessionStateModuleOnAcquireState", "New session: session id reading is delayed"+ "\nReturning from SessionStateModule::OnAcquireState"); } else { Debug.Trace("SessionStateModuleOnAcquireState", "New session: SessionId= " + _rqId + "\nReturning from SessionStateModule::OnAcquireState"); } } else { Debug.Trace("SessionStateModuleOnAcquireState", "Retrieved old session, SessionId= " + _rqId + "\nReturning from SessionStateModule::OnAcquireState"); } #endif }