public void When_validator_implements_IValidatorInterceptor_directly_interceptor_invoked()
        {
            var form = new FormCollection {
                { "Email", "foo" },
                { "Surname", "foo" },
                { "Forename", "foo" },
            };

            var context = new ModelBindingContext {
                ModelName             = "test",
                ModelMetadata         = CreateMetaData(typeof(PropertiesTestModel2)),
                ModelState            = new ModelStateDictionary(),
                FallbackToEmptyPrefix = true,
                ValueProvider         = form.ToValueProvider(),
            };

            binder.BindModel(controllerContext, context);

            context.ModelState.IsValid.ShouldBeTrue();
        }
Beispiel #2
0
        public ActionResult Edit(int id, FormCollection collection)
        {
            var estacionaFacil = new CrudEstacionaFacil();

            TB_CONTROLE_VAGA tbControleVaga = estacionaFacil.TB_CONTROLE_VAGAs.Where(controleVaga => controleVaga.ID_Vagas == id).FirstOrDefault();

            try
            {
                // TODO: Add update logic here
                UpdateModel(tbControleVaga, collection.ToValueProvider());

                estacionaFacil.SubmitChanges();

                return(RedirectToAction("Index"));
            }
            catch
            {
                return(View());
            }
        }
Beispiel #3
0
        public ActionResult Edit(int id, FormCollection collection)
        {
            var estacionaFacil = new CrudEstacionaFacil();

            TB_FLUXO_CAIXA tbFluxoCaixa = estacionaFacil.TB_FLUXO_CAIXAs.Where(fluxocaixa => fluxocaixa.ID_Fluxo_Caixa == id).FirstOrDefault();

            try
            {
                // TODO: Add update logic here
                UpdateModel(tbFluxoCaixa, collection.ToValueProvider());

                estacionaFacil.SubmitChanges();

                return(RedirectToAction("Index"));
            }
            catch
            {
                return(View());
            }
        }
        public ActionResult LeadSourceAdd(FormCollection form)
        {
            lead_source target = new lead_source();

            //get property
            TryUpdateModel(target, new string[] { "source_name" }, form.ToValueProvider());
            //validate
            if (string.IsNullOrEmpty(target.source_name))
            {
                ModelState.AddModelError("source_name", "Project class is required");
            }

            if (ModelState.IsValid)
            {
                db.lead_source.Add(target);
                db.SaveChanges();
            }

            return(RedirectToAction("LeadSource"));
        }
        public void Should_add_all_erorrs_in_one_go_when_NotEmpty_rule_specified_for_non_nullable_value_type()
        {
            var form = new FormCollection {
                { "SomeBool", "False" },
                { "Id", "0" }
            };

            var context = new ModelBindingContext {
                ModelName             = "test",
                ModelMetadata         = CreateMetaData(typeof(TestModel5)),
                ModelState            = new ModelStateDictionary(),
                FallbackToEmptyPrefix = true,
                ValueProvider         = form.ToValueProvider(),
            };

            binder.BindModel(controllerContext, context);

            context.ModelState.IsValidField("SomeBool").ShouldBeFalse();       //Complex rule
            context.ModelState.IsValidField("Id").ShouldBeFalse();             //NotEmpty for non-nullable value type
        }
        public ActionResult ProjectClassAdd(FormCollection form)
        {
            project_class target = new project_class();

            //get property
            TryUpdateModel(target, new string[] { "class_name" }, form.ToValueProvider());
            //validate
            if (string.IsNullOrEmpty(target.class_name))
            {
                ModelState.AddModelError("project_class_name", "Project class is required");
            }

            if (ModelState.IsValid)
            {
                db.project_class.Add(target);
                db.SaveChanges();
            }

            return(RedirectToAction("ProjectClass"));
        }
        public void EditAction_Should_Redisplay_With_Errors_When_Update_Fails()
        {
            // Arrange
            var controller = CreateDinnersControllerAs("SomeUser");
            int id         = 1;

            FormCollection formValues = new FormCollection()
            {
                { "EventDate", "Bogus date value!!!" }
            };

            controller.ValueProvider = formValues.ToValueProvider();

            // Act
            //var result = controller.Edit(id, formValues) as ViewResult;

            // Assert
            //Assert.IsNotNull(result, "Expected redisplay of view");
            //Assert.IsTrue(result.ViewData.ModelState.Sum(p => p.Value.Errors.Count) > 0, "Expected Errors");
        }
        public ActionResult Edit(int id, FormCollection collection)
        {
            var estacionafacil = new CrudEstacionaFacil();

            TB_FLUXO_ENTRADA_SAIDA tbFluxoEntradaSaida = estacionafacil.TB_FLUXO_ENTRADA_SAIDAs.Where(fluxo_e_s => fluxo_e_s.ID_Fluxo_E_S == id).FirstOrDefault();

            try
            {
                // TODO: Add update logic here
                UpdateModel(tbFluxoEntradaSaida, collection.ToValueProvider());

                estacionafacil.SubmitChanges();

                return(RedirectToAction("Index"));
            }
            catch
            {
                return(View());
            }
        }
Beispiel #9
0
        public ActionResult Edit(int id, FormCollection collection)
        {
            var estacionaFacil = new CrudEstacionaFacil();

            TB_CLIENTES_DIARIO tbClienteDiario = estacionaFacil.TB_CLIENTES_DIARIOs.Where(clienteDiario => clienteDiario.ID_Clientes_Diarios == id).FirstOrDefault();

            try
            {
                // TODO: Add update logic here
                UpdateModel(tbClienteDiario, collection.ToValueProvider());

                estacionaFacil.SubmitChanges();

                return(RedirectToAction("Index"));
            }
            catch
            {
                return(View());
            }
        }
Beispiel #10
0
        public void Valid_name_and_connection_information()
        {
            //Arrange
            //Models.InstanceRepository repo = new QuartzAdmin.web.Models.InstanceRepository();
            FormCollection formData = new FormCollection();

            QuartzAdmin.web.Controllers.InstanceController controller = GetInstanceController();
            formData.Add("InstanceName", "MyFirstInstance");
            formData.Add("InstancePropertyKey1", "Red");
            formData.Add("InstancyPropertyValue1", "Dog");
            controller.ValueProvider = formData.ToValueProvider();

            //Act
            controller.Create(formData);
            InstanceModel newInstance = controller.Repository.GetByName("MyFirstInstance");

            //Assert
            Assert.IsNotNull(newInstance);
            Assert.AreEqual(formData["InstanceName"], newInstance.InstanceName);
        }
        public ActionResult Edit(int id, FormCollection collection)
        {
            var estacionafacil = new CrudEstacionaFacil();

            TB_VEICULO tbVeiculo = estacionafacil.TB_VEICULOs.Where(veiculo => veiculo.ID_Veiculo == id).FirstOrDefault();

            try
            {
                // TODO: Add update logic here
                UpdateModel(tbVeiculo, collection.ToValueProvider());

                estacionafacil.SubmitChanges();

                return(RedirectToAction("Index"));
            }
            catch
            {
                return(View());
            }
        }
        public ActionResult CrearLista(FormCollection collection)
        {
            try
            {
                var model = new Especial();
                TryUpdateModel(model, new string[]
                {
                    "Nombre", "Descripcion", "FechaInicio",
                    "FechaTermino", "Precio", "ProductoProductoId"
                }, collection.ToValueProvider());

                repository.AddEspecial(model);

                return(RedirectToAction("Lista", new { id = model.Producto.ProductoId }));
            }
            catch
            {
                return(View());
            }
        }
        public void Allows_override_of_required_property_name_for_non_nullable_value_types()
        {
            var form = new FormCollection {
                { "Id", "" }
            };

            var bindingContext = new ModelBindingContext {
                ModelName             = "test",
                ModelMetadata         = CreateMetaData(typeof(TestModelWithOverridenPropertyNameValueType)),
                ModelState            = new ModelStateDictionary(),
                FallbackToEmptyPrefix = true,
                ValueProvider         = form.ToValueProvider()
            };

            binder.BindModel(controllerContext, bindingContext);

            //TODO: Localise test.
            bindingContext.ModelState["Id"].Errors.Single().ErrorMessage.ShouldEqual("'Foo' must not be empty."
                                                                                     );
        }
        public ActionResult EditarLista(int id, FormCollection collection)
        {
            var model = repository.Especiales.First(e => e.EspecialId == id);

            try
            {
                TryUpdateModel(model,
                               new string[] {
                    "Nombre", "Descripcion", "FechaInicio", "FechaTermino",
                    "Precio", "ProductoProductoId"
                },
                               collection.ToValueProvider());

                repository.SaveDB();
                return(RedirectToAction("Lista", new { id = model.Producto.ProductoId }));
            }
            catch
            {
                return(View());
            }
        }
        public ViewResult CheckOut(Cart cart, FormCollection form)
        {
            // Empty carts can't be checked out
            if (cart.Lines.Count == 0)
            {
                ModelState.AddModelError("Cart", "Sorry, your cart is empty!");
                return(View());
            }

            // Invoke model binding manually
            if (TryUpdateModel(cart.ShippingDetails, form.ToValueProvider()))
            {
                orderSubmitter.SubmitOrder(cart);
                cart.Clear();
                return(View("Completed"));
            }
            else // Something was invalid
            {
                return(View());
            }
        }
Beispiel #16
0
        public void EditAction_Should_Redirect_When_Update_Successful()
        {
            // Arrange
            var controller = CreateDinnersControllerAs("SomeUser");

            var formValues = new FormCollection()
            {
                { "Title", "Another value" },
                { "ContactPhone", "2065551213" }
            };

            controller.ValueProvider = formValues.ToValueProvider();

            // Act
            var result = controller.Edit(1) as RedirectToRouteResult;



            // Assert
            Assert.AreEqual("Details", result.RouteValues["Action"]);
        }
Beispiel #17
0
        public void ConfirmRequestMovieShouldReturnRedirectToResult()
        {
            AdminController adminController = new AdminController();

            InsertRequest insertRequest = CreateInsertRequest(TestUtil.generateMovie());

            mocks.SetFakeControllerContext(adminController);

            FormCollection formCollection = new FormCollection();

            formCollection["Title"]         = "Title";
            formCollection["OriginalTitle"] = "OriginalTitle";
            formCollection["Genre"]         = "Action";
            formCollection["ReleaseDate"]   = "21.08.1984";

            adminController.ValueProvider = formCollection.ToValueProvider();

            RedirectToRouteResult result = adminController.ConfirmRequestMovie(insertRequest.Id, formCollection, principalAdmin) as RedirectToRouteResult;

            Assert.IsNotNull(result);
            Assert.AreEqual(mediaRequests_ViewName, result.RouteValues["action"]);
        }
Beispiel #18
0
        public void ModelState_gets_retrylimitexceeded_exception()
        {
            var _mockDb = new Mock <ISchoolContext>();

            _mockDb.Setup(x => x.SaveChanges()).Throws <RetryLimitExceededException>();

            // Add 1 Enrollment
            var enrollment = new Enrollment()
            {
                EnrollmentID = 1,
                Student      = new Student()
                {
                    ID           = 1,
                    FirstMidName = "Carson",
                    LastName     = "Alexander"
                },
                Grade = Grade.A
            };

            _mockDb.Setup(x => x.Enrollments.Find(It.IsAny <int>()))
            .Returns(() => enrollment);

            var controller = new GradebookController(_mockDb.Object);

            controller.ControllerContext = new ControllerContext();
            // Update Enrollment Grade to a B
            var form = new FormCollection()
            {
                { "Grade", "B" },
            };

            controller.ValueProvider = form.ToValueProvider();

            controller.EditPost(1);

            Assert.Equal(
                "Unable to save changes. Try again, and if the problem persists, see your system administrator.",
                controller.ModelState[""].Errors[0].ErrorMessage);
        }
Beispiel #19
0
 public ActionResult Create(FormCollection form)
 {
     try
     {
         if (ModelState.IsValid)
         {
             TipoProduto TipoProduto = new TipoProduto();
             Produto     produto     = new Produto()
             {
                 Empresa = empresa, TipoProduto = TipoProduto
             };
             TryUpdateModel(produto, form.ToValueProvider());
             produto.TipoProduto = gerenciador.ObterTipoProduto(produto.TipoProduto.Id);
             gerenciador.Adicionar(produto);
             return(RedirectToAction("Index"));
         }
     }
     catch
     {
     }
     return(View());
 }
Beispiel #20
0
 public ActionResult Edit(FormCollection collection)
 {
     try
     {
         if (ModelState.IsValid)
         {
             Usuario usuario = new Usuario();
             TryUpdateModel <Usuario>(usuario, collection.ToValueProvider());
             gerenciador.Editar(usuario);
             return(RedirectToAction("ListagemUsuarios"));
         }
         return(View());
     }
     catch (NegocioException n)
     {
         throw new ControllerException("Erro ao tentar alterar as informações do objeto.", n);
     }
     catch (Exception e)
     {
         throw new ControllerException("Erro ao tentar alterar as informações do objeto.", e);
     }
 }
Beispiel #21
0
        public void ConfirmRequestTVShowShouldReturnNotFoundView_NoRequestFound()
        {
            AdminController adminController = new AdminController();

            mocks.SetFakeControllerContext(adminController);

            FormCollection formCollection = new FormCollection();

            formCollection["Title"]         = "Title";
            formCollection["OriginalTitle"] = "OriginalTitle";
            formCollection["Genre"]         = "Action";
            formCollection["Seasons"]       = "4";
            formCollection["ShowBeginning"] = "01.01.1904";
            formCollection["ShowEnding"]    = "06.07.1999";

            adminController.ValueProvider = formCollection.ToValueProvider();

            ViewResult result = adminController.ConfirmRequestTVShow(7, formCollection, principalAdmin) as ViewResult;

            Assert.IsNotNull(result);
            Assert.AreEqual(notFound_ViewName, result.ViewName);
        }
Beispiel #22
0
        public void ConfirmRequestMovieShouldReturnNotAuthorizedView()
        {
            AdminController adminController = new AdminController(membershipService, insertRequestService, mediaService);

            Expect.Call(membershipService.IsAdmin(fakeAdmin.Identity.Name)).Return(false);
            mocks.SetFakeControllerContext(adminController);
            mocks.ReplayAll();

            FormCollection formCollection = new FormCollection();

            formCollection["Title"]         = "Title";
            formCollection["OriginalTitle"] = "OriginalTitle";
            formCollection["Genre"]         = "Action";
            formCollection["ReleaseDate"]   = "21.08.1984";

            adminController.ValueProvider = formCollection.ToValueProvider();

            ViewResult result = adminController.ConfirmRequestMovie(7, formCollection, fakeAdmin) as ViewResult;

            Assert.IsNotNull(result);
            Assert.AreEqual(notAuthorized_ViewName, result.ViewName);
        }
Beispiel #23
0
 public ActionResult CheckOut(Cart cart, /*ShippingDetails spDetails*/ FormCollection form)
 {
     if (cart.Lines.Count == 0)
     {
         ModelState.AddModelError("Cart", "Ваша корзина пуста");
         return(View());
     }
     if (TryUpdateModel(cart.ShippingDetails, form.ToValueProvider()))
     {
         _orderSubmitter.SumbitterOrder(cart);
         cart.Clear();
         return(View("Comleted"));
     }
     else
     {
         return(View());
     }
     //if (!ModelState.IsValid)
     //    RedirectToAction("CheckOut");
     //_dataManager.Order.CreateOrder(cart, spDetails);
     //return View("Comleted");
 }
Beispiel #24
0
        public ActionResult Create(FormCollection collection)
        {
            var item = new Subscription();
            //please don't omit this...
            var whiteList = new[] { "FirstName", "LastName", "EMail" };

            this.UpdateModel(item, whiteList, collection.ToValueProvider());

            if (ModelState.IsValid)
            {
                try
                {
                    using (var session = this.dataStorage.NewSession())
                    {
                        if (session.Single <Subscription>(x => x.EMail.Equals(item.EMail, StringComparison.InvariantCultureIgnoreCase)) != null)
                        {
                            this.FlashWarning("Subscription already exists for e-mail address");
                            return(this.View());
                        }

                        session.Add(item);
                        session.CommitChanges();

                        this.userActivityLogger.LogIt("webuser", "Subscription Added: " + item);

                        this.FlashInfo("Subscription saved...");
                        return(RedirectToAction("Index", "Home"));
                    }
                }
                catch
                {
                    this.FlashError("There was an error adding this subscription");
                    return(View());
                }
            }

            return(View(item));
        }
Beispiel #25
0
        public void edit_post_valid_updates_model_returns_JSON()
        {
            //Arrange
            _serv = new Mock <IPersonService>();
            int            testid   = 4242;
            FormCollection fakeform = new FormCollection();

            fakeform.Add("ID", testid.ToString());
            fakeform.Add("firstname1", "blah");     //Every required field must be populated,
            fakeform.Add("lastname1", "UnitTest");  //or result will be null.
            fakeform.Add("gender", "47");
            Person fakeperson  = new Person();
            Person savedperson = new Person();
            string user        = "";

            _serv.Setup(p => p.Get(testid)).Returns(fakeperson);
            _serv.Setup(x => x.Save(It.IsAny <Person>(),
                                    It.IsAny <string>())
                        ).Callback((Person p, string str) =>
            {
                savedperson = p;
                user        = str;
            });
            var _ctrlr = new PersonController(_serv.Object, def.Object, map.Object);

            _ctrlr.SetFakeControllerContext();
            _ctrlr.ValueProvider = fakeform.ToValueProvider();
            //Act
            var result = _ctrlr.Edit(testid, "UnitTest") as JsonResult;
            //Assert
            IDictionary <string, object> data = new RouteValueDictionary(result.Data);

            Assert.AreEqual("OK", data["status"]);
            Assert.AreEqual(fakeperson, savedperson);
            Assert.AreEqual(savedperson.firstname1, "blah");
            Assert.AreEqual(savedperson.lastname1, "UnitTest");
            Assert.AreEqual(savedperson.gender, 47);
        }
Beispiel #26
0
        private void SaveRoles(Guid userId, FormCollection collection)
        {
            UsersInRole role;
            var         roles = from x in db.Roles select x;
            var         exist = (from x in db.UsersInRoles
                                 where x.UserId == userId
                                 select x.RoleId).AsEnumerable <Guid>();
            var provider = collection.ToValueProvider();
            var selected = from x in roles.AsEnumerable()
                           where (bool)provider.GetValue(x.RoleName).ConvertTo(typeof(bool))
                           select x.RoleId;
            var forAdd = selected.Except(exist);
            var forDel = exist.Except(selected);

            using (IEnumerator <Guid> enumerator = forDel.GetEnumerator())
            {
                Guid guid;
                while (enumerator.MoveNext())
                {
                    guid = enumerator.Current;
                    role = (from x in db.UsersInRoles
                            where (x.UserId == userId) && (x.RoleId == guid)
                            select x).First();
                    db.UsersInRoles.DeleteOnSubmit(role);
                }
            }
            foreach (Guid guid in forAdd)
            {
                var usersInRole = new UsersInRole
                {
                    RoleId = guid,
                    UserId = userId
                };

                db.UsersInRoles.InsertOnSubmit(usersInRole);
            }
            db.SubmitChanges();
        }
Beispiel #27
0
 public ActionResult AlterarDados(FormCollection collection)
 {
     try
     {
         if (ModelState.IsValid)
         {
             Empresa empresa = new Empresa();
             TryUpdateModel <Empresa>(empresa, collection.ToValueProvider());
             SessionHelper.Set(SessionKeys.Pessoa, empresa);
             gerenciador.Editar(empresa);
             return(RedirectToAction("Index"));
         }
         return(View());
     }
     catch (NegocioException n)
     {
         throw new ControllerException("Erro ao tentar alterar as informações do objeto.", n);
     }
     catch (Exception e)
     {
         throw new ControllerException("Erro ao tentar alterar as informações do objeto.", e);
     }
 }
Beispiel #28
0
        public void When_interceptor_specified_Intercepts_validation_provides_custom_errors()
        {
            var form = new FormCollection {
                { "Email", "foo" },
                { "Surname", "foo" },
                { "Forename", "foo" },
            };

            var context = new ModelBindingContext {
                ModelName             = "test",
                ModelMetadata         = CreateMetaData(typeof(PropertiesTestModel)),
                ModelState            = new ModelStateDictionary(),
                FallbackToEmptyPrefix = true,
                ValueProvider         = form.ToValueProvider(),
            };
            var binder = new CustomizeValidatorAttribute {
                Interceptor = typeof(ClearErrorsInterceptor)
            };

            binder.BindModel(controllerContext, context);

            context.ModelState.IsValid.ShouldBeTrue();
        }