public void SIMPL_user_timesout_then_logs_back_in_gets_correct_return_url()
        {
            using (ShimsContext.Create())
            {
                // Arrange
                //Given a user
                const string userName = "******";
                const string password = "******";
                const string returnUrl = "/SIMPLNET/Subscriber?subID=370001704986|state=WA|billingRegion=";

                const string redirectURL = "/SIMPLNET/Subscriber?subID=370001704986&state=WA&billingRegion=";
                var session = new System.Web.SessionState.Fakes.ShimHttpSessionState()
                {
                    ItemGetString = (key) =>
                    {
                        return key == "CurrentUser" ? new ShimCurrentUser() : null;
                    }
                };
                var context = new System.Web.Fakes.ShimHttpContext();
                var applicationShim = new System.Web.Fakes.ShimHttpApplicationState();
                context.ApplicationGet = delegate { return applicationShim; };
                var requestStub = new StubHttpRequestBase();
                var contextStub = new StubHttpContextBase { RequestGet = () => requestStub };

                System.Web.Fakes.ShimHttpContext.CurrentGet = delegate { return context; };
                System.Web.Fakes.ShimHttpContext.AllInstances.SessionGet = delegate { return session; };

                ShimUserEvents.AllInstances.InitializeSessionStringString = delegate { };
                ShimSingleConcurrentLoginManager.AllInstances.CreateLoginRecordStringString = delegate { return true; };

                ShimCurrentUser.SetInstanceString = delegate {  };
                ShimCurrentUser.Clear = delegate { };
                ShimCurrentUser.SessionInstanceGet = delegate { return new ShimCurrentUser(); };
                ShimLoginModel.AllInstances.SyncWithOrImportDataFromASPPIErrorLoggingServiceString = (loginModel, errorLoggingService, userNameSentToLoginModel) =>
                {
                };

                ShimSingleConcurrentLoginManager.AllInstances.CreateLoginRecordStringString = delegate { return true; };

                ShimFormsAuthentication.SetAuthCookieStringBooleanString = delegate {  };

                //And an known AD username and password
                ShimUserManagement.AllInstances.AuthenticateStringString = delegate { return ASPP.UserManagement.AuthenticationResults.Success; };

                //And the AD username does not exist in ASPP
                ShimUserManagement.AllInstances.GetUserDetailsString = delegate { return new ASPP_Users(); };
                ShimUserManagement.AllInstances.GetUserGroupsString = delegate
                {
                    return new List<ASPP_Groups>
                    {
                        new ASPP_Groups()
                    };
                };

                LoginControllerForTests.ControllerContext = new ControllerContext { HttpContext = contextStub };

                //When attempting to log in to SIMPL
                var resultUserLogin = LoginControllerForTests.UserLogin(userName, password, returnUrl);

                //Then an error is reported to the user to log in using their ASPP credentials
                Assert.IsNotNull(resultUserLogin);
            #pragma warning disable 183
                // ReSharper generates a warning on the next line, but having this check will guarantee that the return type is checked before the other asserts
                Assert.IsTrue(resultUserLogin is ActionResult, "The return from the UserLogin action method was not a ActionResult");
            #pragma warning restore 183
                Assert.IsTrue(resultUserLogin is RedirectResult, "The return from the UserLogin action method was not a ViewResult");

                var resultUserLoginAsRedirectResult = resultUserLogin as RedirectResult;

                Assert.AreEqual(redirectURL, resultUserLoginAsRedirectResult.Url, string.Format("The RedirectUrl is {0}, should redirect to {1}", resultUserLoginAsRedirectResult.Url, redirectURL));

            }
        }
        public void A_user_can_associate_SIMPL_username_to_their_corp_username()
        {
            using (ShimsContext.Create())
            {
                //Setup

                var session = new System.Web.SessionState.Fakes.ShimHttpSessionState()
                {
                    ItemGetString = (key) =>
                    {
                        return key == "CurrentUser" ? new ShimCurrentUser() : null;
                    }
                };
                var context = new System.Web.Fakes.ShimHttpContext();
                var applicationShim = new System.Web.Fakes.ShimHttpApplicationState();
                context.ApplicationGet = delegate { return applicationShim; };

                System.Web.Fakes.ShimHttpContext.CurrentGet = delegate { return context; };
                System.Web.Fakes.ShimHttpContext.AllInstances.SessionGet = delegate { return session; };

                ShimUserEvents.AllInstances.InitializeSessionStringString = delegate { };
                ShimSingleConcurrentLoginManager.AllInstances.CreateLoginRecordStringString = delegate { return true; };
                var calledSetCurrentUser = false;
                ShimCurrentUser.SetInstanceString = delegate { calledSetCurrentUser = true; };
                ShimCurrentUser.Clear = delegate { };
                ShimCurrentUser.SessionInstanceGet = delegate { return new ShimCurrentUser(); };
                ShimLoginModel.AllInstances.SyncWithOrImportDataFromASPPIErrorLoggingServiceString = (loginModel, errorLoggingService, userNameSentToLoginModel) =>
                {
                };
                var calledSetAuthCookie = false;
                ShimFormsAuthentication.SetAuthCookieStringBooleanString = delegate { calledSetAuthCookie = true; };

                // Given a user
                const string corpUserName = "******";
                const string corpPassword = "******";
                const string simplUserName = "******";
                const string simplPassword = "******";
                var requestStub = new StubHttpRequestBase();
                var contextStub = new StubHttpContextBase {RequestGet = () => requestStub};

                var calledUpdateHistoricalRecored = false;
                ShimUserRepository.AllInstances.UpdateHistoricalRecordStringString = delegate
                {
                    calledUpdateHistoricalRecored = true;
                    return true;
                };

                var userAssociationModel = new AssociationViewModel();

                // And has known corp credentials
                userAssociationModel.UserName = corpUserName;
                userAssociationModel.Password = corpPassword;

                // And has known SIMPL credentials
                userAssociationModel.SIMPLUserName = simplUserName;
                userAssociationModel.SIMPLPassword = simplPassword;

                var wasAttemptToLogUserInCalledForCorp = false;
                var wasAttemptToLogUserInCalledForSIMPL = false;
                ShimLoginModel.AllInstances.AttemptToLogUserInStringString = (loginModel, userName, password) =>
                {
                    if (wasAttemptToLogUserInCalledForCorp && wasAttemptToLogUserInCalledForSIMPL)
                    {
                        return new LoginModel();
                    }
                    if (userName == corpUserName && password == corpPassword)
                    {
                        wasAttemptToLogUserInCalledForCorp = true;
                        return new LoginModel()
                        {
                            Message = SIMPL.Models.Code.Constants.Areas.Common.LoginModel.AuthenticationResultMessages.NoUserRoles
                        };
                    }
                    if (userName == simplUserName && password == simplPassword)
                    {
                        wasAttemptToLogUserInCalledForSIMPL = true;
                        return new LoginModel();
                    }
                    return new LoginModel()
                    {
                        Errors = true,
                        Message = SIMPL.Models.Code.Constants.Areas.Common.LoginModel.AuthenticationResultMessages.UnknownResult
                    };
                };

                // And corp username doesn’t match SIMPL username
                // When submitting the association form
                ShimUserManagement.AllInstances.UpdateUsernameStringString = delegate { return UserManagement.UpdateUsernameResult.Success; };
                LoginControllerForTests.ControllerContext = new ControllerContext { HttpContext = contextStub };
                var userAssociationResult = LoginControllerForTests.UserNameAssociation(userAssociationModel);

                // Then usernames are associated
                Assert.IsTrue(wasAttemptToLogUserInCalledForCorp, "Corp credential were not Authorized");
                Assert.IsTrue(wasAttemptToLogUserInCalledForSIMPL, "SIMPL credentials were not Authorized");
                Assert.IsTrue(calledUpdateHistoricalRecored, "UpdateHistoricalRecords was not called");
                Assert.IsNotNull(userAssociationResult);
                #pragma warning disable 183
                // ReSharper generates a warning on the next line, but having this check will guarantee that the return type is checked before the other asserts
                Assert.IsTrue(userAssociationResult is ActionResult, "The return from the UserLogin action method was not a ActionResult");
                #pragma warning restore 183
                Assert.IsTrue(userAssociationResult is RedirectResult, "The return from the UserLogin action method was not a RedirectResult");

                // And user is logged in
                Assert.IsTrue(calledSetCurrentUser, "The set CurrentUser was never called");
                Assert.IsTrue(calledSetAuthCookie, "The set Authorization cookie was never called");

                // And a message is displayed stating “Username association successful! Please use your corp credentials for future logins to SIMPL.”
                var redirectResult = userAssociationResult as RedirectResult;
                Assert.AreEqual("~/SIMPLNET/Search", redirectResult.Url, "The redirect URL was not the search page which should be called when you have a successful login");
            }
        }
        /// <summary>
        /// The get shim http context base, used for tests. Must be encapsulated in
        /// using (ShimsContext.Create())
        /// {}
        /// statement.
        /// </summary>
        /// <param name="useCookie">
        /// Set to true if cookies are used.
        /// </param>
        /// <returns>
        /// Shimmed httpContextBase. <see cref="HttpContextBase"/>.
        /// </returns>
        private static HttpContext GetShimHttpContext(bool useCookie = true)
        {
            string[] allFactorEnumFieldValueKeys  = new string[] { "factorEnumFieldValue_1091_0_0_1097_2" };
            string[] allFactorEnumFieldValueKeys2 = new string[] { "factorEnumFieldValue2_1091_0_0_1097_2" };
            string[] allFactorEnumFieldValueKeys3 = new string[] { "factorEnumFieldValue3_1091_0_0_1097_2" };
            string   key1 = "1";
            string   key2 = "2";
            string   key3 = "3";

            NameValueCollection nameValueCollection = new NameValueCollection();

            nameValueCollection.Add("factorEnumFieldValue_1091_0_0_1097_2", key1);
            nameValueCollection.Add("factorEnumFieldValue2_1091_0_0_1097_2", key2);
            nameValueCollection.Add("factorEnumFieldValue3_1091_0_0_1097_2", key3);

            //var mockHttpContext = MockRepository.GenerateStub<HttpContextBase>();
            //mockHttpContext.Stub(c => c.Request.Form.AllKeys).Return(allFactorEnumFieldValueKeys).Repeat.Any();
            ////mockHttpContext.Stub(c => c.Request.Form.AllKeys.Where(key => key.StartsWith("factorEnumFieldValue_"))).Return(allFactorEnumFieldValueKeys).Repeat.Any();
            ////mockHttpContext.Stub(c => c.Request.Form.AllKeys.Where(key => key.StartsWith("factorEnumFieldValue2_"))).Return(allFactorEnumFieldValueKeys2).Repeat.Any();
            ////mockHttpContext.Stub(c => c.Request.Form.AllKeys.Where(key => key.StartsWith("factorEnumFieldValue3_"))).Return(allFactorEnumFieldValueKeys3).Repeat.Any();
            //
            //mockHttpContext.Stub(c => c.Request.Form).Return(value).Repeat.Any();



            var cookie = new HttpCookieCollection();

            cookie.Add(new HttpCookie("CultureInfo", "en-GB"));
            var queryString = new NameValueCollection();

            queryString.Add("error", "false");
            queryString.Add("handler", "true");
            var cultureInfo = new HttpCookie("CultureInfo", "en-GB");

            if (useCookie)
            {
                cookie.Add(cultureInfo);
            }

            HttpRequest stubHttpRequestBase = new System.Web.Fakes.ShimHttpRequest()
            {
                CookiesGet = () => { return(cookie); },
                FormGet    = () =>
                {
                    if (true)
                    {
                        return(nameValueCollection);
                    }
                    else
                    {
                        return(nameValueCollection);
                    }
                },
                QueryStringGet = () => { return(queryString); },
            };


            HttpResponse response = new System.Web.Fakes.ShimHttpResponse()
            {
                CookiesGet = () => { return(cookie); }
            };
            HttpServerUtilityBase untilityBase = new System.Web.Fakes.StubHttpServerUtilityBase()
            {
                UrlEncodeString = (info) => { return(cultureInfo.ToString()); },
                MapPathString   = (path) => { return(SelectedPath); }
            };
            HttpServerUtility untility = new System.Web.Fakes.ShimHttpServerUtility()
            {
                UrlEncodeString = (info) => { return(cultureInfo.ToString()); },
                MapPathString   = (path) => { return(SelectedPath); },
            };



            HttpApplicationState state = new System.Web.Fakes.ShimHttpApplicationState()
            {
                AddStringObject = (cacheKey, userContext) =>
                {
                    IUserContext tempContext = userContext as IUserContext;

                    if (tempContext.Locale.Id == DyntaxaTestSettings.Default.SwedishLocaleId)
                    {
                        ApplicationUserContextSV = tempContext;
                    }
                    else
                    {
                        ApplicationUserContext = tempContext;
                    }
                }
            };

            var context = new ShimHttpContext
            {
                ApplicationGet = () => { return(state); },
                RequestGet     = () => { return(stubHttpRequestBase); },
                ResponseGet    = () => { return(response); },
                ServerGet      = () => { return(untility); }
            };

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


            // Create session varables
            var session = new System.Web.SessionState.Fakes.ShimHttpSessionState()
            {
                ItemGetString = (key) =>
                {
                    if (key == DyntaxaSettings.Default.ApplicationContextCacheKey)
                    {
                        return(ApplicationUserContext);
                    }
                    else if (key == DyntaxaSettings.Default.ApplicationContextCacheKey + DyntaxaTestSettings.Default.EnglishLocale)
                    {
                        return(ApplicationUserContext);
                    }
                    else if (key == DyntaxaSettings.Default.ApplicationContextCacheKey + DyntaxaTestSettings.Default.SwedishLocale)
                    {
                        return(ApplicationUserContextSV);
                    }
                    else if (key == "userContext")
                    {
                        if (UserContextData.IsNotNull())
                        {
                            return(UserContextData);
                        }
                        else
                        {
                            return(ApplicationUserContext);
                        }
                    }
                    else if (key == "RevisionId")
                    {
                        return(SessionRevisionId);
                    }
                    else if (key == "TaxonId")
                    {
                        return(SessionTaxonId);
                    }
                    else if (key == "Revision")
                    {
                        return(SessionRevision);
                    }
                    else if (key == "SpeciesFactHostTaxonIdList")
                    {
                        return(SessionSpeciesFactHostTaxonIdList);
                    }
                    return(null);
                },
                ItemSetStringObject = (key, sessionObject) =>
                {
                    if (key == "TaxonId")
                    {
                        SessionTaxonId = sessionObject as TaxonIdTuple;
                    }
                },
            };


            System.Web.Fakes.ShimHttpContext.AllInstances.SessionGet =
                (o) =>
            {
                return(session);
            };

            // Creat cash varables
            var cache = new System.Web.Caching.Fakes.ShimCache()
            {
                ItemGetString = (key) =>
                {
                    if (key == DyntaxaSettings.Default.ApplicationContextCacheKey)
                    {
                        return(ApplicationUserContext);
                    }
                    else if (key == DyntaxaSettings.Default.ApplicationContextCacheKey + DyntaxaTestSettings.Default.EnglishLocale)
                    {
                        return(ApplicationUserContext);
                    }
                    else if (key == DyntaxaSettings.Default.ApplicationContextCacheKey + DyntaxaTestSettings.Default.SwedishLocale)
                    {
                        return(ApplicationUserContextSV);
                    }
                    else if (key == "userContext")
                    {
                        if (UserContextData.IsNotNull())
                        {
                            return(UserContextData);
                        }
                        else
                        {
                            return(ApplicationUserContext);
                        }
                    }
                    else if (key == "RevisionId")
                    {
                        return(SessionRevisionId);
                    }
                    else if (key == "TaxonId")
                    {
                        return(SessionTaxonId);
                    }
                    else if (key == "Revision")
                    {
                        return(SessionRevision);
                    }
                    else if (key == "SpeciesFactHostTaxonIdList")
                    {
                        return(SessionSpeciesFactHostTaxonIdList);
                    }
                    return(null);
                },
            };


            System.Web.Fakes.ShimHttpContext.AllInstances.CacheGet =
                (o) =>
            {
                return(cache);
            };

            return(context);
        }