public void CanLoadTempDataFromCookie() { var tempData = new TempDataDictionary(); tempData.Add("abc", "easy as 123"); tempData.Add("price", 1.234); string serializedTempData = CookieTempDataProvider.SerializeToBase64EncodedString(tempData); var cookies = new HttpCookieCollection(); var httpCookie = new HttpCookie("__ControllerTempData"); httpCookie.Value = serializedTempData; cookies.Add(httpCookie); var requestMock = new Mock <HttpRequestBase>(); requestMock.Expect(r => r.Cookies).Returns(cookies); var responseMock = new Mock <HttpResponseBase>(); responseMock.Expect(r => r.Cookies).Returns(cookies); var httpContextMock = new Mock <HttpContextBase>(); httpContextMock.Expect(c => c.Request).Returns(requestMock.Object); httpContextMock.Expect(c => c.Response).Returns(responseMock.Object); ITempDataProvider provider = new CookieTempDataProvider(httpContextMock.Object); IDictionary <string, object> loadedTempData = provider.LoadTempData(null /* controllerContext */); Assert.AreEqual(2, loadedTempData.Count); Assert.AreEqual("easy as 123", loadedTempData["abc"]); Assert.AreEqual(1.234, loadedTempData["price"]); }
public void SaveTempDataStoresSerializedFormInCookie() { var cookies = new HttpCookieCollection(); var responseMock = new Mock <HttpResponseBase>(); responseMock.Expect(r => r.Cookies).Returns(cookies); var httpContextMock = new Mock <HttpContextBase>(); httpContextMock.Expect(c => c.Response).Returns(responseMock.Object); ITempDataProvider provider = new CookieTempDataProvider(httpContextMock.Object); var tempData = new TempDataDictionary(); tempData.Add("Testing", "Turn it up to 11"); tempData.Add("Testing2", 1.23); provider.SaveTempData(null, tempData); HttpCookie cookie = cookies["__ControllerTempData"]; string serialized = cookie.Value; IDictionary <string, object> deserializedTempData = CookieTempDataProvider.DeserializeTempData(serialized); Assert.AreEqual("Turn it up to 11", deserializedTempData["Testing"]); Assert.AreEqual(1.23, deserializedTempData["Testing2"]); }
public static bool BankAccntOrCategoriesIsNull(CreateTransactionViewModel viewModel, TempDataDictionary tempData) { if ((viewModel.BankAccounts is null || viewModel.Categories is null) || (viewModel.BankAccounts.Count <= 0 || viewModel.Categories.Count <= 0) && !tempData.Keys.Contains("Message")) { tempData.Add("Message", ""); tempData.Add("MessageColour", "danger"); } if (viewModel.BankAccounts is null && viewModel.Categories is null || (viewModel.BankAccounts.Count <= 0 && viewModel.Categories.Count <= 0)) { tempData["Message"] = "There's no bank accounts or categories on this household yet. Create them before making a transaction!"; return(true); }
public void Danger(string message) { if (tempData.ContainsKey(AlertType.DANGER)) { ((List <string>)tempData[AlertType.DANGER]).Add(message); } else { tempData.Add(AlertType.DANGER, new List <string> { message }); } }
public async Task PostShouldAddNews() { var mockRepo = new Mock <INewsRepository>(); var news = new News { Title = "2020 FIFA U-17 Women World Cup", Content = "The tournament will be held in India between 2 and 21 November 2020.", PublishedAt = DateTime.Now, UrlToImage = null, UserId = "Jack" }; mockRepo.Setup(repo => repo.AddNews(news)).Returns(Task.FromResult(new News { NewsId = 102, Title = "2020 FIFA U-17 Women World Cup", Content = "The tournament will be held in India between 2 and 21 November 2020.", PublishedAt = DateTime.Now, UrlToImage = null, UserId = "Jack" })); var httpContext = new DefaultHttpContext(); var tempData = new TempDataDictionary(httpContext, Mock.Of <ITempDataProvider>()); tempData.Add("uId", "Jack"); var newsController = new NewsController(mockRepo.Object); newsController.TempData = tempData; var actual = await newsController.Index(news); var actionResult = Assert.IsType <RedirectToActionResult>(actual); Assert.Equal("Index", actionResult.ActionName); }
public void SheetSelector_ReturnsAnActionResult() { //Arrange System.Threading.Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; Mock <ISilveRRepository> mock = new Mock <ISilveRRepository>(); var tempDataMock = new TempDataDictionary(new DefaultHttpContext(), Mock.Of <ITempDataProvider>()); tempDataMock.Add("TableNames", new List <string> { "SheetName1", "SheetName 2", "SheetName 3" }); DataController sut = new DataController(mock.Object); sut.TempData = tempDataMock; //Act IActionResult result = sut.SheetSelector("TheFile.csv"); //Assert ViewResult viewResult = Assert.IsType <ViewResult>(result); Assert.Equal("TheFile.csv", viewResult.ViewData["FileName"]); Assert.Equal(new List <string> { "SheetName1", "SheetName 2", "SheetName 3" }, viewResult.ViewData["SheetList"]); }
public void Add(string type, string message) { if (String.IsNullOrEmpty(message)) { return; } //as the type would come from a anonymous object property name, //we assume the underscore means the hyphen as that is the usual convention for css class name type = type.Replace("_", "-"); IList <KeyValuePair <string, string> > messages; object tmp; if (!_backingStore.TryGetValue(Key, out tmp)) { messages = new List <KeyValuePair <string, string> >(); _backingStore.Add(Key, messages); } else { messages = (IList <KeyValuePair <string, string> >)tmp; } var item = messages.SingleOrDefault(e => e.Key.Equals(type, StringComparison.OrdinalIgnoreCase)); if (!String.IsNullOrWhiteSpace(item.Value)) { messages.Remove(item); } messages.Add(new KeyValuePair <string, string>(type, message)); //_backingStore.Keep(Key); }
public void LoadTempDataIgnoresNullResponseCookieDoesNotThrowException() { HttpCookie cookie = new HttpCookie("__ControllerTempData"); TempDataDictionary initialTempData = new TempDataDictionary(); initialTempData.Add("WhatIsInHere?", "Stuff"); cookie.Value = CookieTempDataProvider.SerializeToBase64EncodedString(initialTempData); var cookies = new HttpCookieCollection(); cookies.Add(cookie); var requestMock = new Mock <HttpRequestBase>(); requestMock.Expect(r => r.Cookies).Returns(cookies); var responseMock = new Mock <HttpResponseBase>(); responseMock.Expect(r => r.Cookies).Returns((HttpCookieCollection)null); var httpContextMock = new Mock <HttpContextBase>(); httpContextMock.Expect(c => c.Request).Returns(requestMock.Object); httpContextMock.Expect(c => c.Response).Returns(responseMock.Object); ITempDataProvider provider = new CookieTempDataProvider(httpContextMock.Object); IDictionary <string, object> tempData = provider.LoadTempData(null /* controllerContext */); Assert.AreEqual("Stuff", tempData["WhatIsInHere?"]); }
public void RedirectsToHomepageOnlyWith2FAMarker(bool shouldEnable2FA) { var tempData = new TempDataDictionary(); if (shouldEnable2FA) { tempData.Add(GalleryConstants.AskUserToEnable2FA, true); } var context = BuildAuthorizationContext( BuildClaimsIdentity( AuthenticationTypes.External, authenticated: true, hasDiscontinuedLoginClaim: false).Object).Object; context.Controller.TempData = tempData; var attribute = new UIAuthorizeAttribute(); // Act attribute.OnAuthorization(context); // Assert var redirectResult = context.Result as RedirectToRouteResult; if (shouldEnable2FA) { Assert.NotNull(redirectResult); Assert.Contains(new KeyValuePair <string, object>("controller", "Pages"), redirectResult.RouteValues); Assert.Contains(new KeyValuePair <string, object>("action", "Home"), redirectResult.RouteValues); } else { Assert.Null(redirectResult); } }
private void TryLoadTempData(Controller controller) { try { if (controller != null && controller.ControllerContext != null && controller.Session != null && !controller.ControllerContext.IsChildAction) { // Saving the current temp data. var oldTempData = new TempDataDictionary(); foreach (var kv in controller.TempData) { oldTempData.Add(kv.Key, kv.Value); } // Loading the temp data removes all current temp data. controller.TempData.Load(controller.ControllerContext, controller.TempDataProvider); // Restoring the current temp data. foreach (var kv in oldTempData) { controller.TempData[kv.Key] = kv.Value; } } } catch (Exception ex) { var exceptionMessage = string.Format( "Failed to Load TempData. Class: {0}, Method: {1}, Exception {2}, Stack Trace {3}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name, ex.Message, ex.StackTrace); Log.Write(exceptionMessage, ConfigurationPolicy.ErrorLog); } }
private static void Set(Type type, TempDataDictionary tempDataDictionary, string message) { if (string.IsNullOrEmpty(message) || tempDataDictionary.ContainsKey(type.ToString())) { return; } tempDataDictionary.Add(type.ToString(), message); }
public override void OnException(ExceptionContext filterContext) { if (filterContext.ExceptionHandled == true) { return; } else { ControllerBase controllerContext = filterContext.Controller; string subject = ""; string message = filterContext.Exception.Message; if (controllerContext.GetType() == typeof(HomeController)) { subject = ((HomeController)controllerContext).getError().ErrorSubject; } else if (controllerContext.GetType() == typeof(AccountController)) { controllerContext = (AccountController)controllerContext; subject = ((AccountController)controllerContext).getError().ErrorSubject; } else if (controllerContext.GetType() == typeof(AdminController)) { subject = ((AdminController)controllerContext).getError().ErrorSubject; } TempDataDictionary controllerTempData = filterContext.Controller.TempData; if (subject == null || subject.Equals("")) //if no error subject was provided { //set to default errsubject: subject = "An internal error occured"; } controllerTempData.Add("errorSubject", subject); controllerTempData.Add("errorMessage", message); filterContext.Result = new ViewResult { ViewName = "Error", TempData = controllerTempData }; } filterContext.ExceptionHandled = true; }
public static void FlashMessage(this TempDataDictionary data, string message, string title = null, FlashMessageTypeEnum type = FlashMessageTypeEnum.Green) { if (data.FlashExists()) { data.ResetFlash(); } data.Add("FlashMessage", new FlashMessage { Message = message, Title = title, Type = type }); }
public IActionResult MessageLayout(string viewName, string title, string message, string backUrl, string note = "") { TempDataDictionary tempData = new TempDataDictionary(HttpContext, _tempDataProvider); tempData.Add("Title", title); tempData.Add("Message", message); tempData.Add("Note", note); tempData.Add("BaseUrl", BaseUrl); tempData.Add("BackUrl", backUrl); if (string.IsNullOrEmpty(viewName)) { viewName = ControllerContext.ActionDescriptor.DisplayName; } PartialViewResult partialView = new PartialViewResult(); partialView.ViewName = viewName; partialView.TempData = tempData; partialView.ViewData = ViewData; partialView.ViewEngine = _serviceProvider.GetService(typeof(ICompositeViewEngine)) as ICompositeViewEngine; ActionContext actionContext = new ActionContext(); partialView.ExecuteResult(actionContext); return(partialView); }
/// <summary> /// Notify user of exception via a View. /// </summary> /// <param name="filterContext">ExceptionContext object</param> /// private void NotifyUserViaView(ExceptionContext filterContext) { filterContext.ExceptionHandled = true; filterContext.HttpContext.Response.Clear(); filterContext.HttpContext.Response.StatusCode = 500; filterContext.HttpContext.Response.TrySkipIisCustomErrors = true; var errorMessage = filterContext.Exception.Message; var tempData = new TempDataDictionary(); tempData.Add("ErrorMessage", errorMessage); filterContext.Result = new ViewResult { ViewName = "Error", TempData = tempData }; }
public async Task <string> RenderStringAsync <TModel>(string name, TModel model, IReadOnlyDictionary <string, object> tempData = null, HtmlHelperOptions htmlHelperOptions = null) { var actionContext = new ActionContext(new DefaultHttpContext { RequestServices = _serviceProvider }, new RouteData(), new ActionDescriptor()); var viewEngineResult = _viewEngine.FindView(actionContext, name, false); if (!viewEngineResult.Success) { throw new InvalidOperationException($"Couldn't find view '{name}'"); } var tempDataDictionary = new TempDataDictionary(actionContext.HttpContext, _tempDataProvider); if (tempData != null) { foreach (var(key, value) in tempData) { tempDataDictionary.Add(key, value); } } var view = viewEngineResult.View; await using var output = new StringWriter(); var viewContext = new ViewContext( actionContext, view, new ViewDataDictionary <TModel>(new EmptyModelMetadataProvider(), new ModelStateDictionary()) { Model = model }, tempDataDictionary , output, htmlHelperOptions ?? new HtmlHelperOptions()); await view.RenderAsync(viewContext); return(output.ToString()); }
public void Result_WithCorrectTempData() { var test = new List <string>(); test.Add("David,Rudd,60050,9%,01 March - 31 March"); TestControllerBuilder builder = new TestControllerBuilder(); var tempData = new TempDataDictionary(); tempData.Add("rawCSV", test); HomeController controller = new HomeController(); builder.InitializeController(controller); controller.TempData = tempData; var result = controller.Result() as ViewResult; Assert.IsNotNull(result); Assert.IsNotNull(controller.Session["plist"]); }
public async Task <string> RenderTemplateAsync <TViewModel>(string filename, TViewModel viewModel) { var httpContext = new DefaultHttpContext { RequestServices = _serviceProvider }; var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor()); using (var outputWriter = new StringWriter()) { var viewResult = _viewEngine.FindView(actionContext, filename, false); var viewDictionary = new ViewDataDictionary <TViewModel>(new EmptyModelMetadataProvider(), new ModelStateDictionary()) { Model = viewModel }; var tempDataDictionary = new TempDataDictionary(httpContext, _tempDataProvider); //tempDataDictionary.Add("Employees", viewModel); tempDataDictionary.Add(filename, viewModel); if (!viewResult.Success) { throw new TemplateServiceException($"Failed to render template {filename} because it was not found."); } try { var viewContext = new ViewContext(actionContext, viewResult.View, viewDictionary, tempDataDictionary, outputWriter, new HtmlHelperOptions()); await viewResult.View.RenderAsync(viewContext); } catch (Exception ex) { throw new TemplateServiceException("Failed to render template due to a razor engine failure", ex); } return(outputWriter.ToString()); } }
/// <summary> /// Adds or replaces a value in a TempDataDictionary. /// </summary> /// <param name="dict">The TempDataDictionary</param> /// <param name="key">The key to add or replace</param> /// <param name="value">The value for the corresponding key</param> /// <returns>Returns false, if the value of an existing key has changed, otherwise true.</returns> public static bool AddOrReplace(this TempDataDictionary dict, string key, object value) { if (dict == null) { throw new ArgumentNullException(nameof(dict)); } if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException(nameof(key)); } if (dict.ContainsKey(key)) { dict[key] = value; return(false); } dict.Add(key, value); return(true); }
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { if (!filterContext.HttpContext.User.Identity.IsAuthenticated) { //Here login page is called base.HandleUnauthorizedRequest(filterContext); } else { if (!this.IsAuthorized) { var tempData = new TempDataDictionary(); tempData.Add("ErrorReason", "Unauthorized"); filterContext.Result = new ViewResult() { ViewName = "Error", TempData = tempData }; } } }
private static void AddMessage(TempDataDictionary tempData, TempMessage message) { IList <TempMessage> list = null; if (tempData.ContainsKey(TempMessage.TempDataKey)) { list = tempData[TempMessage.TempDataKey] as IList <TempMessage>; if (list != null) { list.Add(message); } } if (list == null) { list = new List <TempMessage>(); list.Add(message); tempData.Add(TempMessage.TempDataKey, list); } }
public bool use(TempDataDictionary ViewData, out T savedObject, string sessionVarName, useSessionFunc methodsetObject) { bool newData; savedObject = default(T); object sessionVar = ViewData[sessionVarName]; if ((sessionVar == null || !(sessionVar.GetType() == typeof(T))) && methodsetObject != null) { newData = true; methodsetObject(out savedObject); // set saved to value ViewData.Add(sessionVarName, savedObject); } else { newData = false; savedObject = (T)ViewData[sessionVarName]; } return(newData); }
protected override void OnException(ExceptionContext filterContext) { filterContext.ExceptionHandled = true; string ErrorId = Guid.NewGuid().ToString(); string messageException = string.Format("ErrorId:{0} ,Details:{1}", ErrorId, telemetria.MakeMessageException(filterContext.Exception, System.Reflection.MethodBase.GetCurrentMethod().Name) ); telemetria.Critical(messageException); // OR TempDataDictionary errors = new TempDataDictionary(); errors.Add("ErrorId", ErrorId); filterContext.Result = new ViewResult { ViewName = "~/Views/Error/InternalServer.cshtml", TempData = errors }; }
public async Task GetShouldReturnListOfNews() { var mockRepo = new Mock <INewsRepository>(); string userId = "Jack"; mockRepo.Setup(repo => repo.GetAllNews(userId)).Returns(Task.FromResult(this.newsList)); var httpContext = new DefaultHttpContext(); var tempData = new TempDataDictionary(httpContext, Mock.Of <ITempDataProvider>()); tempData.Add("uId", "Jack"); var newsController = new NewsController(mockRepo.Object); newsController.TempData = tempData; var actual = await newsController.Index(); var actionResult = Assert.IsType <ViewResult>(actual); Assert.True(actionResult.ViewData.Values.Count > 0); Assert.IsAssignableFrom <List <News> >(actionResult.ViewData["newslist"]); }
public void LoadTempDataIgnoresNullResponseCookieDoesNotThrowException() { HttpCookie cookie = new HttpCookie("__ControllerTempData"); TempDataDictionary initialTempData = new TempDataDictionary(); initialTempData.Add("WhatIsInHere?", "Stuff"); cookie.Value = CookieTempDataProvider.SerializeToBase64EncodedString(initialTempData); var cookies = new HttpCookieCollection(); cookies.Add(cookie); var requestMock = new Mock<HttpRequestBase>(); requestMock.Expect(r => r.Cookies).Returns(cookies); var responseMock = new Mock<HttpResponseBase>(); responseMock.Expect(r => r.Cookies).Returns((HttpCookieCollection)null); var httpContextMock = new Mock<HttpContextBase>(); httpContextMock.Expect(c => c.Request).Returns(requestMock.Object); httpContextMock.Expect(c => c.Response).Returns(responseMock.Object); ITempDataProvider provider = new CookieTempDataProvider(httpContextMock.Object); IDictionary<string, object> tempData = provider.LoadTempData(null /* controllerContext */); Assert.AreEqual("Stuff", tempData["WhatIsInHere?"]); }
protected void Application_Error(object sender, EventArgs e) { telemetria = new Trace(); Exception exception = Server.GetLastError(); if (exception != null) { string ErrorId = Guid.NewGuid().ToString(); string messageException = string.Format("ErrorId:{0} ,Details:{1}", ErrorId, telemetria.MakeMessageException(exception, System.Reflection.MethodBase.GetCurrentMethod().Name) ); telemetria.Critical(messageException); TempDataDictionary errors = new TempDataDictionary(); errors.Add("ErrorId", ErrorId); var httpContext = ((HttpApplication)sender).Context; httpContext.Response.Clear(); httpContext.ClearError(); httpContext.Response.TrySkipIisCustomErrors = true; InvokeErrorAction(httpContext, exception); } }
public static void ToastError(this TempDataDictionary tempData, string message = null) { tempData.Add(ToastrNotificationsEnum.ValidationOrException.ToString(), string.IsNullOrWhiteSpace(message) ? "Action Required. Kindly review below." : message); }
public void SaveTempDataStoresSerializedFormInCookie() { var cookies = new HttpCookieCollection(); var responseMock = new Mock<HttpResponseBase>(); responseMock.Expect(r => r.Cookies).Returns(cookies); var httpContextMock = new Mock<HttpContextBase>(); httpContextMock.Expect(c => c.Response).Returns(responseMock.Object); ITempDataProvider provider = new CookieTempDataProvider(httpContextMock.Object); var tempData = new TempDataDictionary(); tempData.Add("Testing", "Turn it up to 11"); tempData.Add("Testing2", 1.23); provider.SaveTempData(null, tempData); HttpCookie cookie = cookies["__ControllerTempData"]; string serialized = cookie.Value; IDictionary<string, object> deserializedTempData = CookieTempDataProvider.DeserializeTempData(serialized); Assert.AreEqual("Turn it up to 11", deserializedTempData["Testing"]); Assert.AreEqual(1.23, deserializedTempData["Testing2"]); }
public void TempDataIsADictionary() { // Arrange TempDataDictionary tempData = new TempDataDictionary(); // Act tempData["Key1"] = "Value1"; tempData.Add("Key2", "Value2"); ((ICollection<KeyValuePair<string, object>>)tempData).Add(new KeyValuePair<string,object>("Key3", "Value3")); // Assert (IDictionary) Assert.AreEqual(3, tempData.Count, "tempData should contain 3 items"); Assert.IsTrue(tempData.Remove("Key1"), "The key should be present"); Assert.IsFalse(tempData.Remove("Key4"), "The key should not be present"); Assert.IsTrue(tempData.ContainsValue("Value2"), "The value should be present"); Assert.IsFalse(tempData.ContainsValue("Value1"), "The value should not be present"); Assert.IsNull(tempData["Key6"], "The key should not be present"); IEnumerator tempDataEnumerator = tempData.GetEnumerator(); tempDataEnumerator.Reset(); while (tempDataEnumerator.MoveNext()) { KeyValuePair<string, object> pair = (KeyValuePair<string, object>)tempDataEnumerator.Current; Assert.IsTrue(((ICollection<KeyValuePair<string, object>>)tempData).Contains(pair), "The key/value pair should be present"); } // Assert (ICollection) foreach (string key in tempData.Keys) { Assert.IsTrue(((ICollection<KeyValuePair<string, object>>)tempData).Contains(new KeyValuePair<string, object>(key, tempData[key])), "The key/value pair should be present"); } foreach (string value in tempData.Values) { Assert.IsTrue(tempData.ContainsValue(value)); } foreach (string key in ((IDictionary<string, object>)tempData).Keys) { Assert.IsTrue(tempData.ContainsKey(key), "The key should be present"); } foreach (string value in ((IDictionary<string, object>)tempData).Values) { Assert.IsTrue(tempData.ContainsValue(value)); } KeyValuePair<string, object>[] keyValuePairArray = new KeyValuePair<string, object>[tempData.Count]; ((ICollection<KeyValuePair<string, object>>)tempData).CopyTo(keyValuePairArray, 0); Assert.IsFalse(((ICollection<KeyValuePair<string, object>>)tempData).IsReadOnly, "The dictionary should not be read-only."); Assert.IsFalse(((ICollection<KeyValuePair<string, object>>)tempData).Remove(new KeyValuePair<string, object>("Key5", "Value5")), "The key/value pair should not be present"); IEnumerator<KeyValuePair<string, object>> keyValuePairEnumerator = ((ICollection<KeyValuePair<string, object>>)tempData).GetEnumerator(); keyValuePairEnumerator.Reset(); while (keyValuePairEnumerator.MoveNext()) { KeyValuePair<string, object> pair = keyValuePairEnumerator.Current; Assert.IsTrue(((ICollection<KeyValuePair<string, object>>)tempData).Contains(pair), "The key/value pair should be present"); } // Act tempData.Clear(); // Assert Assert.AreEqual(0, tempData.Count, "tempData should not contain any items"); IEnumerator y = ((IEnumerable)tempData).GetEnumerator(); while (y.MoveNext()) { Assert.Fail("There should not be any elements in tempData"); } }
//private void CacheValidateHandler(HttpContext context, object data, ref HttpValidationStatus validationStatus) //{ // validationStatus = OnCacheAuthorization(new HttpContextWrapper(context)); //} public virtual void OnAuthorization(AuthorizationContext filterContext) { this._empRepo = DependencyResolver.Current.GetService <IEmployeeRepository>(); this._configRepo = DependencyResolver.Current.GetService <IConfigRepository>(); var __config = _configRepo.GetConfigCache(); //nếu mà allowAnonymous thì bỏ qua if (this.IsAnonymousAction(filterContext)) { return; } var rd = filterContext.RequestContext.RouteData; string currentAction = rd.GetRequiredString("action"); string currentController = rd.GetRequiredString("controller"); string currentArea = rd.Values["area"] as string; var area = HttpContext.Current.Request.RequestContext.RouteData.DataTokens["area"]; var currentRequestReturnUrl = rd.Values["ReturnUrl"]; string _returnUrl = filterContext.HttpContext.Request.Url.AbsoluteUri; if (currentRequestReturnUrl != null) { if (!string.IsNullOrWhiteSpace(currentRequestReturnUrl as string)) { _returnUrl = currentRequestReturnUrl as string; } } _returnUrl = myBase64EncodeDecode.EncodeBase64(_returnUrl); if (filterContext == null) { throw new ArgumentNullException("filterContext"); } if (!AuthorizeCore(filterContext.HttpContext)) { string _err_msg = __config.conf_val_login_employees; TempDataDictionary tempdata = filterContext.Controller.TempData; if (filterContext.HttpContext.Request.IsAjaxRequest()) { filterContext.HttpContext.Response.StatusCode = 401; filterContext.Result = new JsonResult() { JsonRequestBehavior = JsonRequestBehavior.AllowGet, ContentType = "application/json", ContentEncoding = Encoding.UTF8, Data = rs.Err(401, _err_msg) }; /* * filterContext.HttpContext.Response.ContentType = "application/json"; * filterContext.Result = new HttpUnauthorizedResult(_err_msg);*/ } else { //here we will need to pass to the access denied if (!string.IsNullOrWhiteSpace(Message)) { _err_msg = Message; } if (!tempdata.ContainsKey("message")) { tempdata.Add("message", _err_msg); } filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { action = "Login", controller = "Candidates", area = currentArea, relog = "c", returnUrl = _returnUrl })); } //filterContext.Result = new RedirectResult(loginUrl); // FilterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Auth", action = "SSLogin",area="" })); // New HttpUnauthorizedResult(); } else { // ** IMPORTANT ** // Since we're performing authorization at the action level, the authorization code runs // After the output caching module. In the worst case this could allow an authorized user // To cause the page to be cached, then an unauthorized user would later be served the // Cached page. We work around this by telling proxies not to cache the sensitive page, // Then we hook our custom authorization code into the caching mechanism so that we have // The final say on whether a page should be served from the cache. //HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache; //cachePolicy.SetProxyMaxAge(new TimeSpan(0)); //cachePolicy.AddValidationCallback(CacheValidateHandler, null /* data */); } }
public void TempDataIsADictionary() { // Arrange TempDataDictionary tempData = new TempDataDictionary(); // Act tempData["Key1"] = "Value1"; tempData.Add("Key2", "Value2"); ((ICollection <KeyValuePair <string, object> >)tempData).Add(new KeyValuePair <string, object>("Key3", "Value3")); // Assert (IDictionary) Assert.Equal(3, tempData.Count); Assert.True(tempData.Remove("Key1")); Assert.False(tempData.Remove("Key4")); Assert.True(tempData.ContainsValue("Value2")); Assert.False(tempData.ContainsValue("Value1")); Assert.Null(tempData["Key6"]); IEnumerator tempDataEnumerator = tempData.GetEnumerator(); tempDataEnumerator.Reset(); while (tempDataEnumerator.MoveNext()) { KeyValuePair <string, object> pair = (KeyValuePair <string, object>)tempDataEnumerator.Current; Assert.True(((ICollection <KeyValuePair <string, object> >)tempData).Contains(pair)); } // Assert (ICollection) foreach (string key in tempData.Keys) { Assert.True(((ICollection <KeyValuePair <string, object> >)tempData).Contains(new KeyValuePair <string, object>(key, tempData[key]))); } foreach (string value in tempData.Values) { Assert.True(tempData.ContainsValue(value)); } foreach (string key in ((IDictionary <string, object>)tempData).Keys) { Assert.True(tempData.ContainsKey(key)); } foreach (string value in ((IDictionary <string, object>)tempData).Values) { Assert.True(tempData.ContainsValue(value)); } KeyValuePair <string, object>[] keyValuePairArray = new KeyValuePair <string, object> [tempData.Count]; ((ICollection <KeyValuePair <string, object> >)tempData).CopyTo(keyValuePairArray, 0); Assert.False(((ICollection <KeyValuePair <string, object> >)tempData).IsReadOnly); Assert.False(((ICollection <KeyValuePair <string, object> >)tempData).Remove(new KeyValuePair <string, object>("Key5", "Value5"))); IEnumerator <KeyValuePair <string, object> > keyValuePairEnumerator = ((ICollection <KeyValuePair <string, object> >)tempData).GetEnumerator(); keyValuePairEnumerator.Reset(); while (keyValuePairEnumerator.MoveNext()) { KeyValuePair <string, object> pair = keyValuePairEnumerator.Current; Assert.True(((ICollection <KeyValuePair <string, object> >)tempData).Contains(pair)); } // Act tempData.Clear(); // Assert Assert.Empty(tempData); }
public static void ToastSuccess(this TempDataDictionary tempData, string message = null) { tempData.Add(ToastrNotificationsEnum.Success.ToString(), string.IsNullOrWhiteSpace(message) ? "Action Completed Successfully." : message); }
public void TempDataIsADictionary() { // Arrange TempDataDictionary tempData = new TempDataDictionary(); // Act tempData["Key1"] = "Value1"; tempData.Add("Key2", "Value2"); ((ICollection<KeyValuePair<string, object>>)tempData).Add(new KeyValuePair<string, object>("Key3", "Value3")); // Assert (IDictionary) Assert.Equal(3, tempData.Count); Assert.True(tempData.Remove("Key1")); Assert.False(tempData.Remove("Key4")); Assert.True(tempData.ContainsValue("Value2")); Assert.False(tempData.ContainsValue("Value1")); Assert.Null(tempData["Key6"]); IEnumerator tempDataEnumerator = tempData.GetEnumerator(); tempDataEnumerator.Reset(); while (tempDataEnumerator.MoveNext()) { KeyValuePair<string, object> pair = (KeyValuePair<string, object>)tempDataEnumerator.Current; Assert.True(((ICollection<KeyValuePair<string, object>>)tempData).Contains(pair)); } // Assert (ICollection) foreach (string key in tempData.Keys) { Assert.True(((ICollection<KeyValuePair<string, object>>)tempData).Contains(new KeyValuePair<string, object>(key, tempData[key]))); } foreach (string value in tempData.Values) { Assert.True(tempData.ContainsValue(value)); } foreach (string key in ((IDictionary<string, object>)tempData).Keys) { Assert.True(tempData.ContainsKey(key)); } foreach (string value in ((IDictionary<string, object>)tempData).Values) { Assert.True(tempData.ContainsValue(value)); } KeyValuePair<string, object>[] keyValuePairArray = new KeyValuePair<string, object>[tempData.Count]; ((ICollection<KeyValuePair<string, object>>)tempData).CopyTo(keyValuePairArray, 0); Assert.False(((ICollection<KeyValuePair<string, object>>)tempData).IsReadOnly); Assert.False(((ICollection<KeyValuePair<string, object>>)tempData).Remove(new KeyValuePair<string, object>("Key5", "Value5"))); IEnumerator<KeyValuePair<string, object>> keyValuePairEnumerator = ((ICollection<KeyValuePair<string, object>>)tempData).GetEnumerator(); keyValuePairEnumerator.Reset(); while (keyValuePairEnumerator.MoveNext()) { KeyValuePair<string, object> pair = keyValuePairEnumerator.Current; Assert.True(((ICollection<KeyValuePair<string, object>>)tempData).Contains(pair)); } // Act tempData.Clear(); // Assert Assert.Empty(tempData); }
public void TempDataIsADictionary() { // Arrange TempDataDictionary tempData = new TempDataDictionary(); // Act tempData["Key1"] = "Value1"; tempData.Add("Key2", "Value2"); ((ICollection <KeyValuePair <string, object> >)tempData).Add(new KeyValuePair <string, object>("Key3", "Value3")); // Assert (IDictionary) Assert.AreEqual(3, tempData.Count, "tempData should contain 3 items"); Assert.IsTrue(tempData.Remove("Key1"), "The key should be present"); Assert.IsFalse(tempData.Remove("Key4"), "The key should not be present"); Assert.IsTrue(tempData.ContainsValue("Value2"), "The value should be present"); Assert.IsFalse(tempData.ContainsValue("Value1"), "The value should not be present"); Assert.IsNull(tempData["Key6"], "The key should not be present"); IEnumerator tempDataEnumerator = tempData.GetEnumerator(); tempDataEnumerator.Reset(); while (tempDataEnumerator.MoveNext()) { KeyValuePair <string, object> pair = (KeyValuePair <string, object>)tempDataEnumerator.Current; Assert.IsTrue(((ICollection <KeyValuePair <string, object> >)tempData).Contains(pair), "The key/value pair should be present"); } // Assert (ICollection) foreach (string key in tempData.Keys) { Assert.IsTrue(((ICollection <KeyValuePair <string, object> >)tempData).Contains(new KeyValuePair <string, object>(key, tempData[key])), "The key/value pair should be present"); } foreach (string value in tempData.Values) { Assert.IsTrue(tempData.ContainsValue(value)); } foreach (string key in ((IDictionary <string, object>)tempData).Keys) { Assert.IsTrue(tempData.ContainsKey(key), "The key should be present"); } foreach (string value in ((IDictionary <string, object>)tempData).Values) { Assert.IsTrue(tempData.ContainsValue(value)); } KeyValuePair <string, object>[] keyValuePairArray = new KeyValuePair <string, object> [tempData.Count]; ((ICollection <KeyValuePair <string, object> >)tempData).CopyTo(keyValuePairArray, 0); Assert.IsFalse(((ICollection <KeyValuePair <string, object> >)tempData).IsReadOnly, "The dictionary should not be read-only."); Assert.IsFalse(((ICollection <KeyValuePair <string, object> >)tempData).Remove(new KeyValuePair <string, object>("Key5", "Value5")), "The key/value pair should not be present"); IEnumerator <KeyValuePair <string, object> > keyValuePairEnumerator = ((ICollection <KeyValuePair <string, object> >)tempData).GetEnumerator(); keyValuePairEnumerator.Reset(); while (keyValuePairEnumerator.MoveNext()) { KeyValuePair <string, object> pair = keyValuePairEnumerator.Current; Assert.IsTrue(((ICollection <KeyValuePair <string, object> >)tempData).Contains(pair), "The key/value pair should be present"); } // Act tempData.Clear(); // Assert Assert.AreEqual(0, tempData.Count, "tempData should not contain any items"); IEnumerator y = ((IEnumerable)tempData).GetEnumerator(); while (y.MoveNext()) { Assert.Fail("There should not be any elements in tempData"); } }
public void CanLoadTempDataFromCookie() { var tempData = new TempDataDictionary(); tempData.Add("abc", "easy as 123"); tempData.Add("price", 1.234); string serializedTempData = CookieTempDataProvider.SerializeToBase64EncodedString(tempData); var cookies = new HttpCookieCollection(); var httpCookie = new HttpCookie("__ControllerTempData"); httpCookie.Value = serializedTempData; cookies.Add(httpCookie); var requestMock = new Mock<HttpRequestBase>(); requestMock.Expect(r => r.Cookies).Returns(cookies); var responseMock = new Mock<HttpResponseBase>(); responseMock.Expect(r => r.Cookies).Returns(cookies); var httpContextMock = new Mock<HttpContextBase>(); httpContextMock.Expect(c => c.Request).Returns(requestMock.Object); httpContextMock.Expect(c => c.Response).Returns(responseMock.Object); ITempDataProvider provider = new CookieTempDataProvider(httpContextMock.Object); IDictionary<string, object> loadedTempData = provider.LoadTempData(null /* controllerContext */); Assert.AreEqual(2, loadedTempData.Count); Assert.AreEqual("easy as 123", loadedTempData["abc"]); Assert.AreEqual(1.234, loadedTempData["price"]); }