/*
         *  This method is used to return an HttpContext for use outside of controllers. Use the Mock HttpContextBase for
         *  mocking with Controllers.
         */
        public static HttpContext GenerateBarebonesHttpContext(string requestURL)
        {
            var httpRequest  = new HttpRequest("", requestURL, "");
            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);

            httpContext.Items["AspSession"] =
                typeof(HttpSessionState).GetConstructor(
                    BindingFlags.NonPublic | BindingFlags.Instance,
                    null,
                    CallingConventions.Standard,
                    new[] { typeof(HttpSessionStateContainer) },
                    null).Invoke(new object[] { sessionContainer });

            return(httpContext);
        }
        public void Initialize()
        {
            var httpRequest = new HttpRequest(
                AppDomain.CurrentDomain.BaseDirectory, "http://www.local.myherbalife.com/Default.aspx", "");
            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;
        }
        public static HttpContext FakeHttpContext()
        {
            // source: https://stackoverflow.com/a/10126711/6887257
            var httpRequest  = new HttpRequest("", "http://stackoverflow/", "");
            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);

            httpContext.Items["AspSession"] = typeof(HttpSessionState).GetConstructor(
                BindingFlags.NonPublic | BindingFlags.Instance,
                null,
                CallingConventions.Standard,
                new[] { typeof(HttpSessionStateContainer) },
                null)
                                              .Invoke(new object[] { sessionContainer });

            return(httpContext);
        }
Esempio n. 4
0
        public HttpContext GetTestHttpContext()
        {
            var httpRequest  = new HttpRequest("", _siteUri.AbsoluteUri, "");
            var stringWriter = new StringWriter();
            var httpResponse = new HttpResponse(stringWriter);

            httpRequest.Browser = GetHttpBrowser();

            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 });

            httpContext.Items[Constants.CurrentCustomerInstanceKey] = GetCustomerInstance();

            //HttpContext.Current = httpContext;
            return(httpContext);
        }
Esempio n. 5
0
        public void sessionDestroyed(HttpSessionEvent se)
        {
            bool setDomain = [email protected]() == null;

            if (setDomain)
            {
                AppDomain servletDomain = (AppDomain)se.getSession().getServletContext().getAttribute(J2EEConsts.APP_DOMAIN);
                if (servletDomain == null)
                {
                    return;
                }
                [email protected](servletDomain);
            }
            try {
                HttpSessionStateContainer container =
                    ServletSessionStateStoreProvider.CreateContainer(se.getSession());

                SessionStateUtility.RaiseSessionEnd(container, this, EventArgs.Empty);
            }
            catch (Exception e) {
                Debug.WriteLine(e.Message);
                Debug.WriteLine(e.StackTrace);
            }
            finally {
                if (setDomain)
                {
                    [email protected]();
                }
            }
        }
        /// <summary>
        /// Check http://stackoverflow.com/questions/28405966/how-to-mock-applicationusermanager-from-accountcontroller-in-mvc5
        /// Check http://stackoverflow.com/questions/9624242/setting-httpcontext-current-session-in-a-unit-test
        /// </summary>
        /// <param name="userLoggedIn"></param>
        /// <returns></returns>
        internal static HttpContext CreateHttpContext(bool userLoggedIn)
        {
            var httpContext = new HttpContext(
                new HttpRequest(string.Empty, "http://sample.com", string.Empty),
                new HttpResponse(new StringWriter())
                )
            {
                User = userLoggedIn
                    ? new GenericPrincipal(new GenericIdentity("userName"), new string[0])
                    : new GenericPrincipal(new GenericIdentity(string.Empty), new string[0]),
            };

            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);
        }
Esempio n. 7
0
        //
        // Recursivly remove expired session data from session collection.
        //
        private void RemoveExpiredSessionData()
        {
            string sessionID;

            foreach (DictionaryEntry entry in pSessionItems)
            {
                SessionItem item = (SessionItem)entry.Value;

                if (DateTime.Compare(item.Expires, DateTime.Now) <= 0)
                {
                    sessionID = entry.Key.ToString();
                    pSessionItems.Remove(entry.Key);

                    HttpSessionStateContainer stateProvider =
                        new HttpSessionStateContainer(sessionID,
                                                      item.Items,
                                                      item.StaticObjects,
                                                      pTimeout,
                                                      false,
                                                      pCookieMode,
                                                      SessionStateMode.Custom,
                                                      false);

                    SessionStateUtility.RaiseSessionEnd(stateProvider, this, EventArgs.Empty);
                    this.RemoveExpiredSessionData();
                    break;
                }
            }
        }
Esempio n. 8
0
        //</Snippet4>


        //<Snippet5>
        //
        // Event handler for HttpApplication.ReleaseRequestState
        //

        private void OnReleaseRequestState(object source, EventArgs args)
        {
            HttpApplication app     = (HttpApplication)source;
            HttpContext     context = app.Context;
            string          sessionID;

            // Read the session state from the context
            HttpSessionStateContainer stateProvider =
                (HttpSessionStateContainer)(SessionStateUtility.GetHttpSessionStateFromContext(context));

            // If Session.Abandon() was called, remove the session data from the local Hashtable
            // and execute the Session_OnEnd event from the Global.asax file.
            if (stateProvider.IsAbandoned)
            {
                try
                {
                    pHashtableLock.AcquireWriterLock(Int32.MaxValue);

                    sessionID = pSessionIDManager.GetSessionID(context);
                    pSessionItems.Remove(sessionID);
                }
                finally
                {
                    pHashtableLock.ReleaseWriterLock();
                }

                SessionStateUtility.RaiseSessionEnd(stateProvider, this, EventArgs.Empty);
            }

            SessionStateUtility.RemoveHttpSessionStateFromContext(context);
        }
        private static HttpContext FakeHttpContext(string userId)
        {
            var httpRequest  = new HttpRequest("", "http://google/", "");
            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);

            httpContext.Items["AspSession"] = typeof(HttpSessionState).GetConstructor(
                BindingFlags.NonPublic | BindingFlags.Instance,
                null, CallingConventions.Standard,
                new[] { typeof(HttpSessionStateContainer) },
                null)
                                              .Invoke(new object[] { sessionContainer });

            IPrincipal principal = null;

            principal = new GenericPrincipal(new GenericIdentity(userId),
                                             new string[0]);
            Thread.CurrentPrincipal = principal;
            httpContext.User        = principal;

            return(httpContext);
        }
        public static HttpContext FakeHttpContext()
        {
            var httpRequest  = new HttpRequest("", "http://rav-dsk-386/RMS/", "1208");
            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);

            httpContext.Items["AspSession"] = typeof(HttpSessionState).GetConstructor(
                BindingFlags.NonPublic | BindingFlags.Instance,
                null, CallingConventions.Standard,
                new[] { typeof(HttpSessionStateContainer) },
                null)
                                              .Invoke(new object[] { sessionContainer });

            string[] roles     = null;
            var      identity  = new GenericIdentity("RAVE-TECH.CO.IN\\jagmohan.rawat");
            var      principal = new GenericPrincipal(identity, roles);

            httpContext.User = principal;

            return(httpContext);
        }
Esempio n. 11
0
        private void InitializeSessionFakes()
        {
            var shimSession = new ShimECNSession();

            shimSession.Instance.CurrentUser = new User()
            {
                UserID   = 1,
                UserName = TestUser,
                IsActive = true
            };
            shimSession.Instance.CurrentBaseChannel = new BaseChannel {
                BaseChannelID = 1
            };
            ShimECNSession.CurrentSession = () => shimSession.Instance;
            var sessionContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(),
                                                                 new HttpStaticObjectsCollection(), 10, true,
                                                                 HttpCookieMode.AutoDetect,
                                                                 SessionStateMode.InProc, false);

            _sessionState = typeof(HttpSessionState).GetConstructor(
                BindingFlags.NonPublic | BindingFlags.Instance,
                null, CallingConventions.Standard,
                new[] { typeof(HttpSessionStateContainer) },
                null)
                            .Invoke(new object[] { sessionContainer }) as HttpSessionState;
            ShimPage.AllInstances.SessionGet = (p) =>
            {
                return(_sessionState);
            };
            ShimUserControl.AllInstances.SessionGet = (c) =>
            {
                return(_sessionState);
            };
            ReflectionHelper.CreateInstance(typeof(SF_Search));
        }
Esempio n. 12
0
        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
                       ));
        }
Esempio n. 13
0
        public void TestSetupCoordinatesInvalid()
        {
            var httpRequest = new HttpRequest("", "http://localhost/", "coordinates=M,M,M,M,M,M,M");

            var httpResponce = new HttpResponse(new 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;
        }
        private void InitStateStoreItem(bool addToContext)
        {
            Debug.Assert(_rqId != null, "_rqId != null");

            if (_rqItem == null)
            {
                _rqItem = _store.CreateNewStoreData(_rqContext, s_timeout);
            }

            _rqSessionItems = _rqItem.Items;
            if (_rqSessionItems == null)
            {
                throw new HttpException(string.Format(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(
                _rqId,
                _rqSessionItems,
                _rqStaticObjects,
                _rqItem.Timeout,
                _rqIsNewSession,
                ConfigCookieless,
                s_configMode,
                _rqReadonly);

            if (addToContext)
            {
                SessionStateUtility.AddHttpSessionStateToContext(_rqContext.ApplicationInstance.Context, _rqSessionState);
            }
        }
Esempio n. 15
0
        protected override void SetPageSessionContext()
        {
            base.SetPageSessionContext();
            var sessionContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(),
                                                                 new HttpStaticObjectsCollection(), 10, true,
                                                                 HttpCookieMode.AutoDetect,
                                                                 SessionStateMode.InProc, false);
            var sessionState = typeof(HttpSessionState).GetConstructor(
                BindingFlags.NonPublic | BindingFlags.Instance,
                null, CallingConventions.Standard,
                new[] { typeof(HttpSessionStateContainer) },
                null)
                               .Invoke(new object[] { sessionContainer }) as HttpSessionState;

            ShimUserControl.AllInstances.SessionGet = (p) =>
            {
                return(sessionState);
            };
            _surveyReportInstance      = new SurveyReport();
            _shimSurveyReport          = new ShimSurveyReport(_surveyReportInstance);
            _surveyReportPrivateObject = new PrivateObject(_surveyReportInstance);
            InitializeAllControls(_surveyReportInstance);
            var shimEcnSession = new ShimECNSession();

            ShimECNSession.CurrentSession = () => shimEcnSession;
            ECNSession.CurrentSession().CurrentUser = new User()
            {
                UserID = 10
            };
            _viewState = GetPropertyOrField <StateBag>("ViewState");
        }
Esempio n. 16
0
        public static HttpContext GetHttpContext()
        {
            // We need to setup the Current HTTP Context as follows:

            // Step 1: Setup the HTTP Request
            var httpRequest = new HttpRequest(string.Empty, "http://localhost/", string.Empty);

            // Step 2: Setup the HTTP Response
            var httpResponse = new HttpResponse(new StringWriter());

            // Step 3: Setup the Http Context
            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 HttpContext InitializeHttpContext()
        {
            var testContext = new HttpContext(
                new HttpRequest("", "http://dotnet.try0.jp", ""),
                new HttpResponse(new StringWriter())
                );


            var sessionStateContainer = new HttpSessionStateContainer(
                "",
                new SessionStateItemCollection(),
                new HttpStaticObjectsCollection(),
                20000,
                true,
                HttpCookieMode.UseCookies,
                SessionStateMode.InProc,
                false
                );

            SessionStateUtility.AddHttpSessionStateToContext(testContext, sessionStateContainer);

            HttpContext.Current = testContext;

            FeedbackMessageStore.Initialize(FeedbackMessageStoreHolder.Instance);
            return(testContext);
        }
Esempio n. 18
0
        /// <summary>Sets the HTTP context with a valid simulated request.</summary>
        /// <param name="host">The host that must be associated with the session. Normally 'localhost' will suffice.</param>
        /// <param name="application">The name of the application that requires the session. Any name will do.</param>
        /// <exception cref="ArgumentNullException"><paramref name="host"/> or <paramref name="application"/> is <see langword="null"/> or empty.</exception>
        public static void SetHttpContextWithSimulatedRequest(string host, string application)
        {
            Guard.ArgumentIsNotNullOrEmpty(host, nameof(host), "Specify a valid host");
            Guard.ArgumentIsNotNullOrEmpty(application, nameof(application), "Specify a valid application");

            if (HttpContext.Current != null)
            {
                HttpContext.Current.Session.Clear();
            }
            else
            {
                /* These values are purely to satisfy the constructors of the HttpContext related objects. They don't have to represent a real-life
                 * web-application.*/
                string     appVirtualDir  = "/";
                string     appPhysicalDir = @"d:\projects\Web\";
                string     page           = application.Replace("/", string.Empty) + "/default.aspx";
                string     query          = string.Empty;
                TextWriter output         = null;

                SimulatedHttpRequest workerRequest = new SimulatedHttpRequest(appVirtualDir, appPhysicalDir, page, query, output, host);
                HttpContext.Current = new HttpContext(workerRequest);
                HttpSessionStateContainer session = new HttpSessionStateContainer(Guid.NewGuid().ToString(), new SessionStateItemCollection(),
                                                                                  SessionStateUtility.GetSessionStaticObjects(HttpContext.Current), 30, true, HttpCookieMode.AutoDetect, SessionStateMode.Custom, false);

                SessionStateUtility.AddHttpSessionStateToContext(HttpContext.Current, session);
            }
        }
Esempio n. 19
0
        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);
        }
Esempio n. 20
0
        public void TestSetup()
        {
            // We need to setup the Current HTTP Context as follows:

            // Step 1: Setup the HTTP Request
            var httpRequest = new HttpRequest("", "http://5051.azurewebsites.net/", "");

            // 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("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 });

            // Step 4: Assign the Context
            HttpContext.Current = httpContext;
        }
Esempio n. 21
0
        public MockHttpContext(bool isSecure)
            : this()
        {
            Thread.GetDomain().SetData(
                MockHttpContext.ThreadDataKeyAppPath, MockHttpContext.ThreadDataKeyAppPathValue);
            Thread.GetDomain().SetData(
                MockHttpContext.ThreadDataKeyAppVPath, MockHttpContext.ThreadDataKeyAppVPathValue);
            SimpleWorkerRequest request = new WorkerRequest(MockHttpContext.WorkerRequestPage,
                                                            string.Empty, new StringWriter(), isSecure);

            this.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;

            this.context.Items[ContextKeyAspSession] = state;
        }
Esempio n. 22
0
 public void RaiseOnEnd(HttpSessionStateContainer sessionStateContainer)
 {
     if (_sessionEndEventHandlerCount > 0)
     {
         SessionStateUtility.RaiseSessionEnd(sessionStateContainer, this, EventArgs.Empty);
     }
 }
Esempio n. 23
0
        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"]);
        }
Esempio n. 24
0
        private void CreateMasterPage()
        {
            var master = new ecn.communicator.MasterPages.Communicator();

            InitializeAllControls(master);
            ShimPage.AllInstances.MasterGet = (instance) => master;
            ShimECNSession.CurrentSession   = () => {
                var session = (ECNSession) new ShimECNSession();
                session.CurrentUser        = new User();
                session.CurrentCustomer    = new Customer();
                session.CurrentBaseChannel = new BaseChannel();
                return(session);
            };
            var sessionContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(),
                                                                 new HttpStaticObjectsCollection(), 10, true,
                                                                 HttpCookieMode.AutoDetect,
                                                                 SessionStateMode.InProc, false);
            var sessionState = typeof(HttpSessionState).GetConstructor(
                BindingFlags.NonPublic | BindingFlags.Instance,
                null, CallingConventions.Standard,
                new[] { typeof(HttpSessionStateContainer) },
                null)
                               .Invoke(new object[] { sessionContainer }) as HttpSessionState;

            ShimUserControl.AllInstances.SessionGet = (p) => sessionState;
        }
        public FakeHttpContext()
        {
            Request = new FakeRequest(_fakeWorkerRequest);

            _conextBackup = HttpContext.Current;
            Switchers.Add(_fakeHostEnvironment);

            HttpContext.Current = new HttpContext(_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 });
        }
Esempio n. 26
0
        public HttpContext FakeHttpContext(Dictionary <string, object> sessionVariables, string path)
        {
            var httpRequest  = new HttpRequest(string.Empty, path, string.Empty);
            var stringWriter = new StringWriter();
            var httpResponce = new HttpResponse(stringWriter);
            var httpContext  = new HttpContext(httpRequest, httpResponce);

            httpContext.User        = new GenericPrincipal(new GenericIdentity("username"), new string[0]);
            Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity("username"), new string[0]);
            var sessionContainer = new HttpSessionStateContainer(
                "id",
                new SessionStateItemCollection(),
                new HttpStaticObjectsCollection(),
                10,
                true,
                HttpCookieMode.AutoDetect,
                SessionStateMode.InProc,
                false);

            foreach (var var in sessionVariables)
            {
                sessionContainer.Add(var.Key, var.Value);
            }

            SessionStateUtility.AddHttpSessionStateToContext(httpContext, sessionContainer);
            return(httpContext);
        }
Esempio n. 27
0
        /**********************************************************************
         * Purpose: Fakes an http current context needed for any tests dealing with
         * the ProfileDBRepository
         ***********************************************************************/
        private void FakeCurrentHttpContext()
        {
            //fake an http request by making one of my onwn
            var httpRequest  = new HttpRequest("", "http://mySomething/", "");
            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 });

            //assign it as the current http request
            HttpContext.Current = httpContext;

            //assign session varibales for the important data in the app
            //this makes it so the tests will actually work
            HttpContext.Current.Session["userID"]    = _testUserID;
            HttpContext.Current.Session["userEmail"] = _testEmail;
            HttpContext.Current.Session["profileID"] = _testProfileID;
        }
Esempio n. 28
0
 public HttpContextManager()
 {
     _sessionContainer = new HttpSessionStateContainer(Guid.NewGuid().ToString("N"),
                                                       new SessionStateItemCollection(),
                                                       new HttpStaticObjectsCollection(), 10, true,
                                                       HttpCookieMode.AutoDetect,
                                                       SessionStateMode.InProc, false);
 }
        protected virtual void SetPageSessionContext()
        {
            RedirectUrl = string.Empty;
            ApplicationState.Clear();

            _shimObject = ShimsContext.Create();
            context     = new HttpContext(new HttpRequest("", "http://km.com", ""),
                                          new HttpResponse(TextWriter.Null));

            ShimHttpContext.CurrentGet = () => { return(context); };

            var sessionContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(),
                                                                 new HttpStaticObjectsCollection(), 10, true,
                                                                 HttpCookieMode.AutoDetect,
                                                                 SessionStateMode.InProc, false);
            var sessionState = typeof(HttpSessionState).GetConstructor(
                BindingFlags.NonPublic | BindingFlags.Instance,
                null, CallingConventions.Standard,
                new[] { typeof(HttpSessionStateContainer) },
                null)
                               .Invoke(new object[] { sessionContainer }) as HttpSessionState;

            ShimPage.AllInstances.SessionGet = (p) =>
            {
                return(sessionState);
            };

            ShimHttpContext.AllInstances.SessionGet = (p) =>
            {
                return(sessionState);
            };

            ShimPage.AllInstances.ResponseGet = (p) =>
            {
                return(new System.Web.HttpResponse(TextWriter.Null));
            };

            ShimHttpResponse.AllInstances.RedirectStringBoolean = (r, url, s) =>
            {
                RedirectUrl  = url;
                PageRedirect = true;
            };
            ShimPage.AllInstances.RequestGet = (p) =>
            {
                return(new HttpRequest("test", "http://km.com", ""));
            };

            ShimHttpRequest.AllInstances.QueryStringGet = (r) =>
            {
                return(QueryString);
            };
            ShimHttpRequest.AllInstances.RawUrlGet                    = (r) => string.Empty;
            ShimHttpRequest.AllInstances.ServerVariablesGet           = (r) => QueryString;
            ShimHttpApplication.AllInstances.ResponseGet              = (h) => new System.Web.HttpResponse(TextWriter.Null);
            ShimHttpApplication.AllInstances.RequestGet               = (h) => new HttpRequest("test", "http://km.com", "");
            ShimHttpApplication.AllInstances.ApplicationGet           = (h) => new ShimHttpApplicationState();
            ShimHttpApplicationState.AllInstances.ItemSetStringObject = (a, o, h) => { ApplicationState.Add(o, h); };
        }
        private void InitializeSession()
        {
            ShimECNSession.AllInstances.RefreshSession = (item) => { };
            ShimECNSession.AllInstances.ClearSession   = (itme) => { };
            var customerID     = 1;
            var userID         = 1;
            var config         = new NameValueCollection();
            var reqParams      = new NameValueCollection();
            var queryString    = new NameValueCollection();
            var dummyCustormer = ReflectionHelper.CreateInstance(typeof(Customer));
            var dummyUser      = ReflectionHelper.CreateInstance(typeof(User));
            var authTkt        = ReflectionHelper.CreateInstance(typeof(ECN_Framework_Entities.Application.AuthenticationTicket));
            var ecnSession     = ReflectionHelper.CreateInstance(typeof(ECNSession));

            config.Add("KMCommon_Application", KMCommon_Application);
            queryString.Add("HTTP_HOST", SampleHttpHost);
            queryString.Add("CampaignItemTemplateID", CampaignItemTemplateID);
            dummyCustormer.CustomerID = customerID;
            dummyUser.UserID          = userID;
            ReflectionHelper.SetField(authTkt, "CustomerID", customerID);
            ReflectionHelper.SetField(ecnSession, "CurrentUser", dummyUser);
            ReflectionHelper.SetField(ecnSession, "CurrentCustomer", dummyCustormer);
            HttpContext.Current                             = MockHelpers.FakeHttpContext();
            ShimECNSession.CurrentSession                   = () => ecnSession;
            ShimAuthenticationTicket.getTicket              = () => authTkt;
            ShimUserControl.AllInstances.RequestGet         = (x) => HttpContext.Current.Request;
            ShimUserControl.AllInstances.ResponseGet        = (x) => HttpContext.Current.Response;
            ShimConfigurationManager.AppSettingsGet         = () => config;
            ShimHttpRequest.AllInstances.UserAgentGet       = (h) => SampleUserAgent;
            ShimHttpRequest.AllInstances.QueryStringGet     = (h) => queryString;
            ShimHttpRequest.AllInstances.UserHostAddressGet = (h) => SampleHost;
            ShimHttpRequest.AllInstances.UrlReferrerGet     = (h) => new Uri(SampleHostPath);
            ShimPage.AllInstances.SessionGet                = x => HttpContext.Current.Session;
            ShimPage.AllInstances.RequestGet                = (x) => HttpContext.Current.Request;
            ShimHttpRequest.AllInstances.ParamsGet          = (x) => reqParams;
            ShimControl.AllInstances.ParentGet              = (control) => new Page();
            ShimGridView.AllInstances.DataBind              = (x) => { };
            var sessionContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(),
                                                                 new HttpStaticObjectsCollection(), 10, true,
                                                                 HttpCookieMode.AutoDetect,
                                                                 SessionStateMode.InProc, false);

            _sessionState = typeof(HttpSessionState).GetConstructor(
                BindingFlags.NonPublic | BindingFlags.Instance,
                null, CallingConventions.Standard,
                new[] { typeof(HttpSessionStateContainer) },
                null)
                            .Invoke(new object[] { sessionContainer }) as HttpSessionState;
            ShimPage.AllInstances.SessionGet = (p) =>
            {
                return(_sessionState);
            };
            ShimUserControl.AllInstances.SessionGet = (c) =>
            {
                return(_sessionState);
            };
        }