Beispiel #1
0
        public void When_Basic_Cookie_Serialized()
        {
            var cookie     = new HttpCookie("test", "a.com", "/");
            var serialized = cookie.ToString();

            Assert.AreEqual("test=; Path=/; Domain=a.com", serialized);
        }
        public static HttpContextBase GetAccountControllerContext(bool useCookie = true)
        {
            var cookie = new HttpCookieCollection();

            if (useCookie)
            {
                cookie.Add(new HttpCookie("CultureInfo", "en-GB"));
            }
            var             cultureInfo         = new HttpCookie("CultureInfo", "en-GB");
            HttpRequestBase stubHttpRequestBase = new System.Web.Fakes.StubHttpRequestBase()
            {
                CookiesGet = () => { return(cookie); },
            };
            HttpResponseBase response = new System.Web.Fakes.StubHttpResponseBase()
            {
                CookiesGet = () => { return(cookie); }
            };
            HttpServerUtilityBase untilityBase = new System.Web.Fakes.ShimHttpServerUtilityBase(new StubHttpServerUtilityBase())
            {
                UrlEncodeString = (info) => { return(cultureInfo.ToString()); }
            };

            HttpContextBase stubHttpContext = new System.Web.Fakes.StubHttpContextBase()
            {
                RequestGet  = () => { return(stubHttpRequestBase); },
                ResponseGet = () => { return(response); },
                ServerGet   = () => { return(untilityBase); }
            };

            return(stubHttpContext);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            string     userName = "";
            HttpCookie userCookie;

            userCookie = Request.Cookies["UserID"];
            if (userCookie == null)
            {
                if (IsPrivateAccess(sender))
                {
                    Response.Redirect("~/Pages/Account/Login.aspx");
                }
                menu.Visible = false;
            }
            else
            {
                HttpCookie c1 = Request.Cookies["UserName"];
                if (c1 == null)
                {
                    userName = "******";
                }
                else
                {
                    userName = c1.Value;
                }

                HttpCookie c = Request.Cookies["UserCategory"];
                if (c == null)
                {
                    DoLogout();
                    Response.Redirect("~/Pages/Account/Login.aspx");
                }
                else if (!IsPrivateAccess(sender) && (Session["UserId"] == null))
                {
                    ManageMenuVisibility(c.ToString());
                    //send the user to the first page if is a public
                    if (c.Value == "Admin")
                    {
                        Response.Redirect("~/Pages/Dashboard/AdminDashboard.aspx");
                    }
                    else if (c.Value == "Moderator")
                    {
                        Response.Redirect("~/Pages/Dashboard/ModeratorDashboard.aspx");
                    }
                    else if (c.Value == "Faculty")
                    {
                        Response.Redirect("~/Pages/Dashboard/FacultyDashboard.aspx");
                    }
                    else if (c.Value == "Staff")
                    {
                        Response.Redirect("~/Pages/Dashboard/StaffDashboard.aspx");
                    }
                    else if (c.Value == "Student")
                    {
                        Response.Redirect("~/Pages/Dashboard/StudentDashboard.aspx");
                    }
                }
            }
        }
Beispiel #4
0
        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            string username   = string.Empty;
            string adEmail    = WebConfigurationManager.AppSettings["ADDefaultUserEmail"];
            string adPassword = WebConfigurationManager.AppSettings["ADDefaultUserPassword"];

            /* Return true immediately if the authorization is not
             * locked down to any particular AD group */
            if (String.IsNullOrEmpty(Groups))
            {
                _isInAuthorizedRule = false;
                return(_isAuthorized = false);
            }

            HttpCookie cookie = HttpContext.Current.Request.Cookies["userid"];

            if (String.IsNullOrEmpty(cookie.ToString()))
            {
                username = HttpContext.Current.User.Identity.Name;
            }
            else if (String.IsNullOrEmpty(HttpContext.Current.User.Identity.Name))
            {
                username = cookie.Value;
            }
            else
            {
                username = string.Empty;
            }

            if (string.IsNullOrEmpty(username))
            {
                _isInAuthorizedRule = false;
                return(_isAuthorized = false);
            }

            // Get the AD groups
            var groups = Groups.Split(',').ToList <string>();


            // set up domain context

            PrincipalContext context = new PrincipalContext(ContextType.Domain, Silicus.ProjectTracker.Core.Constants.DomainName, null, ContextOptions.SimpleBind, adEmail, adPassword);

            // find a user
            UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(context, username);

            foreach (var group in groups)
            {
                if (userPrincipal.IsMemberOf(context, IdentityType.Name, group))
                {
                    _isInAuthorizedRule = true;
                    return(_isAuthorized = true);
                }
            }

            _isInAuthorizedRule = false;
            return(_isAuthorized = false);
        }
Beispiel #5
0
        public void When_Cookie_Value_Invalid_Characters()
        {
            var cookie = new HttpCookie("test", "a.com", "/")
            {
                Value = ";;==;;"
            };
            var serialized = cookie.ToString();

            Assert.AreEqual("test=;;==;;; Path=/; Domain=a.com", serialized);
        }
Beispiel #6
0
        public void When_Cookie_With_Value_Serialized()
        {
            var cookie = new HttpCookie("test", "a.com", "/")
            {
                Value = "abc"
            };
            var serialized = cookie.ToString();

            Assert.AreEqual("test=abc; Path=/; Domain=a.com", serialized);
        }
Beispiel #7
0
        public void When_Cookie_With_Expires_Serialized()
        {
            var cookie = new HttpCookie("test", "a.com", "/")
            {
                Expires = new DateTimeOffset(2021, 12, 4, 3, 5, 13, TimeSpan.Zero),
            };
            var serialized = cookie.ToString();

            Assert.AreEqual("test=; Path=/; Domain=a.com; Expires=Sat, 04 Dec 2021 03:05:13 GMT", serialized);
        }
Beispiel #8
0
        public void When_Cookie_With_HttpOnly_Serialized()
        {
            var cookie = new HttpCookie("test", "a.com", "/")
            {
                HttpOnly = true
            };
            var serialized = cookie.ToString();

            Assert.AreEqual("test=; Path=/; Domain=a.com; HttpOnly", serialized);
        }
Beispiel #9
0
        /// <summary>
        /// 读取Cookie
        /// </summary>
        /// <param name="key">键</param>
        /// <returns></returns>
        public static string Get(string key)
        {
            var        cookieValue = string.Empty;
            HttpCookie cookie      = HttpContext.Current.Request.Cookies[key];

            if (cookie != null && cookie.ToString() != "")
            {
                cookieValue = cookie.Value;
            }
            return(cookieValue);
        }
Beispiel #10
0
        public void When_Cookie_With_All_Properties_Serialized()
        {
            var cookie = new HttpCookie("test", "subdomain.example.com", "/some/path")
            {
                Value    = "abc",
                Expires  = new DateTimeOffset(2021, 12, 4, 3, 5, 13, TimeSpan.Zero),
                HttpOnly = true,
                Secure   = true,
            };
            var serialized = cookie.ToString();

            Assert.AreEqual("test=abc; Path=/some/path; Domain=subdomain.example.com; Secure; HttpOnly; Expires=Sat, 04 Dec 2021 03:05:13 GMT", serialized);
        }
Beispiel #11
0
        public string  getSecureCookie(HttpRequest Request)
        {
            HttpCookie secureCookie = Request.Cookies["vsc"];

            if (secureCookie != null)
            {
                return(secureCookie.ToString());
            }
            else
            {
                return("");
            }
        }
Beispiel #12
0
        protected void btnNewPassword_Click(object sender, EventArgs e)
        {
            objCookie = Request.Cookies["theResetEmail"];
            string email = objCookie.ToString();

            string pass    = txtPass.Text.ToString();
            string confirm = txtConfirm.Text.ToString();

            if (validationOBJ.checkReset(email, pass, confirm) == 4)
            {
                dbCommand.Parameters.Clear();
                dbCommand.CommandType = CommandType.StoredProcedure;
                dbCommand.CommandText = "TP_UpdatePassword";
                SqlParameter inputParameter = new SqlParameter("@theEmail", email);
                inputParameter.Direction = ParameterDirection.Input;
                inputParameter.SqlDbType = SqlDbType.VarChar;
                inputParameter.Size      = 50;                           // 50-bytes ~ varchar(50)
                dbCommand.Parameters.Add(inputParameter);

                inputParameter           = new SqlParameter("@thePassword", pass);
                inputParameter.Direction = ParameterDirection.Input;
                inputParameter.SqlDbType = SqlDbType.VarChar;
                inputParameter.Size      = 50;                           // 50-bytes ~ varchar(50)
                dbCommand.Parameters.Add(inputParameter);

                // Execute the stored procedure using the DBConnect object and the SQLCommand object
                DataSet myDS = db.GetDataSetUsingCmdObj(dbCommand);

                Response.Redirect("Login.aspx");
            }
            else if (validationOBJ.checkReset(email, pass, confirm) == 1)
            {
                Response.Write(@"<script langauge='text/javascript'>alert
                ('These passwords don't match, try again');</script>");
                return;
            }
            else if (validationOBJ.checkReset(email, pass, confirm) == 2)
            {
                Response.Write(@"<script langauge='text/javascript'>alert
                ('One or both of these passwords have not been filled in, please fill in each form and try again');</script>");
                return;
            }
            else if (validationOBJ.checkReset(email, pass, confirm) == 3)
            {
                Response.Write(@"<script langauge='text/javascript'>alert
                ('This password matches your existing password, please make a new password  ');</script>");
                return;
            }
        }
        /// <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 HttpContextBase GetStubHttpContextBase(bool useCookie = true)
        {
            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);
            }

            HttpRequestBase stubHttpRequestBase = new System.Web.Fakes.StubHttpRequestBase()
            {
                CookiesGet     = () => { return(cookie); },
                FormGet        = () => { return(new NameValueCollection()); },
                QueryStringGet = () => { return(queryString); }
            };
            // Might be needed? instead of stubHttpRequestBase: HttpRequestWrapper httpRequestWrapper = new System.Web.Fakes.ShimHttpRequestWrapper()
            // {
            //    CookiesGet = () => { return cookie; },
            //    FormGet = () => { return new NameValueCollection(); },
            //    QueryStringGet = () => { return queryString; }
            // };

            HttpResponseBase response = new System.Web.Fakes.StubHttpResponseBase()
            {
                CookiesGet = () => { return(cookie); }
            };
            HttpServerUtilityBase untilityBase = new System.Web.Fakes.StubHttpServerUtilityBase()
            {
                UrlEncodeString = (info) => { return(cultureInfo.ToString()); }
            };

            HttpContextBase stubHttpContext = new System.Web.Fakes.StubHttpContextBase()
            {
                RequestGet  = () => { return(stubHttpRequestBase); },
                ResponseGet = () => { return(response); },
                ServerGet   = () => { return(untilityBase); }
            };

            return(stubHttpContext);
        }
Beispiel #14
0
        public bool CheckSet(string setId, string item)
        {
            HttpCookie cookie    = HttpContext.Current.Request.Cookies["RedisSessionId"];
            string     sessionId = cookie == null ? string.Empty : cookie.ToString();

            if (!string.IsNullOrEmpty(sessionId))
            {
                using (IRedisClient redisClent = RedisHelper.clientManager.GetClient())
                {
                    return(redisClent.SetContainsItem(sessionId + "%" + setId, item));
                }
            }
            else
            {
                return(false);
            }
        }
Beispiel #15
0
        public static DatosUsuario authenticationAtiveDiretory(string usuario, string password)
        {
            try
            {
                OpenService();

                DatosUsuario       datosUsuarios;
                LdapAuthentication adAuth = new LdapAuthentication(adPath);

                if (true == adAuth.IsAuthenticated(domain, usuario, password))
                {
                    string datosUsuario = getUsuarioPaisNavision(usuario);
                    if (string.IsNullOrEmpty(datosUsuario))
                    {
                        throw new Exception("Error al recuperar el país del usuario");
                    }
                    if (datosUsuario.Length > 2)
                    {
                        string codUsuario = datosUsuario.Split(';')[0];
                        string codPais    = datosUsuario.Split(';')[1];
                        string esJefe     = datosUsuario.Split(';')[2];
                        string email      = datosUsuario.Split(';')[3];
                        string grupo      = datosUsuario.Split(';')[4];



                        FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1, usuario, DateTime.Now, DateTime.Now.AddMinutes(60), false, codUsuario.ToString());
                        string     encryptedTicket           = FormsAuthentication.Encrypt(authTicket);
                        HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
                        HttpContext.Current.Response.Cookies.Add(authCookie);

                        datosUsuarios = new DatosUsuario(codUsuario, email, authCookie.ToString());
                        return(datosUsuarios);
                    }
                }
                else
                {
                    throw new Exception("El Usuario y/o Contraseña son incorrectos o la cuenta está deshabilitada. ");
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(null);
        }
Beispiel #16
0
        public HashSet <string> GetSet(string setId)
        {
            HttpCookie cookie    = HttpContext.Current.Request.Cookies["RedisSessionId"];
            string     sessionId = cookie == null ? string.Empty : cookie.ToString();

            if (!string.IsNullOrEmpty(sessionId))
            {
                using (IRedisClient redisClent = RedisHelper.clientManager.GetClient())
                {
                    return(redisClent.GetAllItemsFromSet(sessionId + "%" + setId));
                }
            }
            else
            {
                return(null);
            }
        }
Beispiel #17
0
        public bool AddSet(string setId, string value)
        {
            HttpCookie cookie    = HttpContext.Current.Request.Cookies["RedisSessionId"];
            string     sessionId = cookie == null ? string.Empty : cookie.ToString();

            if (!string.IsNullOrEmpty(sessionId))
            {
                using (IRedisClient redisClent = RedisHelper.clientManager.GetClient())
                {
                    redisClent.AddItemToSet(sessionId + "%" + setId, value);
                    return(true);
                }
            }
            else
            {
                return(false);
            }
        }
Beispiel #18
0
        public static Client GetClient(HttpRequest request)
        {
            HttpCookie uid = request.Cookies["uid"];
            HttpCookie pid = request.Cookies["pid"];

            if (uid == null || pid == null)
            {
                return(null);
            }

            Client clinet = Client.CreateManager().Load(uid.ToString());

            if (clinet == null)
            {
                return(null);
            }

            return(clinet);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                HttpCookie userCredentials = Request.Cookies["FirstForRentalsUserCredentials"];

                if (userCredentials != null)
                {
                    Session["userCredentials"] = userCredentials.ToString();
                    Response.Redirect("./Home.aspx");
                }

                if (_provider != null)
                {
                    HandleProviderResponse();
                }
            }
            else
            {
                HandleRequest();
            }
        }
        public static ControllerContext GetBaseControllerContext()
        {
            var cookie = new HttpCookieCollection();

            cookie.Add(new HttpCookie("CultureInfo", "en-GB"));
            var             cultureInfo = new HttpCookie("CultureInfo", "en-GB");
            HttpRequestBase request     = new System.Web.Fakes.ShimHttpRequestBase(new StubHttpRequestBase())
            {
                CookiesGet = () => { return(cookie); }
            };
            HttpResponseBase response = new System.Web.Fakes.ShimHttpResponseBase(new StubHttpResponseBase())
            {
                CookiesGet = () => { return(cookie); }
            };

            HttpServerUtilityBase untilityBase = new System.Web.Fakes.ShimHttpServerUtilityBase(new StubHttpServerUtilityBase())
            {
                UrlEncodeString = (info) => { return(cultureInfo.ToString()); }
            };

            HttpContextBase context = new System.Web.Fakes.ShimHttpContextBase(new StubHttpContextBase())
            {
                RequestGet  = () => { return(request); },
                ResponseGet = () => { return(response); },
                ServerGet   = () => { return(untilityBase); }
            };

            ControllerBase baseStub = new BaseController();//new System.Web.Mvc.Fakes.ShimControllerBase(new StubControllerBase())
            //{

            //};

            var routeData = new RouteData();



            return(new ControllerContext(context, routeData, baseStub));
        }
Beispiel #21
0
        public void SetCookie(SetCookieRequest request)
        {
            var httpCookie = new HttpCookie(request.Cookie.Name, request.Domain ?? string.Empty, request.Path ?? string.Empty)
            {
                Secure  = request.Secure,
                Expires = request.Expires,
                Value   = request.Cookie.Value,
            };
            var serializedCookie = httpCookie.ToString();

            if (request.MaxAge != null)
            {
                serializedCookie += $"; max-age={request.MaxAge.Value.ToString(CultureInfo.InvariantCulture)}";
            }
            if (request.SameSite != null)
            {
                serializedCookie += $"; samesite={request.SameSite.Value.ToString("g").ToLowerInvariant()}";
            }

            var escapedCookie = WebAssemblyRuntime.EscapeJs(serializedCookie);
            var jsInvoke      = $"document.cookie = '{escapedCookie}'";

            WebAssemblyRuntime.InvokeJS(jsInvoke);
        }
Beispiel #22
0
        [Test]         // bug #81333
        public void ToStringTest()
        {
            HttpCookie cookie;

            cookie = new HttpCookie("cookie1", "this x=y is the & first = cookie");
            Assert.AreEqual("System.Web.HttpCookie", cookie.ToString(), "#A1");
            Assert.AreEqual("this x=y is the & first = cookie", cookie.Value, "#A2");
            Assert.AreEqual(2, cookie.Values.Count, "#A3");
            Assert.AreEqual("this x", cookie.Values.GetKey(0), "#A4");
            Assert.AreEqual("y is the ", cookie.Values.Get(0), "#A5");
            Assert.AreEqual(" first ", cookie.Values.GetKey(1), "#A6");
            Assert.AreEqual(" cookie", cookie.Values.Get(1), "#A7");
            Assert.AreEqual("this+x=y+is+the+&+first+=+cookie",
                            cookie.Values.ToString(), "#A8");

            cookie = new HttpCookie("cookie11", cookie.Values.ToString());
            Assert.AreEqual("System.Web.HttpCookie", cookie.ToString(), "#B1");
            Assert.AreEqual("this+x=y+is+the+&+first+=+cookie", cookie.Value, "#B2");
            Assert.AreEqual(2, cookie.Values.Count, "#B3");
            Assert.AreEqual("this+x", cookie.Values.GetKey(0), "#B4");
            Assert.AreEqual("y+is+the+", cookie.Values.Get(0), "#B5");
            Assert.AreEqual("+first+", cookie.Values.GetKey(1), "#B6");
            Assert.AreEqual("+cookie", cookie.Values.Get(1), "#B7");
            Assert.AreEqual("this%2bx=y%2bis%2bthe%2b&%2bfirst%2b=%2bcookie",
                            cookie.Values.ToString(), "#B8");

            cookie = new HttpCookie("cookie2");
            cookie.Values ["first"]   = "hell=o = y";
            cookie.Values ["second"]  = "the&re";
            cookie.Values ["third"]   = "three";
            cookie.Values ["three-a"] = null;
            cookie.Values ["fourth"]  = "last value";
            Assert.AreEqual("System.Web.HttpCookie", cookie.ToString(), "#C1");
            Assert.AreEqual("first=hell=o = y&second=the&re&third=three&three"
                            + "-a=&fourth=last value", cookie.Value, "#C2");
            Assert.AreEqual(5, cookie.Values.Count, "#C3");
            Assert.AreEqual("first", cookie.Values.GetKey(0), "#C4");
            Assert.AreEqual("hell=o = y", cookie.Values.Get(0), "#C5");
            Assert.AreEqual("second", cookie.Values.GetKey(1), "#C6");
            Assert.AreEqual("the&re", cookie.Values.Get(1), "#C7");
            Assert.AreEqual("third", cookie.Values.GetKey(2), "#C8");
            Assert.AreEqual("three", cookie.Values.Get(2), "#C9");
            Assert.AreEqual("three-a", cookie.Values.GetKey(3), "#C10");
            Assert.IsNull(cookie.Values.Get(3), "#C11");
            Assert.AreEqual("fourth", cookie.Values.GetKey(4), "#C12");
            Assert.AreEqual("last value", cookie.Values.Get(4), "#C13");
            Assert.AreEqual("first=hell%3do+%3d+y&second=the%26re&third=three"
                            + "&three-a=&fourth=last+value", cookie.Values.ToString(), "#C14");

            cookie = new HttpCookie("cookie21", cookie.Values.ToString());
            Assert.AreEqual("System.Web.HttpCookie", cookie.ToString(), "#D1");
            Assert.AreEqual("first=hell%3do+%3d+y&second=the%26re&third=three"
                            + "&three-a=&fourth=last+value", cookie.Value, "#D2");
            Assert.AreEqual(5, cookie.Values.Count, "#D3");
            Assert.AreEqual("first", cookie.Values.GetKey(0), "#D4");
            Assert.AreEqual("hell%3do+%3d+y", cookie.Values.Get(0), "#D5");
            Assert.AreEqual("second", cookie.Values.GetKey(1), "#D6");
            Assert.AreEqual("the%26re", cookie.Values.Get(1), "#D7");
            Assert.AreEqual("third", cookie.Values.GetKey(2), "#D8");
            Assert.AreEqual("three", cookie.Values.Get(2), "#D9");
            Assert.AreEqual("three-a", cookie.Values.GetKey(3), "#D10");
            Assert.AreEqual("three-a", cookie.Values.GetKey(3), "#D11");
            Assert.AreEqual("fourth", cookie.Values.GetKey(4), "#D12");
            Assert.AreEqual("last+value", cookie.Values.Get(4), "#D13");
            Assert.AreEqual("first=hell%253do%2b%253d%2by&second=the%2526re&"
                            + "third=three&three-a=&fourth=last%2bvalue",
                            cookie.Values.ToString(), "#D14");

            cookie = new HttpCookie("cookie3", "this is & the x=y third = cookie");
            cookie.Values ["first"]  = "hel&l=o =y";
            cookie.Values ["second"] = "there";
            Assert.AreEqual("System.Web.HttpCookie", cookie.ToString(), "#E1");
            Assert.AreEqual("this is & the x=y third = cookie&first=hel&l=o =y"
                            + "&second=there", cookie.Value, "#E2");
            Assert.AreEqual(4, cookie.Values.Count, "#E3");
            Assert.IsNull(cookie.Values.GetKey(0), "#E4");
            Assert.AreEqual("this is ", cookie.Values.Get(0), "#E5");
            Assert.AreEqual(" the x", cookie.Values.GetKey(1), "#E6");
            Assert.AreEqual("y third = cookie", cookie.Values.Get(1), "#E7");
            Assert.AreEqual("first", cookie.Values.GetKey(2), "#E8");
            Assert.AreEqual("hel&l=o =y", cookie.Values.Get(2), "#E9");
            Assert.AreEqual("second", cookie.Values.GetKey(3), "#E10");
            Assert.AreEqual("there", cookie.Values.Get(3), "#E11");
            Assert.AreEqual("this+is+&+the+x=y+third+%3d+cookie&first=hel%26l"
                            + "%3do+%3dy&second=there", cookie.Values.ToString(), "#E12");

            cookie = new HttpCookie("cookie31", cookie.Values.ToString());
            Assert.AreEqual("System.Web.HttpCookie", cookie.ToString(), "#F1");
            Assert.AreEqual("this+is+&+the+x=y+third+%3d+cookie&first=hel%26l"
                            + "%3do+%3dy&second=there", cookie.Value, "#F2");
            Assert.AreEqual(4, cookie.Values.Count, "#F3");
            Assert.IsNull(cookie.Values.GetKey(0), "#F4");
            Assert.AreEqual("this+is+", cookie.Values.Get(0), "#F5");
            Assert.AreEqual("+the+x", cookie.Values.GetKey(1), "#F6");
            Assert.AreEqual("y+third+%3d+cookie", cookie.Values.Get(1), "#F7");
            Assert.AreEqual("first", cookie.Values.GetKey(2), "#F8");
            Assert.AreEqual("hel%26l%3do+%3dy", cookie.Values.Get(2), "#F9");
            Assert.AreEqual("second", cookie.Values.GetKey(3), "#F10");
            Assert.AreEqual("there", cookie.Values.Get(3), "#F11");
            Assert.AreEqual("this%2bis%2b&%2bthe%2bx=y%2bthird%2b%253d%2bcookie"
                            + "&first=hel%2526l%253do%2b%253dy&second=there",
                            cookie.Values.ToString(), "#F12");

            cookie = new HttpCookie("funkycookie", "`~!@#$%^&*()_+-=\\][{}|'\";:,<.>/?");
            Assert.AreEqual("System.Web.HttpCookie", cookie.ToString(), "#G1");
            Assert.AreEqual("`~!@#$%^&*()_+-=\\][{}|'\";:,<.>/?", cookie.Value, "#G2");
            Assert.AreEqual(2, cookie.Values.Count, "#G3");
            Assert.IsNull(cookie.Values.GetKey(0), "#G4");
            Assert.AreEqual("`~!@#$%^", cookie.Values.Get(0), "#G5");
            Assert.AreEqual("*()_+-", cookie.Values.GetKey(1), "#G6");
            Assert.AreEqual("\\][{}|'\";:,<.>/?", cookie.Values.Get(1), "#G7");
#if NET_4_0
            Assert.AreEqual("%60%7e!%40%23%24%25%5e&*()_%2b-=%5c%5d%5b%7b%7d"
                            + "%7c%27%22%3b%3a%2c%3c.%3e%2f%3f", cookie.Values.ToString(), "#G8");
#else
            Assert.AreEqual("%60%7e!%40%23%24%25%5e&*()_%2b-=%5c%5d%5b%7b%7d"
                            + "%7c'%22%3b%3a%2c%3c.%3e%2f%3f", cookie.Values.ToString(), "#G8");
#endif

            cookie = new HttpCookie("funkycookie11", cookie.Values.ToString());
            Assert.AreEqual("System.Web.HttpCookie", cookie.ToString(), "#H1");
#if NET_4_0
            Assert.AreEqual("%60%7e!%40%23%24%25%5e&*()_%2b-=%5c%5d%5b%7b%7d"
                            + "%7c%27%22%3b%3a%2c%3c.%3e%2f%3f", cookie.Value, "#H2");
#else
            Assert.AreEqual("%60%7e!%40%23%24%25%5e&*()_%2b-=%5c%5d%5b%7b%7d"
                            + "%7c'%22%3b%3a%2c%3c.%3e%2f%3f", cookie.Value, "#H2");
#endif
            Assert.AreEqual(2, cookie.Values.Count, "#H3");
            Assert.IsNull(cookie.Values.GetKey(0), "#H4");
            Assert.AreEqual("%60%7e!%40%23%24%25%5e", cookie.Values.Get(0), "#H5");
            Assert.AreEqual("*()_%2b-", cookie.Values.GetKey(1), "#H6");
#if NET_4_0
            Assert.AreEqual("%5c%5d%5b%7b%7d%7c%27%22%3b%3a%2c%3c.%3e%2f%3f",
                            cookie.Values.Get(1), "#H7");
            Assert.AreEqual("%2560%257e!%2540%2523%2524%2525%255e&*()_%252b-="
                            + "%255c%255d%255b%257b%257d%257c%2527%2522%253b%253a%252c%253c.%2"
                            + "53e%252f%253f", cookie.Values.ToString(), "#H8");
#else
            Assert.AreEqual("%5c%5d%5b%7b%7d%7c'%22%3b%3a%2c%3c.%3e%2f%3f",
                            cookie.Values.Get(1), "#H7");
            Assert.AreEqual("%2560%257e!%2540%2523%2524%2525%255e&*()_%252b-="
                            + "%255c%255d%255b%257b%257d%257c'%2522%253b%253a%252c%253c.%2"
                            + "53e%252f%253f", cookie.Values.ToString(), "#H8");
#endif

            cookie = new HttpCookie("basic");
            cookie.Values ["one"]   = "hello world";
            cookie.Values ["two"]   = "a^2 + b^2 = c^2";
            cookie.Values ["three"] = "a & b";
            Assert.AreEqual("System.Web.HttpCookie", cookie.ToString(), "#I1");
            Assert.AreEqual("one=hello world&two=a^2 + b^2 = c^2&three=a & b",
                            cookie.Value, "#I2");
            Assert.AreEqual(3, cookie.Values.Count, "#I3");
            Assert.AreEqual("one", cookie.Values.GetKey(0), "#I4");
            Assert.AreEqual("hello world", cookie.Values.Get(0), "#I5");
            Assert.AreEqual("two", cookie.Values.GetKey(1), "#I6");
            Assert.AreEqual("a^2 + b^2 = c^2", cookie.Values.Get(1), "#I7");
            Assert.AreEqual("three", cookie.Values.GetKey(2), "#I8");
            Assert.AreEqual("a & b", cookie.Values.Get(2), "#I9");
            Assert.AreEqual("one=hello+world&two=a%5e2+%2b+b%5e2+%3d+c%5e2&"
                            + "three=a+%26+b", cookie.Values.ToString(), "#I10");

            HttpCookie cookie2 = new HttpCookie("basic2");
            cookie2.Value = cookie.Values.ToString();
            Assert.AreEqual("System.Web.HttpCookie", cookie2.ToString(), "#J1");
            Assert.AreEqual("one=hello+world&two=a%5e2+%2b+b%5e2+%3d+c%5e2&"
                            + "three=a+%26+b", cookie2.Value, "#J2");
            Assert.AreEqual(3, cookie2.Values.Count, "#J3");
            Assert.AreEqual("one", cookie.Values.GetKey(0), "#J4");
            Assert.AreEqual("hello world", cookie.Values.Get(0), "#J5");
            Assert.AreEqual("two", cookie.Values.GetKey(1), "#J6");
            Assert.AreEqual("a^2 + b^2 = c^2", cookie.Values.Get(1), "#J7");
            Assert.AreEqual("three", cookie.Values.GetKey(2), "#J8");
            Assert.AreEqual("a & b", cookie.Values.Get(2), "#J9");
            Assert.AreEqual("one=hello%2bworld&two=a%255e2%2b%252b%2bb%255e2"
                            + "%2b%253d%2bc%255e2&three=a%2b%2526%2bb",
                            cookie2.Values.ToString(), "#J10");
        }
        public void LoadActiveConversation()
        {
            //reset this.activeConversation
            this.activeConversation = null;

            if (LOG.IsDebugEnabled)
            {
                LOG.Debug("LoadActiveConversation");
            }

            HttpCookie activeConveCookie = HttpContext.Current.Request.Cookies[CONVERSATION_COOKIE_ID];

            if (activeConveCookie != null && !String.IsNullOrEmpty(activeConveCookie.Value))
            {
                if (LOG.IsDebugEnabled)
                {
                    LOG.Debug(String.Format("LoadActiveConversation: cooking found for current active conversation: [{0}]", activeConveCookie.ToString()));
                }
                if (this.conversations.ContainsKey(activeConveCookie.Value))
                {
                    if (LOG.IsDebugEnabled)
                    {
                        LOG.Debug(String.Format("LoadActiveConversation: active conversation found for id: '{0}'", activeConveCookie.Value));
                    }
                    IConversationState conversation = this.conversations[activeConveCookie.Value];
                    if (conversation != null)
                    {
                        if (LOG.IsDebugEnabled)
                        {
                            LOG.Debug(String.Format("LoadActiveConversation: conversation found: '{0}'", conversation.Id));
                        }
                        //find root conversation.
                        IConversationState rootConversation = conversation;
                        while (rootConversation.ParentConversation != null)
                        {
                            rootConversation = rootConversation.ParentConversation;
                        }
                        rootConversation.StartResumeConversation();
                        this.SetActiveConversation(rootConversation);
                    }
                }
                else
                {
                    if (LOG.IsDebugEnabled)
                    {
                        LOG.Debug(String.Format("LoadActiveConversation: conversation NOT found for id on the cookie: '{0}'", activeConveCookie.Value));
                    }
                    HttpContext.Current.Response.Cookies.Remove(CONVERSATION_COOKIE_ID);
                }
            }
        }
        /// <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);
        }
Beispiel #25
0
 public void Describe(Description description)
 {
     description.Title            = "Wrote cookie {0} to response".ToFormat(_cookie.Name);
     description.ShortDescription = _cookie.ToString();
 }