Esempio n. 1
0
 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
         });
     }
 }
Esempio n. 2
0
        public void ExecuteResultPreservesTempData()
        {
            // Arrange
            TempDataDictionary tempData = new TempDataDictionary();

            tempData["Foo"] = "Foo";
            tempData["Bar"] = "Bar";
            Mock <Controller> mockController = new Mock <Controller>()
            {
                CallBase = true
            };

            mockController.Object.TempData = tempData;
            Mock <ControllerContext> mockControllerContext = new Mock <ControllerContext>();

            mockControllerContext
            .Setup(c => c.HttpContext.Request.ApplicationPath)
            .Returns("/somepath");
            mockControllerContext
            .Setup(c => c.HttpContext.Response.ApplyAppPathModifier(It.IsAny <string>()))
            .Returns((string s) => s);
            mockControllerContext
            .Setup(c => c.HttpContext.Response.Redirect("/somepath/c/a/i", false))
            .Verifiable();
            mockControllerContext.Setup(c => c.Controller).Returns(mockController.Object);

            var values = new { Controller = "c", Action = "a", Id = "i" };
            RedirectToRouteResult result = new RedirectToRouteResult(
                new RouteValueDictionary(values)
                )
            {
                Routes = new RouteCollection()
                {
                    new Route("{controller}/{action}/{id}", null)
                },
            };

            // Act
            object value = tempData["Foo"];

            result.ExecuteResult(mockControllerContext.Object);
            mockController.Object.TempData.Save(
                mockControllerContext.Object,
                new Mock <ITempDataProvider>().Object
                );

            // Assert
            Assert.True(tempData.ContainsKey("Foo"));
            Assert.True(tempData.ContainsKey("Bar"));
        }
Esempio n. 3
0
        public void TempData_Save_RemovesKeysThatWereRead()
        {
            // Arrange
            var tempData = new TempDataDictionary(GetHttpContextAccessor(), new NullTempDataProvider());
            tempData["Foo"] = "Foo";
            tempData["Bar"] = "Bar";

            // Act
            var value = tempData["Foo"];
            tempData.Save();

            // Assert
            Assert.False(tempData.ContainsKey("Foo"));
            Assert.True(tempData.ContainsKey("Bar"));
        }
        private void CopyTempDataToModelState(ModelStateDictionary modelState, TempDataDictionary tempData)
        {
            if (!tempData.ContainsKey(TempDataKey))
            {
                return;
            }

            var fromTempData = tempData[TempDataKey] as ModelStateDictionary;

            if (fromTempData == null)
            {
                return;
            }

            foreach (var pair in fromTempData)
            {
                if (modelState.ContainsKey(pair.Key))
                {
                    modelState[pair.Key].Value = pair.Value.Value;

                    foreach (var error in pair.Value.Errors)
                    {
                        modelState[pair.Key].Errors.Add(error);
                    }
                }
                else
                {
                    modelState.Add(pair.Key, pair.Value);
                }
            }
        }
 public HomeIndexViewModel(TempDataDictionary tempData)
 {
     if (tempData.ContainsKey("CRUD"))
     {
         CRUDResult = (CRUDResultModel)tempData["CRUD"];
     }
 }
Esempio n. 6
0
        /// <summary>
        /// После выполнения действия производим слияние состояний моделей.
        /// </summary>
        public override void OnActionExecuted(ActionExecutedContext filter_context)
        {
            base.OnActionExecuted(filter_context);
            if (filter_context.HttpContext.Request.RequestType == "GET")
            {
                if (filter_context.Result is ViewResult)
                {
                    var view_result = filter_context.Result as ViewResult;
                    view_result.ViewData.ModelState.Clear();
                }
            }
            TempDataDictionary temp_data = filter_context.Controller.TempData;

            if (temp_data.ContainsKey(ModelStateKey))
            {
                var model_state = temp_data[ModelStateKey] as ModelStateDictionary;

                if (model_state != null)
                {
                    if (filter_context.Result is ViewResult)
                    {
                        // Производим слияние состояний модели.
                        filter_context.Controller.ViewData.ModelState.Merge(model_state);
                    }
                    else
                    {
                        filter_context.Controller.TempData.Remove(ModelStateKey);
                    }
                }
            }
        }
Esempio n. 7
0
    public void TempData_Keep_RetainsAllKeysWhenSavingDictionary()
    {
        // Arrange
        var tempData = new TempDataDictionary(new DefaultHttpContext(), new NullTempDataProvider());

        tempData["Foo"] = "Foo";
        tempData["Bar"] = "Bar";

        // Act
        tempData.Keep();
        tempData.Save();

        // Assert
        Assert.True(tempData.ContainsKey("Foo"));
        Assert.True(tempData.ContainsKey("Bar"));
    }
Esempio n. 8
0
        public static List <PersonalData> GetPersonalDataList(this TempDataDictionary tempData)
        {
            if (!tempData.ContainsKey(PersonalDataListKey))
            {
                tempData[PersonalDataListKey] = new List <PersonalData>
                {
                    new PersonalData
                    {
                        Name   = "Johny",
                        Age    = 25,
                        Gender = Gender.M,
                        Height = 185,
                        Weight = 85,
                        Pal    = 1.5,
                        Id     = 0,
                    },
                    new PersonalData
                    {
                        Name   = "Anna",
                        Age    = 22,
                        Gender = Gender.K,
                        Height = 160,
                        Weight = 50,
                        Pal    = 1.8,
                        Id     = 1
                    }
                };
            }

            return(tempData.Peek(PersonalDataListKey) as List <PersonalData>);
        }
Esempio n. 9
0
        private static List <Message> getMessages(TempDataDictionary tempData, HttpSessionStateBase session, bool useSession)
        {
            List <Message> res;

            if (useSession)
            {
                res = session[BaseController.SESSION_MESSAGES] as List <Message>;
            }
            else
            {
                if (tempData.ContainsKey(BaseController.VIEW_DATA_MESSAGES))
                {
                    res = tempData[BaseController.VIEW_DATA_MESSAGES] as List <Message>;
                }
                else
                {
                    res = null;
                }
            };
            if (res == null)
            {
                res = new List <Message>();
            }
            ;
            return(res);
        }
        private void CopyTempDataToModelState(ModelStateDictionary modelState,
                                              TempDataDictionary tempData)
        {
            if (!tempData.ContainsKey(TempDataKey))
            {
                return;
            }

            ModelStateDictionary fromTempData = tempData[TempDataKey]
                                                    as ModelStateDictionary;
            if (fromTempData == null)
            {
                return;
            }

            foreach (KeyValuePair<string, ModelState> pair in fromTempData)
            {
                if (modelState.ContainsKey(pair.Key))
                {
                    modelState[pair.Key].Value = pair.Value.Value;

                    foreach (ModelError error in pair.Value.Errors)
                    {
                        modelState[pair.Key].Errors.Add(error);
                    }
                }
                else
                {
                    modelState.Add(pair.Key, pair.Value);
                }
            }
        }
Esempio n. 11
0
        public void OnTempDataSaving_PopulatesTempDataWithNewValuesFromPageProperties()
        {
            // Arrange
            var httpContext = new DefaultHttpContext();

            var tempData = new TempDataDictionary(httpContext, Mock.Of <ITempDataProvider>())
            {
                ["TempDataProperty-Test"] = "Old-Value",
            };
            var pageModel = new TestPageModel()
            {
                Test  = "TestString",
                Test2 = "Test2",
            };

            var filter = CreatePageSaveTempDataPropertyFilter(tempData, "TempDataProperty-");

            filter.Subject = pageModel;

            // Act
            filter.OnTempDataSaving(tempData);

            // Assert
            Assert.Equal("TestString", tempData["TempDataProperty-Test"]);
            Assert.False(tempData.ContainsKey("TestDataProperty-Test2"));
        }
Esempio n. 12
0
        private void CopyTempDataToModelState(ModelStateDictionary modelState, TempDataDictionary tempData)
        {
            if (!tempData.ContainsKey(TempDataKey)) return;

            var fromTempData = tempData[TempDataKey] as ModelStateDictionary;
            if (fromTempData == null) return;

            foreach (var pair in fromTempData)
            {
                if (modelState.ContainsKey(pair.Key))
                {
                    modelState[pair.Key].Value = pair.Value.Value;

                    foreach (var error in pair.Value.Errors)
                    {
                        if (!modelState[pair.Key].Errors.Contains(error))
                            modelState[pair.Key].Errors.Add(error);
                    }
                }
                else
                {
                    modelState.Add(pair.Key, pair.Value);
                }
            }
        }
Esempio n. 13
0
    public void TempData_Save_RemovesKeysThatWereRead()
    {
        // Arrange
        var tempData = new TempDataDictionary(new DefaultHttpContext(), new NullTempDataProvider());

        tempData["Foo"] = "Foo";
        tempData["Bar"] = "Bar";

        // Act
        var value = tempData["Foo"];

        tempData.Save();

        // Assert
        Assert.False(tempData.ContainsKey("Foo"));
        Assert.True(tempData.ContainsKey("Bar"));
    }
Esempio n. 14
0
    public void TempData_RemovalOfKeysAreCaseInsensitive()
    {
        var tempData = new TempDataDictionary(new DefaultHttpContext(), new NullTempDataProvider());

        tempData["Foo"] = "Foo";
        tempData["Bar"] = "Bar";

        // Act
        tempData.TryGetValue("foo", out var fooValue);
        var barValue = tempData["bar"];

        tempData.Save();

        // Assert
        Assert.False(tempData.ContainsKey("Foo"));
        Assert.False(tempData.ContainsKey("Boo"));
    }
        public void KeepRetainsAllKeysWhenSavingDictionary() {
            // Arrange
            NullTempDataProvider provider = new NullTempDataProvider();
            TempDataDictionary tempData = new TempDataDictionary();
            Mock<ControllerContext> controllerContext = new Mock<ControllerContext>();
            controllerContext.Setup(c => c.HttpContext.Request).Returns(new Mock<HttpRequestBase>().Object);
            tempData["Foo"] = "Foo";
            tempData["Bar"] = "Bar";

            // Act
            tempData.Keep();
            tempData.Save(controllerContext.Object, provider);

            // Assert
            Assert.IsTrue(tempData.ContainsKey("Foo"), "tempData should contain 'Foo'");
            Assert.IsTrue(tempData.ContainsKey("Bar"), "tempData should contain 'Bar'");
        }
Esempio n. 16
0
 public Notifications(TempDataDictionary tempDataDictionary)
 {
     if (!tempDataDictionary.ContainsKey(DictionaryName))
     {
         tempDataDictionary[DictionaryName] = new List <Notification>();
     }
     _notifications = tempDataDictionary[DictionaryName] as IList <Notification>;
 }
Esempio n. 17
0
 public static List <string> SuccessMessages(this TempDataDictionary tempData)
 {
     if (!tempData.ContainsKey("success-message"))
     {
         tempData["success-message"] = new List <string>();
     }
     return(tempData["success-message"] as List <string>);
 }
Esempio n. 18
0
 public static List <Alert> GetAlerts(this TempDataDictionary tempData)
 {
     if (!tempData.ContainsKey(Alerts))
     {
         tempData[Alerts] = new List <Alert>();
     }
     return((List <Alert>)tempData[Alerts]);
 }
        public void SaveRetainsAllKeys()
        {
            // Arrange
            NullTempDataProvider     provider          = new NullTempDataProvider();
            TempDataDictionary       tempData          = new TempDataDictionary();
            Mock <ControllerContext> controllerContext = new Mock <ControllerContext>();

            tempData["Foo"] = "Foo";
            tempData["Bar"] = "Bar";

            // Act
            tempData.Save(controllerContext.Object, provider);

            // Assert
            Assert.True(tempData.ContainsKey("Foo"));
            Assert.True(tempData.ContainsKey("Bar"));
        }
Esempio n. 20
0
 public Notifications(TempDataDictionary tempDataDictionary)
 {
     if (!tempDataDictionary.ContainsKey(DictionaryName))
     {
         tempDataDictionary[DictionaryName] = new List<Notification>();
     }
     _notifications = tempDataDictionary[DictionaryName] as IList<Notification>;
 }
Esempio n. 21
0
        public static List <Alert> GetAlerts(this TempDataDictionary tempData)
        {
            if (!tempData.ContainsKey(AppConstants.ALERT_KEY))
            {
                tempData[AppConstants.ALERT_KEY] = new List <Alert>();
            }

            return((List <Alert>)tempData[AppConstants.ALERT_KEY]);
        }
Esempio n. 22
0
        public static MvcHtmlString RenderFlash(this TempDataDictionary tempData)
        {
            MvcHtmlString result = MvcHtmlString.Empty;

            if (tempData != null)
            {
                if (tempData.ContainsKey(MessageKey))
                {
                    result = CreateFlash(tempData, MessageKey, FlashMessageClassName);
                }
                if (tempData.ContainsKey(ErrorKey))
                {
                    result = CreateFlash(tempData, ErrorKey, ErrorMessageClassName);
                }
            }

            return(result);
        }
Esempio n. 23
0
        public static SweetAlert GetAlert(this TempDataDictionary tempData)
        {
            if (!tempData.ContainsKey(SweetAlerts))
            {
                tempData[SweetAlerts] = new List <SweetAlert>();
            }

            return(((List <SweetAlert>)tempData[SweetAlerts]).LastOrDefault());
        }
Esempio n. 24
0
        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 static bool HasMessage(this TempDataDictionary dictionary)
        {
            if (dictionary != null && dictionary.ContainsKey(Key_Message))
            {
                return(true);
            }

            return(false);
        }
        public static object GetMessagePriority(this TempDataDictionary dictionary)
        {
            if (dictionary != null && dictionary.ContainsKey(Key_MessagePriority))
            {
                return(dictionary[Key_MessagePriority]);
            }

            return(null);
        }
Esempio n. 27
0
        private static string Get(Type type, TempDataDictionary tempDataDictionary)
        {
            if (!tempDataDictionary.ContainsKey(type.ToString()))
            {
                return(string.Empty);
            }

            return(tempDataDictionary[type.ToString()].ToString());
        }
        public static Toastr GetToastr(this TempDataDictionary tempData)
        {
            if (!tempData.ContainsKey(Toastr))
            {
                tempData[Toastr] = new Toastr();
            }

            return((Toastr)tempData[Toastr]);
        }
Esempio n. 29
0
        public override object ResolveWith(IInstanceResolver locator, IServiceLocatorStore context, PostResolutionPipeline pipeline)
        {
            if (!tempData.ContainsKey(registration.GetMappedToType().ToString()))
            {
                tempData[registration.GetMappedToType().ToString()] = registration.ResolveWith(locator, context, pipeline);
            }

            return(tempData[registration.GetMappedToType().ToString()]);
        }
        private static IDictionary <string, object> WrapArrayWithObject(dynamic model, TempDataDictionary tempData, ViewDataDictionary viewDataDictionary)
        {
            var output = new Dictionary <string, object>();

            // We want to avoid sending a JSON array as a response.
            // See http://haacked.com/archive/2009/06/25/json-hijacking.aspx
            // In cases where our model would be converted to an array,
            // we wrap it in an object.
            object wrappedModel = (typeof(IEnumerable)).IsInstanceOfType(model) ? new { model } : model;

            output["Model"] = wrappedModel;

            if (tempData.ContainsKey("alert"))
            {
                output["FlashAlert"] = tempData["alert"].ToString();
            }

            if (tempData.ContainsKey("confirm"))
            {
                output["FlashConfirm"] = tempData["confirm"].ToString();
            }

            if (viewDataDictionary.Any())
            {
                output["__view__"] = viewDataDictionary
                                     .ToDictionary(viewDataKeyValuePair => viewDataKeyValuePair.Key,
                                                   viewDataKeyValuePair => viewDataKeyValuePair.Value);
            }

            if (viewDataDictionary.ModelState.Any())
            {
                var errors = viewDataDictionary.ModelState
                             .Where(p => p.Value.Errors.Any());

                if (errors.Any())
                {
                    output["Errors"] = errors
                                       .ToDictionary(p => p.Key, p => p.Value.Errors.Select(x => x.ErrorMessage).ToArray());
                }
            }

            return(output);
        }
        public void KeepRetainsAllKeysWhenSavingDictionary()
        {
            // Arrange
            NullTempDataProvider     provider          = new NullTempDataProvider();
            TempDataDictionary       tempData          = new TempDataDictionary();
            Mock <ControllerContext> controllerContext = new Mock <ControllerContext>();

            controllerContext.Setup(c => c.HttpContext.Request).Returns(new Mock <HttpRequestBase>().Object);
            tempData["Foo"] = "Foo";
            tempData["Bar"] = "Bar";

            // Act
            tempData.Keep();
            tempData.Save(controllerContext.Object, provider);

            // Assert
            Assert.True(tempData.ContainsKey("Foo"));
            Assert.True(tempData.ContainsKey("Bar"));
        }
        public void SaveRemovesKeysThatWereRead()
        {
            // Arrange
            NullTempDataProvider     provider          = new NullTempDataProvider();
            TempDataDictionary       tempData          = new TempDataDictionary();
            Mock <ControllerContext> controllerContext = new Mock <ControllerContext>();

            tempData["Foo"] = "Foo";
            tempData["Bar"] = "Bar";

            // Act
            object value = tempData["Foo"];

            tempData.Save(controllerContext.Object, provider);

            // Assert
            Assert.False(tempData.ContainsKey("Foo"));
            Assert.True(tempData.ContainsKey("Bar"));
        }
Esempio n. 33
0
        public void EnumeratingDictionaryMarksValuesForDeletion() {
            // Arrange
            NullTempDataProvider provider = new NullTempDataProvider();
            TempDataDictionary tempData = new TempDataDictionary();
            Mock<ControllerContext> controllerContext = new Mock<ControllerContext>();
            tempData["Foo"] = "Foo";
            tempData["Bar"] = "Bar";

            // Act
            IEnumerator<KeyValuePair<string, object>> enumerator = tempData.GetEnumerator();
            while (enumerator.MoveNext()) {
                object value = enumerator.Current;
            }
            tempData.Save(controllerContext.Object, provider);

            // Assert
            Assert.IsFalse(tempData.ContainsKey("Foo"), "tempData should not contain 'Foo'");
            Assert.IsFalse(tempData.ContainsKey("Bar"), "tempData should not contain 'Bar'");
        }
Esempio n. 34
0
        public void TempData_EnumeratingDictionary_MarksKeysForDeletion()
        {
            // Arrange
            var tempData = new TempDataDictionary(GetHttpContextAccessor(), new NullTempDataProvider());
            tempData["Foo"] = "Foo";
            tempData["Bar"] = "Bar";

            // Act
            var enumerator = tempData.GetEnumerator();
            while (enumerator.MoveNext())
            {
                var value = enumerator.Current;
            }
            tempData.Save();

            // Assert
            Assert.False(tempData.ContainsKey("Foo"));
            Assert.False(tempData.ContainsKey("Bar"));
        }
Esempio n. 35
0
    public void TempData_LoadAndSaveAreCaseInsensitive()
    {
        // Arrange
        var data = new Dictionary <string, object>();

        data["Foo"] = "Foo";
        data["Bar"] = "Bar";
        var provider = new TestTempDataProvider(data);
        var tempData = new TempDataDictionary(new DefaultHttpContext(), provider);

        // Act
        tempData.Load();
        var value = tempData["FOO"];

        tempData.Save();

        // Assert
        Assert.False(tempData.ContainsKey("foo"));
        Assert.True(tempData.ContainsKey("bar"));
    }
        public void RemovalOfKeysAreCaseInsensitive()
        {
            NullTempDataProvider     provider          = new NullTempDataProvider();
            TempDataDictionary       tempData          = new TempDataDictionary();
            Mock <ControllerContext> controllerContext = new Mock <ControllerContext>();
            object fooValue;

            tempData["Foo"] = "Foo";
            tempData["Bar"] = "Bar";

            // Act
            tempData.TryGetValue("foo", out fooValue);
            object barValue = tempData["bar"];

            tempData.Save(controllerContext.Object, provider);

            // Assert
            Assert.False(tempData.ContainsKey("Foo"));
            Assert.False(tempData.ContainsKey("Boo"));
        }
        private static IDictionary<string,object> WrapArrayWithObject(dynamic model, TempDataDictionary tempData, ViewDataDictionary viewDataDictionary)
        {
            var output = new Dictionary<string, object>();

            // We want to avoid sending a JSON array as a response.
            // See http://haacked.com/archive/2009/06/25/json-hijacking.aspx
            // In cases where our model would be converted to an array,
            // we wrap it in an object.
            object wrappedModel = (typeof(IEnumerable)).IsInstanceOfType(model) ? new { model } : model;

            output["Model"] = wrappedModel;

            if (tempData.ContainsKey("alert"))
            {
                output["FlashAlert"] = tempData["alert"].ToString();
            }

            if (tempData.ContainsKey("confirm"))
            {
                output["FlashConfirm"] = tempData["confirm"].ToString();
            }
            
            if (viewDataDictionary.Any())
            {
                output["__view__"] = viewDataDictionary
                    .ToDictionary(viewDataKeyValuePair => viewDataKeyValuePair.Key,
                                  viewDataKeyValuePair => viewDataKeyValuePair.Value);
            }

            if (viewDataDictionary.ModelState.Any())
            {
                var errors = viewDataDictionary.ModelState
                    .Where(p => p.Value.Errors.Any());

                if(errors.Any())
                output["Errors"] = errors
                    .ToDictionary(p => p.Key, p => p.Value.Errors.Select(x => x.ErrorMessage).ToArray());
            }

            return output;
        }
        public void EnumeratingTempDataAsIEnmerableMarksValuesForDeletion()
        {
            // Arrange
            NullTempDataProvider provider = new NullTempDataProvider();
            TempDataDictionary tempData = new TempDataDictionary();
            Mock<ControllerContext> controllerContext = new Mock<ControllerContext>();
            tempData["Foo"] = "Foo";
            tempData["Bar"] = "Bar";

            // Act
            IEnumerator enumerator = ((IEnumerable)tempData).GetEnumerator();
            while (enumerator.MoveNext())
            {
                object value = enumerator.Current;
            }
            tempData.Save(controllerContext.Object, provider);

            // Assert
            Assert.False(tempData.ContainsKey("Foo"));
            Assert.False(tempData.ContainsKey("Bar"));
        }
Esempio n. 39
0
        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            if (!dictionary.ContainsKey(binder.Name))
            {
                result = null;
                return(true);
            }

            result = dictionary[binder.Name];

            return(true);
        }
Esempio n. 40
0
        public void TempData_TryGetValue_MarksKeyForDeletion()
        {
            var tempData = new TempDataDictionary(GetHttpContextAccessor(), new NullTempDataProvider());
            object value;
            tempData["Foo"] = "Foo";

            // Act
            tempData.TryGetValue("Foo", out value);
            tempData.Save();

            // Assert
            Assert.False(tempData.ContainsKey("Foo"));
        }
        public void PeekDoesNotMarkKeyAsRead()
        {
            // Arrange
            NullTempDataProvider provider = new NullTempDataProvider();
            TempDataDictionary tempData = new TempDataDictionary();
            Mock<ControllerContext> controllerContext = new Mock<ControllerContext>();
            tempData["Bar"] = "barValue";

            // Act
            object value = tempData.Peek("bar");
            tempData.Save(controllerContext.Object, provider);

            // Assert
            Assert.Equal("barValue", value);
            Assert.True(tempData.ContainsKey("Bar"));
        }
        public void KeepRetainsSpecificKeysWhenSavingDictionary()
        {
            // Arrange
            NullTempDataProvider provider = new NullTempDataProvider();
            TempDataDictionary tempData = new TempDataDictionary();
            Mock<ControllerContext> controllerContext = new Mock<ControllerContext>();
            controllerContext.Setup(c => c.HttpContext.Request).Returns(new Mock<HttpRequestBase>().Object);
            tempData["Foo"] = "Foo";
            tempData["Bar"] = "Bar";

            // Act
            tempData.Keep("Foo");
            object value = tempData["Bar"];
            tempData.Save(controllerContext.Object, provider);

            // Assert
            Assert.True(tempData.ContainsKey("Foo"));
            Assert.False(tempData.ContainsKey("Bar"));
        }
        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);
        }
Esempio n. 44
0
        public void TempData_RemovalOfKeysAreCaseInsensitive()
        {
            var tempData = new TempDataDictionary(GetHttpContextAccessor(), new NullTempDataProvider());
            object fooValue;
            tempData["Foo"] = "Foo";
            tempData["Bar"] = "Bar";

            // Act
            tempData.TryGetValue("foo", out fooValue);
            var barValue = tempData["bar"];
            tempData.Save();

            // Assert
            Assert.False(tempData.ContainsKey("Foo"));
            Assert.False(tempData.ContainsKey("Boo"));
        }
 /// <summary>
 /// Получаем старое значение отправленное из формы и сохраненные в TempData по имени поля
 /// </summary>
 /// <param name="name">имя поля</param>
 /// <param name="tempData"></param>
 /// <returns></returns>
 public static string GetFormDataFromTempDataByName(string name, TempDataDictionary tempData)
 {
     return tempData.ContainsKey("formData") ? ((tempData["formData"] as System.Collections.Specialized.NameValueCollection)[name]) : "";
 }
Esempio n. 46
0
        public void RemovalOfKeysAreCaseInsensitive() {
            NullTempDataProvider provider = new NullTempDataProvider();
            TempDataDictionary tempData = new TempDataDictionary();
            Mock<ControllerContext> controllerContext = new Mock<ControllerContext>();
            object fooValue;
            tempData["Foo"] = "Foo";
            tempData["Bar"] = "Bar";

            // Act
            tempData.TryGetValue("foo", out fooValue);
            object barValue = tempData["bar"];
            tempData.Save(controllerContext.Object, provider);

            // Assert
            Assert.IsFalse(tempData.ContainsKey("Foo"), "tempData should not contain 'Foo'");
            Assert.IsFalse(tempData.ContainsKey("Boo"), "tempData should not contain 'Bar'");
        }
Esempio n. 47
0
        public void TempData_LoadAndSaveAreCaseInsensitive()
        {
            // Arrange
            var data = new Dictionary<string, object>();
            data["Foo"] = "Foo";
            data["Bar"] = "Bar";
            var provider = new TestTempDataProvider(data);
            var tempData = new TempDataDictionary(GetHttpContextAccessor(), provider);

            // Act
            tempData.Load();
            var value = tempData["FOO"];
            tempData.Save();

            // Assert
            Assert.False(tempData.ContainsKey("foo"));
            Assert.True(tempData.ContainsKey("bar"));
        }
        public void ExecuteResultPreservesTempData() {
            // Arrange
            TempDataDictionary tempData = new TempDataDictionary();
            tempData["Foo"] = "Foo";
            tempData["Bar"] = "Bar";
            Mock<Controller> mockController = new Mock<Controller>() { CallBase = true };
            mockController.Object.TempData = tempData;
            Mock<ControllerContext> mockControllerContext = new Mock<ControllerContext>();
            mockControllerContext.Expect(c => c.HttpContext.Request.ApplicationPath).Returns("/somepath");
            mockControllerContext.Expect(c => c.HttpContext.Response.ApplyAppPathModifier(It.IsAny<string>())).Returns((string s) => s);
            mockControllerContext.Expect(c => c.HttpContext.Response.Redirect("/somepath/c/a/i", false)).Verifiable();
            mockControllerContext.Expect(c => c.Controller).Returns(mockController.Object);

            var values = new { Controller = "c", Action = "a", Id = "i" };
            RedirectToRouteResult result = new RedirectToRouteResult(new RouteValueDictionary(values)) {
                Routes = new RouteCollection() { new Route("{controller}/{action}/{id}", null) },
            };

            // Act
            object value = tempData["Foo"];
            result.ExecuteResult(mockControllerContext.Object);
            mockController.Object.TempData.Save(mockControllerContext.Object, new Mock<ITempDataProvider>().Object);

            // Assert
            Assert.IsTrue(tempData.ContainsKey("Foo"));
            Assert.IsTrue(tempData.ContainsKey("Bar"));
        }
Esempio n. 49
0
        public void TempData_Keep_RetainsSpecificKeysWhenSavingDictionary()
        {
            // Arrange
            var tempData = new TempDataDictionary(GetHttpContextAccessor(), new NullTempDataProvider());
            tempData["Foo"] = "Foo";
            tempData["Bar"] = "Bar";

            // Act
            var foo = tempData["Foo"];
            var bar = tempData["Bar"];
            tempData.Keep("Foo");
            tempData.Save();

            // Assert
            Assert.True(tempData.ContainsKey("Foo"));
            Assert.False(tempData.ContainsKey("Bar"));
        }
Esempio n. 50
0
        public void LoadAndSaveAreCaseInsensitive() {
            // Arrange
            Dictionary<string, object> data = new Dictionary<string, object>();
            data["Foo"] = "Foo";
            data["Bar"] = "Bar";
            TestTempDataProvider provider = new TestTempDataProvider(data);
            Mock<ControllerContext> controllerContext = new Mock<ControllerContext>();
            TempDataDictionary tempData = new TempDataDictionary();

            // Act
            tempData.Load(controllerContext.Object, provider);
            object value = tempData["FOO"];
            tempData.Save(controllerContext.Object, provider);

            // Assert
            Assert.IsFalse(tempData.ContainsKey("foo"), "tempData should not contain 'Foo'");
            Assert.IsTrue(tempData.ContainsKey("bar"), "tempData should contain 'Bar'");
        }
Esempio n. 51
0
        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");
            }
        }
Esempio n. 52
0
        public void TryGetValueMarksKeyForDeletion() {
            NullTempDataProvider provider = new NullTempDataProvider();
            TempDataDictionary tempData = new TempDataDictionary();
            Mock<ControllerContext> controllerContext = new Mock<ControllerContext>();
            object value;
            tempData["Foo"] = "Foo";

            // Act
            tempData.TryGetValue("Foo", out value);
            tempData.Save(controllerContext.Object, provider);

            // Assert
            Assert.IsFalse(tempData.ContainsKey("Foo"), "tempData should not contain 'Foo'");
        }
Esempio n. 53
0
        public void SaveRemovesKeysThatWereRead() {
            // Arrange
            NullTempDataProvider provider = new NullTempDataProvider();
            TempDataDictionary tempData = new TempDataDictionary();
            Mock<ControllerContext> controllerContext = new Mock<ControllerContext>();
            tempData["Foo"] = "Foo";
            tempData["Bar"] = "Bar";

            // Act
            object value = tempData["Foo"];
            tempData.Save(controllerContext.Object, provider);

            // Assert
            Assert.IsFalse(tempData.ContainsKey("Foo"), "tempData should not contain 'Foo'");
            Assert.IsTrue(tempData.ContainsKey("Bar"), "tempData should contain 'Bar'");
        }
Esempio n. 54
0
        public void SaveRetainsAllKeys() {
            // Arrange
            NullTempDataProvider provider = new NullTempDataProvider();
            TempDataDictionary tempData = new TempDataDictionary();
            Mock<ControllerContext> controllerContext = new Mock<ControllerContext>();
            tempData["Foo"] = "Foo";
            tempData["Bar"] = "Bar";

            // Act
            tempData.Save(controllerContext.Object, provider);

            // Assert
            Assert.IsTrue(tempData.ContainsKey("Foo"), "tempData should contain 'Foo'");
            Assert.IsTrue(tempData.ContainsKey("Bar"), "tempData should contain 'Bar'");
        }
Esempio n. 55
0
        private static void _AddMessages(TempDataDictionary tempData, BarData bar, IEnumerable<string> messages)
        {
            var key = GetTempDataKeyFor(bar);

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

            if (!tempData.ContainsKey(key))
            {
                tempData[key] = new List<string>();
            }

            var statusData = tempData[key] as IList<string>;
            messages.ForEach(x => statusData.Add(x));
            tempData.Keep(key); // Ensure list will be kept around..
        }
Esempio n. 56
0
        public void TempData_Peek_DoesNotMarkKeyForDeletion()
        {
            // Arrange
            var tempData = new TempDataDictionary(GetHttpContextAccessor(), new NullTempDataProvider());
            tempData["Bar"] = "barValue";

            // Act
            var value = tempData.Peek("bar");
            tempData.Save();

            // Assert
            Assert.Equal("barValue", value);
            Assert.True(tempData.ContainsKey("Bar"));
        }
        public void TempData_Keep_RetainsAllKeysWhenSavingDictionary()
        {
            // Arrange
            var tempData = new TempDataDictionary(new DefaultHttpContext(), new NullTempDataProvider());
            tempData["Foo"] = "Foo";
            tempData["Bar"] = "Bar";

            // Act
            tempData.Keep();
            tempData.Save();

            // Assert
            Assert.True(tempData.ContainsKey("Foo"));
            Assert.True(tempData.ContainsKey("Bar"));
        }
Esempio n. 58
0
        public void PeekDoesNotMarkKeyAsRead() {
            // Arrange
            NullTempDataProvider provider = new NullTempDataProvider();
            TempDataDictionary tempData = new TempDataDictionary();
            Mock<ControllerContext> controllerContext = new Mock<ControllerContext>();
            tempData["Bar"] = "barValue";

            // Act
            object value = tempData.Peek("bar");
            tempData.Save(controllerContext.Object, provider);

            // Assert
            Assert.AreEqual("barValue", value, "Incorrect value read from Peek().");
            Assert.IsTrue(tempData.ContainsKey("Bar"), "Peek() shouldn't have removed 'Bar' from TempData.");
        }