public void RequestAuthenticationRedirectsToProviderWithReturnUrl()
        {
            var cookies = new HttpCookieCollection();

            // Arrange
            var context = new Mock<HttpContextBase>();
            context.Setup(c => c.Request.ServerVariables).Returns(new NameValueCollection());
            context.Setup(c => c.Request.Url).Returns(new Uri("http://live.com/login.aspx"));
            context.Setup(c => c.Request.RawUrl).Returns("/login.aspx");
            context.Setup(c => c.Response.Cookies).Returns(cookies);
            context.Setup(c => c.User.Identity.IsAuthenticated).Returns(false);

            var client = new Mock<IAuthenticationClient>();
            client.Setup(c => c.ProviderName).Returns("yahoo");
            client.Setup(c => c.RequestAuthentication(
                                    context.Object,
                                    It.Is<Uri>(u => u.AbsoluteUri.StartsWith("http://yahoo.com/?__provider__=yahoo", StringComparison.OrdinalIgnoreCase))))
                  .Verifiable();

            OAuthWebSecurity.RegisterClient(client.Object);

            // Act
            OAuthWebSecurity.RequestAuthenticationCore(context.Object, "yahoo", "http://yahoo.com");

            // Assert
            client.Verify();
        }
Esempio n. 2
0
        public static string GetAuthorizationCookie(HttpCookieCollection cookies, string code, IBaseDb db)
        {
            //var code = request.QueryString["code"];

            var stream = HttpTools.PostStream("https://oauth.yandex.ru/token",
                string.Format("grant_type=authorization_code&code={0}&client_id={1}&client_secret={2}", code, ClientId, Password));

            var model = SerializeTools.Deserialize<TokenModel>(stream);

            var userCookie = new HttpCookie("yandex_token")
            {
                Value = model.access_token,
                Expires = DateTime.Now.AddDays(30)
            };

            stream = HttpTools.PostStream(InfoUrl, string.Format("oauth_token={0}", userCookie.Value));
            var email = SerializeTools.Deserialize<UserModel>(stream).default_email;

            var user = db.SingleOrDefault<User>(u => u.Email == email);

            cookies.Set(userCookie);

            var rolesCookie = new HttpCookie("roles") {Value = string.Join(",", user.UserRoles.Select(r => r.Code)), Expires = DateTime.Now.AddDays(30)};
            cookies.Set(rolesCookie);

            return model.access_token;
        }
        public void WhenRequestingMobileProfile_ThenJavascriptIsReturned()
        {
            _profileManifestRepository.Setup(p => p.GetProfile("generic"))
                .Returns(new ProfileManifest
                {
                    Id = "Generic-1.0",
                    Title = "Generic",
                    Features = new Feature[] {},
                    Version = "1.0"
                });

            _profileCookieEncoder.Setup(p => p.GetDeviceCapabilities(It.IsAny<HttpCookie>()))
                .Returns(new Dictionary<string, string>{ {"id", "generic-1.0"} });
            
            var controller = GetTestableMobileProfileController();

            var response = Mock.Get(controller.Response);
            
            var cookies = new HttpCookieCollection();
            cookies.Add(new System.Web.HttpCookie("profile"));
            controller.Request.SetHttpCookies(cookies);
            
            var result = controller.ProfileScript();

            Assert.IsType<PartialViewResult>(result);
            response.VerifySet((r) => { r.ContentType = "text/javascript"; });
        }
 public static void SetHttpCookies(this HttpRequestBase request,
    HttpCookieCollection cookies)
 {
     Mock.Get(request)
         .SetupGet(r => r.Cookies)
         .Returns(cookies);
 }
        internal string ProcessGet(SettingsClassHelper helper, HttpCookieCollection responseCookies)
        {
            var assembly = Assembly.GetExecutingAssembly();

            var fileName = "{0}.Page.html".FormatWith(GetType().Namespace);

            string fileContent;
            using (var stream = assembly.GetManifestResourceStream(fileName))
            {
                if (stream == null)
                    throw new Exception("The UI can't be found.");

                using (var reader = new StreamReader(stream))
                    fileContent = reader.ReadToEnd();
            }

            var model = new ViewModel
                {
                    Settings = InflateSettingsViewModel(helper),
                    Token = CreateCsrfToken(responseCookies)
                };

            foreach (var item in Configuration.SettingsProvider.GetAllValues())
            {
                model.Settings.First(x => x.Name == item.Key).Value = item.Value;
            }

            var outputJson = new JavaScriptSerializer().Serialize(model);

            fileContent = fileContent.Replace("{data}", outputJson);

            return fileContent;
        }
Esempio n. 6
0
        /// <summary>
        /// Used to clear cookie
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static void ClearCookie(HttpRequestBase request, HttpCookieCollection collection)
        {
            HttpCookie userInfoCookie = request.Cookies["USER_INFORMATION"];

            if (userInfoCookie != null)
                collection["USER_INFORMATION"].Expires = DateTime.Now.AddDays(-1);
        }
 public FakeHttpContext(string relativeUrl, 
     IPrincipal principal, NameValueCollection formParams,
     NameValueCollection queryStringParams, HttpCookieCollection cookies,
     SessionStateItemCollection sessionItems, NameValueCollection serverVariables)
     : this(relativeUrl, null, principal, formParams, queryStringParams, cookies, sessionItems, serverVariables)
 {
 }
Esempio n. 8
0
        public static HttpContextBase FakeHttpContext()
        {
            var context = new Mock<HttpContextBase>();

            var request = new Mock<HttpRequestBase>();
            {
                HttpCookieCollection cookie = new HttpCookieCollection();
                request.Setup(ctx => ctx.Cookies).Returns(cookie);
            }

            var response = new Mock<HttpResponseBase>();
            {
                HttpCookieCollection cookie = new HttpCookieCollection();
                response.Setup(ctx => ctx.Cookies).Returns(cookie);
            }

            var session = new Mock<HttpSessionStateBase>();
            var server = new Mock<HttpServerUtilityBase>();

            context.Setup(ctx => ctx.Request).Returns(request.Object);
            context.Setup(ctx => ctx.Response).Returns(response.Object);
            context.Setup(ctx => ctx.Session).Returns(session.Object);
            context.Setup(ctx => ctx.Server).Returns(server.Object);

            return context.Object;
        }
Esempio n. 9
0
        /// <summary>
        /// 通过CookieCollection集合生成nvp字符串
        /// </summary>
        /// <param name="escapeValue">是否转码值</param>
        public static string GetNvpString(this System.Web.HttpCookieCollection cookies, bool escapeValue)
        {
            if (cookies.Count == 0)
            {
                return(string.Empty);
            }
            StringBuilder buffer = new StringBuilder(32 + cookies.Count * 16);

            foreach (object item in cookies)
            {
                if (item.GetType() == typeof(string))
                {
                    buffer.Append(item);
                    buffer.Append('=');
                    buffer.Append(escapeValue ? HttpUtility.UrlEncode((string)item) : (string)item);
                    buffer.Append('&');
                }
                else if (item.GetType() == typeof(System.Web.HttpCookie))
                {
                    buffer.Append(((System.Web.HttpCookie)item).Name);
                    buffer.Append('=');
                    buffer.Append(escapeValue ? HttpUtility.UrlEncode(((System.Web.HttpCookie)item).Value) : ((System.Web.HttpCookie)item).Value);
                    buffer.Append('&');
                }
            }
            return(buffer.ToString(0, buffer.Length - 1));
        }
        public void DoesNothing()
        {
            var responseCookies = new HttpCookieCollection();
            var responseHeaders = new NameValueCollection();

            var httpContext = Substitute.For<HttpContextBase>();

            httpContext.Request.Headers.Returns(new NameValueCollection());

            httpContext.Response.Cookies.Returns(responseCookies);
            httpContext.Response.Headers.Returns(responseHeaders);

            var controllerContext = new ControllerContext(
                httpContext,
                new RouteData(),
                Substitute.For<ControllerBase>());

            var filterContext = new ActionExecutedContext(
                controllerContext,
                Substitute.For<ActionDescriptor>(),
                false,
                null);

            var attribute = new TurbolinksAttribute();

            attribute.OnActionExecuted(filterContext);

            Assert.Empty(responseCookies);
            Assert.Empty(responseHeaders);
        }
Esempio n. 11
0
        public FakeHttpRequest(string url, bool isAuthenticated)
        {
            _url = new Uri(url);
            _isAuthenticated = isAuthenticated;

            _cookies = new HttpCookieCollection();
        }
        public void AuthenticateRequest_WithRequestHavingValidAuthCookies_SetsUserToGenericPrincipalWithRoles()
        {
            // arrange
            var module = new AuthenticationModule();
            const string roles = "Admins|HostAdmins|Users";
            var ticket = new FormsAuthenticationTicket(1, ".ASPXAUTH.42", DateTime.Now, DateTime.Now.AddDays(60), true,
                                                       roles);
            string cookieValue = FormsAuthentication.Encrypt(ticket);
            var authCookie = new HttpCookie(".ASPXAUTH.42") { Value = cookieValue };
            var cookies = new HttpCookieCollection { authCookie };
            var httpContext = new Mock<HttpContextBase>();
            httpContext.Stub(c => c.User);
            httpContext.Setup(c => c.Request.Path).Returns("/");
            httpContext.Setup(c => c.Request.QueryString).Returns(new NameValueCollection());
            httpContext.Setup(c => c.Request.Cookies).Returns(cookies);
            httpContext.Setup(c => c.Response.Cookies).Returns(cookies);
            var blogRequest = new BlogRequest("localhost", string.Empty, new Uri("http://localhost"), false,
                                              RequestLocation.Blog, "/") { Blog = new Blog { Id = 42 } };

            // act
            module.AuthenticateRequest(httpContext.Object, blogRequest);

            // assert
            var principal = httpContext.Object.User as GenericPrincipal;
            Assert.IsNotNull(principal);
            Assert.IsTrue(principal.IsInRole("Admins"));
            Assert.IsTrue(principal.IsInRole("HostAdmins"));
            Assert.IsTrue(principal.IsInRole("Users"));
        }
Esempio n. 13
0
        public static HttpContextBase FakeHttpContext() {

            var context = new Mock<HttpContextBase>();
            var request = new Mock<HttpRequestBase>();
            var response = new Mock<HttpResponseBase>();
            var session = new Mock<HttpSessionStateBase>();
            var server = new Mock<HttpServerUtilityBase>();

            context.Expect(ctx => ctx.Request).Returns(request.Object);
            context.Expect(ctx => ctx.Response).Returns(response.Object);
            context.Expect(ctx => ctx.Session).Returns(session.Object);
            context.Expect(ctx => ctx.Server).Returns(server.Object);


            var form = new NameValueCollection();
            var querystring = new NameValueCollection();
            var cookies = new HttpCookieCollection();
            var user = new GenericPrincipal(new GenericIdentity("testuser"),new string[]{"Administrator"});
            
            request.Expect(r => r.Cookies).Returns(cookies);
            request.Expect(r => r.Form).Returns(form);
            request.Expect(q => q.QueryString).Returns(querystring);
            context.Expect(u => u.User).Returns(user);
            return context.Object;
        }
Esempio n. 14
0
        public bool CheckCookies(HttpCookieCollection cookies)
        {
            if (cookies == null || cookies.Count == 0 || cookies.Count <4)return false;

            if (string.IsNullOrEmpty(cookies[GLB.id].Value) ||
                string.IsNullOrEmpty(cookies[GLB.userId].Value) ||
                string.IsNullOrEmpty(cookies[GLB.userName].Value) ||
                string.IsNullOrEmpty(cookies[GLB.depId].Value))
            {
                return false;
            }

            userDal = new UserDAL();
            bool flag = userDal.CheckValid(new UserStatus()
            {
                //记得加上异常处理
                ID = Convert.ToInt32(cookies[GLB.id].Value),
                UserID = cookies[GLB.userId].Value,
                Dep = new Department()
                {
                    ID = Convert.ToInt32(cookies[GLB.depId].Value)
                }
            });
            userDal.ReturnUnitToPool();
            return flag;
        }
Esempio n. 15
0
		public FakeHttpRequest(string relativeUrl, NameValueCollection formParams, NameValueCollection queryStringParams, HttpCookieCollection cookies)
		{
			_relativeUrl = relativeUrl;
			_formParams = formParams;
			_queryStringParams = queryStringParams;
			_cookies = cookies;
		}
Esempio n. 16
0
        public static UmbracoContext GetMockUmbracoContext(Uri requestUri, HttpCookie mockCookie = null)
        {
            //var mockHttpContext = MockRepository.GenerateStub<HttpContextBase>();
            //var mockHttpRequest = MockRepository.GenerateStub<HttpRequestBase>();
            //var mockHttpResponse = MockRepository.GenerateStub<HttpResponseBase>();
            //SetupResult.For(mockHttpContext.Request).Return(mockHttpRequest);
            //SetupResult.For(mockHttpRequest.Url).Return(requestUri);
            //SetupResult.For(mockHttpRequest.Cookies).Return(cookieCollection);

            //SetupResult.For(mockHttpContext.Response).Return(mockHttpResponse);
            //SetupResult.For(mockHttpResponse.Cookies).ReturncookieCollection);

            var umbracoContext = MockRepository.GenerateStrictMock<UmbracoContext>();

            var cookieCollection = new HttpCookieCollection();
            SetupResult.For(umbracoContext.HttpContext.Request.Cookies).Return(cookieCollection);

            if (mockCookie != null)
            {
                cookieCollection.Add(mockCookie);
                umbracoContext.Expect(c => c.HttpContext.Response.Cookies.Add(mockCookie));
            }
            SetupResult.For(umbracoContext.HttpContext.Request.Url).Return(requestUri);

            return umbracoContext;
        }
Esempio n. 17
0
 public FakeHttpRequest(string relativeUrl, string method, Uri url, Uri urlReferrer, NameValueCollection formParams, NameValueCollection queryStringParams,
                        HttpCookieCollection cookies)
     : this(relativeUrl, method, formParams, queryStringParams, cookies)
 {
     _url = url;
     _urlReferrer = urlReferrer;
 }
Esempio n. 18
0
        public static HttpContextBase GetFakeHttpContext()
        {
            var context = new Mock<HttpContextBase>();
            var request = new Mock<HttpRequestBase>();
            var response = new Mock<HttpResponseBase>();
            var responseCache = new Mock<HttpCachePolicyBase>();
            var session = new Mock<HttpSessionStateBase>();
            var server = new Mock<HttpServerUtilityBase>();
            var cookie = new HttpCookieCollection();
            var user = new Mock<IPrincipal>();
            var identity = new Mock<IIdentity>();

            request.Setup(req => req.Cookies).Returns(cookie);
            response.Setup(resp => resp.Cookies).Returns(cookie);
            identity.Setup(ident => ident.Name).Returns("kpratt");
            user.Setup(usr => usr.Identity).Returns(identity.Object);

            context.Setup(ctx => ctx.User).Returns(user.Object);
            context.Setup(ctx => ctx.Request).Returns(request.Object);
            context.Setup(ctx => ctx.Response).Returns(response.Object);
            context.Setup(ctx => ctx.Response.Cache).Returns(responseCache.Object);
            context.Setup(ctx => ctx.Session).Returns(session.Object);
            context.Setup(ctx => ctx.Server).Returns(server.Object);

            return context.Object;
        }
		/// <summary>
		/// Mocks the http context to test against
		/// </summary>
		/// <param name="fullUrl"></param>
		/// <param name="routeData"></param>
		/// <returns></returns>
		private void CreateContext(Uri fullUrl, RouteData routeData = null)
		{
			//Request context

            var requestContextMock = new Mock<RequestContext>();

            RequestContext = requestContextMock.Object;

            //Cookie collection
		    var cookieCollection = new HttpCookieCollection();
            cookieCollection.Add(new HttpCookie("UMB_UCONTEXT", "FBA996E7-D6BE-489B-B199-2B0F3D2DD826"));

		    //Request
            var requestMock = new Mock<HttpRequestBase>();
            requestMock.Setup(x => x.AppRelativeCurrentExecutionFilePath).Returns("~" + fullUrl.AbsolutePath);
			requestMock.Setup(x => x.PathInfo).Returns(string.Empty);
            requestMock.Setup(x => x.RawUrl).Returns(VirtualPathUtility.ToAbsolute("~" + fullUrl.AbsolutePath, "/"));
            requestMock.Setup(x => x.RequestContext).Returns(RequestContext);
            requestMock.Setup(x => x.Url).Returns(fullUrl);
            requestMock.Setup(x => x.ApplicationPath).Returns("/");
            requestMock.Setup(x => x.Cookies).Returns(cookieCollection);
            requestMock.Setup(x => x.ServerVariables).Returns(new NameValueCollection());
			var queryStrings = HttpUtility.ParseQueryString(fullUrl.Query);
            requestMock.Setup(x => x.QueryString).Returns(queryStrings);
            requestMock.Setup(x => x.Form).Returns(new NameValueCollection());

			//Cache
            var cacheMock = new Mock<HttpCachePolicyBase>();

			//Response 
			//var response = new FakeHttpResponse();
            var responseMock = new Mock<HttpResponseBase>();
            responseMock.Setup(x => x.ApplyAppPathModifier(It.IsAny<string>())).Returns((string s) => s);
            responseMock.Setup(x => x.Cache).Returns(cacheMock.Object);

			//Server

			var serverMock = new Mock<HttpServerUtilityBase>();
			serverMock.Setup(x => x.MapPath(It.IsAny<string>())).Returns(Environment.CurrentDirectory);

			//HTTP Context

            var httpContextMock = new Mock<HttpContextBase>();
            httpContextMock.Setup(x => x.Cache).Returns(HttpRuntime.Cache);
            httpContextMock.Setup(x => x.Items).Returns(new Dictionary<object, object>());
            httpContextMock.Setup(x => x.Request).Returns(requestMock.Object);
            httpContextMock.Setup(x => x.Server).Returns(serverMock.Object);
            httpContextMock.Setup(x => x.Response).Returns(responseMock.Object);

            HttpContext = httpContextMock.Object;

            requestContextMock.Setup(x => x.HttpContext).Returns(httpContextMock.Object);

			if (routeData != null)
			{
                requestContextMock.Setup(x => x.RouteData).Returns(routeData);
			}
		    
            
		}
Esempio n. 20
0
		/// <summary>
		/// Default constructor.
		/// </summary>
		/// <param name="engine">The rewriting engine.</param>
		/// <param name="rawUrl">The initial, raw URL.</param>
		/// <param name="httpMethod">The HTTP method used (GET, POST, ...)</param>
		/// <param name="mapPath">The method to use for mapping paths.</param>
		/// <param name="serverVariables">Collection of server variables.</param>
		/// <param name="headers">Collection of headers.</param>
		/// <param name="cookies">Collection of cookies.</param>
		internal RewriteContext(RewriterEngine engine,
			string rawUrl, string httpMethod,
			MapPath mapPath,
			NameValueCollection serverVariables,
			NameValueCollection headers,
			HttpCookieCollection cookies)
		{
			_engine = engine;
			_location = rawUrl;
			_method = httpMethod;
			_mapPath = mapPath;

			foreach (string key in serverVariables)
			{
				_properties.Add(key, serverVariables[key]);
			}

			foreach (string key in headers)
			{
				_properties.Add(key, headers[key]);
			}

			foreach (string key in cookies)
			{
				_properties.Add(key, cookies[key].Value);
			}
		}
        public void Evaluate_Test()
        {
            var triggerPart = new TriggerPart()
            {
                CookieName     = "c1",
                Operator       = ComparisonOperatorType.Contains,
                ValueToCompare = "1"
            };
            var cookieCollection = new System.Web.HttpCookieCollection()
            {
            };

            Assert.False(CookieValidatorHelper.Evaluate(triggerPart, cookieCollection));

            cookieCollection.Add(new System.Web.HttpCookie("c5", "5"));
            cookieCollection.Add(new System.Web.HttpCookie("c1", "1"));
            cookieCollection.Add(new System.Web.HttpCookie("c2", "test"));
            Assert.True(CookieValidatorHelper.Evaluate(triggerPart, cookieCollection));

            triggerPart.ValueToCompare = "5";
            Assert.False(CookieValidatorHelper.Evaluate(triggerPart, cookieCollection));


            triggerPart.ValueToCompare = "Test";
            triggerPart.IsIgnoreCase   = true;
            triggerPart.CookieName     = "c2";
            Assert.True(CookieValidatorHelper.Evaluate(triggerPart, cookieCollection));

            triggerPart.ValueToCompare = "Test";
            triggerPart.IsIgnoreCase   = true;
            triggerPart.IsNegative     = true;
            triggerPart.CookieName     = "c2";
            Assert.False(CookieValidatorHelper.Evaluate(triggerPart, cookieCollection));
        }
        public void GetValueProvider()
        {
            // Arrange
            HttpCookieCollection cookies = new HttpCookieCollection
            {
                new HttpCookie("foo", "fooValue"),
                new HttpCookie("bar.baz", "barBazValue"),
                new HttpCookie("", "emptyValue"),
                new HttpCookie(null, "nullValue")
            };

            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();
            mockControllerContext.Setup(o => o.HttpContext.Request.Cookies).Returns(cookies);

            CookieValueProviderFactory factory = new CookieValueProviderFactory();

            // Act
            IValueProvider provider = factory.GetValueProvider(mockControllerContext.Object);

            // Assert
            Assert.Null(provider.GetValue(""));
            Assert.True(provider.ContainsPrefix("bar"));
            Assert.Equal("fooValue", provider.GetValue("foo").AttemptedValue);
            Assert.Equal(CultureInfo.InvariantCulture, provider.GetValue("foo").Culture);
        }
		/// <summary>
		/// allows access to things such as the controller's HttpContext, HttpContext.Request, HttpContext.Request.QueryString, HttpContext.Request.Cookies
		/// </summary>
		public static void SetMockControllerContext(this Controller yourController, HttpContextTestData httpContextTestData = null)
		{
			var request = new Mock<HttpRequestBase>();
			var response = new Mock<HttpResponseBase>();
            var requestQuery = httpContextTestData == null ? new NameValueCollection() : httpContextTestData.RequestQueryParams;
		    var reqCookies = new HttpCookieCollection();
		    var respCookies = new HttpCookieCollection();
            // controller methods might access query params either as Request.QueryString or as Request["xxx"]
            //   make Request.QueryString work:
			request.SetupGet(x => x.QueryString).Returns(requestQuery);
            //   make Request["xxx"] work:
            if (requestQuery.Count > 0)
                request.SetupGet(r => r[requestQuery.AllKeys[0]]).Returns(requestQuery.Get(0));
            if (requestQuery.Count > 1)
                request.SetupGet(r => r[requestQuery.AllKeys[1]]).Returns(requestQuery.Get(1));
            if (requestQuery.Count > 2)
                request.SetupGet(r => r[requestQuery.AllKeys[2]]).Returns(requestQuery.Get(2));
            if (requestQuery.Count > 3)
                request.SetupGet(r => r[requestQuery.AllKeys[3]]).Returns(requestQuery.Get(3));
            if (requestQuery.Count > 4)
                request.SetupGet(r => r[requestQuery.AllKeys[4]]).Returns(requestQuery.Get(4));
            request.SetupGet(x => x.Cookies).Returns(reqCookies);
		    if (httpContextTestData != null && !string.IsNullOrEmpty(httpContextTestData.Url))
		        request.SetupGet(x => x.Url).Returns(new Uri(httpContextTestData.Url));
            response.SetupGet(x => x.Cookies).Returns(respCookies);
            var context = new Mock<HttpContextBase>();
			context.SetupGet(x => x.Request).Returns(request.Object);
		    context.SetupGet(x => x.Response).Returns(response.Object);
            if (httpContextTestData != null)
                response.Setup(x => x.Redirect(It.IsAny<string>())).Callback<string>(url => httpContextTestData.RedirectUrl = url);
            yourController.ControllerContext = new ControllerContext(context.Object, new RouteData(), yourController);
		}
        public void IsInDebugMode_ShouldBeCorrect(NameValueCollection queryString, HttpCookieCollection cookies, bool expected)
        {
            _mockRequest.Expect(r => r.QueryString).Return(queryString);
            _mockRequest.Expect(r => r.Cookies).Return(cookies);

            Assert.Equal(expected, _html.IsInDebugMode());
        }
        /// <summary>
        /// Adds cookie data to the request
        /// </summary>
        /// <param name="request">request to add cookiedata too</param>
        /// <param name="cookieName">name of cookie to add data to</param>
        /// <param name="key">key for data value</param>
        /// <param name="value">value for data</param>
        /// <returns>HttpRequestBase</returns>
        /// <exception cref="ArgumentNullExeption">request is null</exception>
        /// <exception cref="ArgumentNullExeption">cookieName is null or empty</exception>
        /// <exception cref="ArgumentNullExeption">key is null or empty</exception>
        /// <exception cref="ArgumentNullExeption">value is null</exception>
        public static HttpRequestBase AddCookieData(this HttpRequestBase request, string cookieName, string key, string value)
        {
            if (request == null)
                throw new ArgumentNullException("request");

            if (String.IsNullOrWhiteSpace(cookieName))
                throw new ArgumentNullException("cookieName");

            if(String.IsNullOrWhiteSpace(key))
                throw new ArgumentNullException("key");

            if(value == null)
                throw new ArgumentNullException("value");

            if(request.Cookies == null)
            {
                var cookieCollection = new HttpCookieCollection();
                Mock.Get(request).Setup(r => r.Cookies).Returns(cookieCollection);
            }

            if (!request.Cookies.AllKeys.Contains(cookieName))
                request.Cookies.Add(new HttpCookie(cookieName));

            request.Cookies[cookieName][key] = value;

            return request;
        }
        public void OnlySetsRequestMethodCookie()
        {
            var responseCookies = new HttpCookieCollection();

            var httpContext = Substitute.For<HttpContextBase>();

            httpContext.Request.HttpMethod.Returns("GET");
            httpContext.Request.Headers.Returns(
                new NameValueCollection
                    {
                        {
                            "X-XHR-Referer",
                            "http://localhost:61049/Projects/Create"
                        }
                    });

            httpContext.Response.Cookies.Returns(responseCookies);

            var controllerContext = new ControllerContext(
                httpContext,
                new RouteData(),
                Substitute.For<ControllerBase>());

            var filterContext = new ActionExecutedContext(
                controllerContext,
                Substitute.For<ActionDescriptor>(),
                false,
                null);

            var attribute = new TurbolinksAttribute();

            attribute.OnActionExecuted(filterContext);

            Assert.Equal("GET", responseCookies["request_method"].Value);
        }
Esempio n. 27
0
        public static HttpContextBase FakeHttpContext()
        {
            var context = new Mock<HttpContextBase>();
            var request = new Mock<HttpRequestBase>();
            var response = new Mock<HttpResponseBase>();
            var session = new Mock<HttpSessionStateBase>();
            var server = new Mock<HttpServerUtilityBase>();

            context.Setup(ctx => ctx.Request).Returns(request.Object);
            context.Setup(ctx => ctx.Response).Returns(response.Object);
            context.Setup(ctx => ctx.Session).Returns(session.Object);
            context.Setup(ctx => ctx.Server).Returns(server.Object);

            var form = new NameValueCollection();
            var querystring = new NameValueCollection();
            var cookies = new HttpCookieCollection();

            request.Setup(r => r.Cookies).Returns(cookies);
            request.Setup(r => r.Form).Returns(form);
            request.Setup(q => q.QueryString).Returns(querystring);

            response.Setup(r => r.Cookies).Returns(cookies);

            return context.Object;
        }
Esempio n. 28
0
        public static HttpContextBase GetFakeContext()
        {
            var httpContext = MockRepository.GenerateStub<HttpContextBase>();
            var request = MockRepository.GenerateStub<HttpRequestBase>();
            var response = MockRepository.GenerateStub<HttpResponseBase>();
            var session = MockRepository.GenerateStub<HttpSessionStateBase>();
            var server = MockRepository.GenerateStub<HttpServerUtilityBase>();
            var cookies = new HttpCookieCollection();

            httpContext.Stub(x => x.Request)
                .Return(request);
            httpContext.Stub(x => x.Response)
                .Return(response);
            httpContext.Stub(x => x.Session)
                .Return(session);
            httpContext.Stub(x => x.Server)
                .Return(server);
            response.Stub(x => x.Cookies)
                .Return(cookies);

            var writer = new StringWriter();
            var wr = new SimpleWorkerRequest("", "", "", "", writer);
            HttpContext.Current = new HttpContext(wr);

            return httpContext;
        }
Esempio n. 29
0
        public XrcResponse(Stream stream, HttpResponseBase parentResponse = null)
        {
            if (stream == null)
                throw new ArgumentNullException("stream");

            _innerResponse = parentResponse;

            _isStreamOwner = true;
            if (_innerResponse == null)
            {
                _cookies = new HttpCookieCollection();
                _statusCode = (int)HttpStatusCode.OK;
                _contentEncoding = Encoding.UTF8;
                _contentType = "text/html; charset=UTF-8";
                _redirectLocation = null;
                _statusDescription = null;
                _outputStream = stream;
                _output = new StreamWriter(stream, _contentEncoding);
            }
            else
            {
                _cookies = _innerResponse.Cookies;
                _statusCode = (int)HttpStatusCode.OK;
                _contentEncoding = _innerResponse.ContentEncoding;
                _contentType = _innerResponse.ContentType;
                _redirectLocation = null;
                _statusDescription = null;
                _outputStream = stream;
                _output = new StreamWriter(stream, _contentEncoding);
            }
        }
Esempio n. 30
0
 public static void Logout(HttpCookieCollection requestCookies, HttpCookieCollection responseCookies)
 {
     FormsAuthentication.SignOut();
     Thread.CurrentPrincipal = null;
     HttpContext.Current.Session.Remove("EpiPrincipal");
     ForgetLoggedInUser(requestCookies, responseCookies);
 }
 public FakeHttpRequest(string url, NameValueCollection formParams, NameValueCollection queryStringParams, HttpCookieCollection cookies)
 {
     _uri = new Uri(url);
     _formParams = formParams;
     _queryStringParams = queryStringParams;
     _cookies = cookies;
 }
        public RedirectToDifferentOrigin()
        {
            var httpContext = Substitute.For<HttpContextBase>();

            httpContext.Request.HttpMethod.Returns("GET");
            httpContext.Request.Headers.Returns(
                new NameValueCollection
                    {
                        {
                            "X-XHR-Referer",
                            "http://localhost:61049/Projects/Create"
                        }
                    });

            responseCookies = new HttpCookieCollection();
            httpContext.Response.Cookies.Returns(responseCookies);

            var controllerContext = new ControllerContext(
                httpContext,
                new RouteData(),
                Substitute.For<ControllerBase>());

            filterContext = new ActionExecutedContext(
                controllerContext,
                Substitute.For<ActionDescriptor>(),
                false,
                null) { Result = new RedirectResult("http://google.com") };

            var attribute = new TurbolinksAttribute();

            attribute.OnActionExecuted(filterContext);
        }
 public static bool Evaluate(TriggerPart triggerPart, System.Web.HttpCookieCollection cookieCollection)
 {
     return(ComparisonOperatorHelper.Evaluate(triggerPart.Operator,
                                              triggerPart.IsNegative,
                                              triggerPart.IsIgnoreCase,
                                              GetCookie(triggerPart.CookieName, cookieCollection),
                                              triggerPart.ValueToCompare));
 }
        private static string GetCookie(string cookieName, System.Web.HttpCookieCollection cookieCollection)
        {
            var cookie = cookieCollection?.Get(cookieName);

            if (cookie == null)
            {
                return(string.Empty);
            }
            return(cookieCollection[cookieName].Value);
        }
Esempio n. 35
0
        private void Page_Load(object sender, System.EventArgs e)
        {
            System.Web.UI.HtmlControls.HtmlForm frm = (HtmlForm)FindControl("Form1");
            GHTTestBegin(frm);
            // ===================================
            // testing if the Context object is set
            // ===================================
            GHTSubTestBegin("Request.Cookies1");
            try
            {
                if (Request.Cookies == null)
                {
                    GHTSubTestAddResult("Failed");
                }
                else
                {
                    GHTSubTestAddResult("Success");
                }
            }
            catch (Exception ex)
            {
                GHTSubTestAddResult("unxpected " + ex.GetType().Name + " exception was caught-" + ex.Message);
            }

            GHTSubTestEnd();

            // ===================================
            // testing if the objects return is from the
            // correct type
            // ===================================
            GHTSubTestBegin("Request.Cookies2");
            try
            {
                HttpCookieCollection cookie = Request.Cookies;
                GHTSubTestAddResult("success");
            }
            catch (Exception ex)
            {
                GHTSubTestAddResult("Unxpected " + ex.GetType().Name + " exception was caught-" + ex.Message);
            }

            GHTSubTestEnd();

            // ===================================
            // testing if the Cookies collection contains the
            // right context. This is basic testing
            // a more rigorous testing needs to be included
            // in the HTTPColkiesCollction object
            // ===================================
            GHTSubTestBegin("Request.Cookies3");
            HttpCookie MyCookie;

            MyCookie = new HttpCookie("MyCookie", "MyCookieValue");
            Response.Cookies.Add(MyCookie);
            try
            {
                HttpCookieCollection Cookies = Request.Cookies;
                foreach (System.Web.HttpCookie cookie in Cookies)
                {
                    if (cookie.Name == "MyCookie")
                    {
                        GHTSubTestAddResult(cookie.Name + " - " + cookie.Value);
                    }
                }
            }

            catch (Exception ex)
            {
                GHTSubTestAddResult("Unxpected " + ex.GetType().Name + " exception was caught-" + ex.Message);
            }

            GHTSubTestEnd();

            // ===================================
            // testing if the Cookies collection contains the
            // right context. This is basic testing
            // a more rigorous testing needs to be included
            // in the HTTPColkiesCollction object
            // ===================================
            GHTSubTestBegin("Request.Cookies4");
            try
            {
                System.Web.HttpCookieCollection Cookies = Request.Cookies;
                string currentKey = "MyCookie";
                GHTSubTestAddResult(Cookies[currentKey].Name + " - " + Cookies[currentKey].Value);
            }
            catch (Exception ex)
            {
                GHTSubTestAddResult("Unxpected " + ex.GetType().Name + " exception was caught-" + ex.Message);
            }

            GHTSubTestEnd();
            GHTTestEnd();
        }
Esempio n. 36
0
 public HttpResponse(Microsoft.AspNetCore.Http.HttpContext context)
 {
     this.context     = context;
     cookieCollection = new HttpCookieCollection(context);
 }