// Useful utility method private Customer CreateFakeExistingCustomer(EntityManager entityManager, string companyName = "Existing Customer") { var customer = new Customer(); customer.CompanyName = companyName; customer.CustomerID = Guid.NewGuid(); entityManager.AttachEntity(customer); return customer; }
public async Task SaveModifiedEntity() { var entityManager = await TestFns.NewEm(_northwindServiceName); // Create a new customer var customer = new Customer { CustomerID = Guid.NewGuid() }; entityManager.AddEntity(customer); customer.CompanyName = "Test2A " + DateTime.Now.ToString(); Assert.IsTrue(customer.EntityAspect.EntityState == EntityState.Added, "State of new entity should be Added"); try { var saveResult = await entityManager.SaveChanges(); var savedEntity = saveResult.Entities[0]; Assert.IsTrue(savedEntity is Customer && savedEntity == customer, "After save, added entity should still exist"); Assert.IsTrue(customer.EntityAspect.EntityState == EntityState.Unchanged, "State of saved entity should be Unchanged"); // Modify customer customer.CompanyName = "Test2M " + DateTime.Now.ToString(); Assert.IsTrue(customer.EntityAspect.EntityState == EntityState.Modified, "State of modified entity should be Modified"); saveResult = await entityManager.SaveChanges(); savedEntity = saveResult.Entities[0]; Assert.IsTrue(savedEntity is Customer && savedEntity == customer, "After save, modified entity should still exist"); Assert.IsTrue(customer.EntityAspect.EntityState == EntityState.Unchanged, "State of saved entity should be Unchanged"); } catch (Exception e) { var message = string.Format("Save of customer {0} should have succeeded; Received {1}: {2}", customer.CompanyName, e.GetType().Name, e.Message); Assert.Fail(message); } }
public ActionResult Create(Customer customer) { if (ModelState.IsValid) { db.Customers.Add(customer); db.SaveChanges(); return RedirectToAction("Index"); } return View(customer); }
public static int InsertCustomer(Customer customer) { var affectedRows = 0; using (var db = new NorthwindEntities()) { db.Customers.Add(customer); affectedRows = db.SaveChanges(); } return affectedRows; }
private static void TestInsertMethod() { var customer = new Customer() { CustomerID = "TEST", CompanyName = "UNKNOWN", ContactName = "UNNAMED", ContactTitle = "NO-TITLE" }; var affectedRows = DataAccessObjectsClass.InsertCustomer(customer); Console.WriteLine("\rInsert -> ({0} affected row(s))", affectedRows); }
public async Task DoesValidateOnAttachByDefault() { var manager = new EntityManager(_serviceName); // new empty EntityManager await manager.FetchMetadata(); // required before creating a new entity var customer = new Customer(); var validationErrors = customer.EntityAspect.ValidationErrors; Assert.IsFalse(validationErrors.Any(), "Should be no validation errors before attach."); // attach triggers entity validation by default manager.AttachEntity(customer); Assert.IsTrue(validationErrors.Any(ve => ve.Message.Contains("CompanyName") && ve.Message.Contains("required")), "Should be a validation error stating CompanyName is required."); }
public async Task DoesNotValidateOnAttachWhenOptionIsOff() { var manager = new EntityManager(_serviceName); // new empty EntityManager await manager.FetchMetadata(); // required before creating a new entity // change the default options, turning off "OnAttach" var valOpts = new ValidationOptions { ValidationApplicability = ValidationApplicability.OnPropertyChange | ValidationApplicability.OnSave }; // reset manager's options manager.ValidationOptions = valOpts; var customer = new Customer(); manager.AttachEntity(customer); var validationErrors = customer.EntityAspect.ValidationErrors; Assert.IsFalse(validationErrors.Any(), "Should be no validation errors even though CompanyName is required."); }
public async Task SaveNewEntity() { var entityManager = await TestFns.NewEm(_northwindServiceName); // Create a new customer var customer = new Customer(); customer.CustomerID = Guid.NewGuid(); customer.CompanyName ="Test1 " + DateTime.Now.ToString(); entityManager.AddEntity(customer); Assert.IsTrue(customer.EntityAspect.EntityState == EntityState.Added, "State of new entity should be Added"); try { var saveResult = await entityManager.SaveChanges(); Assert.IsTrue(customer.EntityAspect.EntityState == EntityState.Unchanged, "State of saved entity should be Unchanged"); } catch (Exception e) { var message = "Server should not have rejected save of Customer entity with the error " + e.Message; Assert.Fail(message); } }
public async Task CreatingEntities() { var manager = new EntityManager(_serviceName); // Metadata must be fetched before CreateEntity() can be called await manager.FetchMetadata(); //Snippet1 var newCustomer = new Customer(); // rarely done in Breeze //Snippet2 // Order uses an auto-generated key value var order = manager.CreateEntity<Order>(); //Snippet3 // If the key is not auto generated, it must be initialized by CreateEntity() var alpha = manager.CreateEntity<Customer>(new { CustomerID = Guid.NewGuid(), CompanyName = "Alpha" }); //Snippet4 // Unattached new customer so you can keep configuring it and add/attach it later // Key value initializer not required because new entity is not attached to entity manager var beta = manager.CreateEntity<Customer>(new { CompanyName = "Beta" }, EntityState.Detached); // Attached customer, as if retrieved from the database // Note that the key must be initialized when new entity will be in an attached state var gamma = manager.CreateEntity<Customer>(new { CustomerID = Guid.NewGuid(), CompanyName = "Gamma" }, EntityState.Unchanged); //Snippet5 // Only need to do this once var metadataStore = manager.MetadataStore; // The model metadata known to this EntityManager instance var customerType = metadataStore.GetEntityType(typeof(Customer)); // Metadata about the Customer type // Do this for each customer to be created var acme = customerType.CreateEntity() as Customer; // Returns Customer as IEntity acme.CompanyName = "Acme"; // CompanyName is a required field acme.CustomerID = Guid.NewGuid(); // Must set the key field before attaching to entity manager manager.AddEntity(acme); // Attach the entity as a new entity; it's EntityState is "Added" }
public static int InsertCustomer( string customerID, string companyName, string contactName = null, string city = null, string contactTitle = null, string address = null, string region = null, string postalCode = null, string country = null, string phone = null, string fax = null) { var newCustomer = new Customer { CustomerID = customerID, CompanyName = companyName, City = city, ContactName = contactName, ContactTitle = contactTitle, Address = address, Region = region, PostalCode = postalCode, Country = country, Phone = phone, Fax = fax, }; using (var dbContext = new NorthwindEntities()) { dbContext.Customers.Add(newCustomer); int affectedRows = dbContext.SaveChanges(); return affectedRows; } }
public async Task CustomizeMessageString() { var manager = new EntityManager(_serviceName); // new empty EntityManager await manager.FetchMetadata(); // required before creating a new entity var customer = new Customer(); var vr = new RequiredValidator().WithMessage("Dude! The {0} is really required ... seriously ... as in mandatory"); var companyNameProp = customer.EntityAspect.EntityType.GetDataProperty("CompanyName"); var context = new ValidationContext(customer, companyNameProp, null); var error = vr.Validate(context); Assert.IsTrue(error.Message.Contains("CompanyName") && error.Message.Contains("Dude"), "should be an error containing 'Dude'"); }
public async Task AddRemoveValidationError() { var manager = new EntityManager(_serviceName); // new empty EntityManager await manager.FetchMetadata(); // required before creating a new entity var customer = new Customer { CompanyName = "Presumed Guilty"}; manager.AttachEntity(customer); var errmsgs = customer.EntityAspect.ValidationErrors; Assert.IsFalse(errmsgs.Any(), "should have no errors at start"); // create a fake error var fakeError = new ValidationError( new AlwaysWrongValidator(), // the marker validator new ValidationContext(customer),// validation context "You were wrong this time!" // error message ); // add the fake error errmsgs.Add(fakeError); Assert.IsTrue(errmsgs.Any(), String.Format("should have 1 error after add: {0}", errmsgs.First().Message)); // Now remove that error errmsgs.Remove(fakeError); customer.EntityAspect.Validate(); // re-validate Assert.IsFalse(errmsgs.Any(), "should have no errors after remove"); }
public async Task RemoveRuleAndError() { var manager = new EntityManager(_serviceName); // new empty EntityManager await manager.FetchMetadata(); // required before creating a new entity var customerType = manager.MetadataStore.GetEntityType(typeof(Customer)); //get the Customer type var alwaysWrongValidator = new AlwaysWrongValidator(); var validators = customerType.Validators; try { // add alwaysWrong to the entity (not to a property) validators.Add(alwaysWrongValidator); var customer = new Customer { CompanyName = "Presumed Guilty"}; // Attach triggers entity validation by default manager.AttachEntity(customer); var errmsgs = customer.EntityAspect.ValidationErrors; Assert.IsTrue(errmsgs.Any(), String.Format("should have 1 error: {0}", errmsgs.First().Message)); // remove validation rule Assert.IsTrue(validators.Remove(alwaysWrongValidator)); // Clear out the "alwaysWrong" error // Must do manually because that rule is now gone // and, therefore, can't cleanup after itself customer.EntityAspect.ValidationErrors.RemoveKey(ValidationError.GetKey(alwaysWrongValidator)); customer.EntityAspect.Validate(); // re-validate Assert.IsFalse(errmsgs.Any(), "should have no errors"); } finally { validators.Remove(alwaysWrongValidator); } }
public async Task USCustomerMustHaveValidZipCode() { var manager = new EntityManager(_serviceName); // new empty EntityManager await manager.FetchMetadata(); // required before creating a new entity var customerType = manager.MetadataStore.GetEntityType(typeof(Customer)); //get the Customer type try { // add US zip code validator to the entity (not to a property) customerType.Validators.Add(new ZipCodeValidator()); var customer = new Customer { CustomerID = Guid.NewGuid(), CompanyName = "Boogaloo Board Games" }; customer.Country = "USA"; customer.PostalCode = "N2L 3G1"; // a Canadian postal code manager.AddEntity(customer); // force validation of customer var errors = customer.EntityAspect.Validate(); Assert.IsTrue(errors.Any(), String.Format("should have 1 error: {0}", errors.First().Message)); customer.Country = "Canada"; errors = customer.EntityAspect.Validate(); Assert.IsFalse(errors.Any(), String.Format("should have no errors")); } finally { Assert.IsTrue(customerType.Validators.Remove(new ZipCodeValidator())); } }
public async Task AddRequiredValidator() { var manager = new EntityManager(_serviceName); // new empty EntityManager await manager.FetchMetadata(); // required before creating a new entity // Add required validator to the Country property of a Customer entity var customerType = manager.MetadataStore.GetEntityType(typeof(Customer)); //get the Customer type var countryProp = customerType.GetProperty("Country"); //get the property definition to validate var validators = countryProp.Validators; // get the property's validator collection Assert.IsFalse(validators.Any(v => v == new RequiredValidator()), "Should be no required validators on Customer.Country."); try { validators.Add(new RequiredValidator()); // add a new required validator instance Assert.IsTrue(validators.Any(), "Should now have a required validator on Customer.Country."); // create a new customer setting the required CompanyName var customer = new Customer { CompanyName = "zzz" }; var validationErrors = customer.EntityAspect.ValidationErrors; Assert.IsFalse(validationErrors.Any(), "Should be no validation errors prior to attach"); // attach triggers entity validation by default manager.AttachEntity(customer); // customer is no longer valid since Country was never set Assert.IsTrue(validationErrors.Any(ve => ve.Message.Contains("Country") && ve.Message.Contains("required")), "Should be a validation error stating Country is required."); } finally { Assert.IsTrue(validators.Remove(new RequiredValidator())); } }
public void AddCustomer(Customer customer) { context.Customers.Add(customer); context.SaveChanges(); }
public async Task ManualValidationAndClearingOfErrors() { var manager = new EntityManager(_serviceName); // new empty EntityManager await manager.FetchMetadata(); // required before creating a new entity var newCustomer = new Customer(); // attach triggers entity validation by default manager.AttachEntity(newCustomer); // validate an individual entity at any time var results = newCustomer.EntityAspect.Validate(); if (results.Any()) {/* do something about errors */} Assert.IsTrue(results.Any(ve => ve.Message.Contains("CompanyName") && ve.Message.Contains("required")), "Should be a validation error stating CompanyName is required."); // remove all current errors from the collection newCustomer.EntityAspect.ValidationErrors.Clear(); Assert.IsFalse(newCustomer.EntityAspect.ValidationErrors.Any(), "Should be no validation errors after clearing them."); // validate a specific property at any time var dp = newCustomer.EntityAspect.EntityType.GetDataProperty("CompanyName"); results = newCustomer.EntityAspect.ValidateProperty(dp); if (results.Any()) { /* do something about errors */} Assert.IsTrue(results.Any(ve => ve.Message.Contains("CompanyName") && ve.Message.Contains("required")), "Should be a validation error stating CompanyName is required."); // remove a specific error var specificError = results.First(ve => ve.Context.PropertyPath == "CompanyName"); newCustomer.EntityAspect.ValidationErrors.Remove(specificError); Assert.IsFalse(newCustomer.EntityAspect.ValidationErrors.Any(), "Should be no validation errors after clearing a specific one."); // clear server errors var errors = newCustomer.EntityAspect.ValidationErrors; errors.ForEach(ve => { if (ve.IsServerError) errors.Remove(ve); }); }
public async Task CustomerCanBeInCanada() { var manager = new EntityManager(_serviceName); // new empty EntityManager await manager.FetchMetadata(); // required before creating a new entity var customer = new Customer {CompanyName="zzz", ContactName = "Wayne Gretzky", Country = "Canada"}; // force validation of unattached customer var errors = customer.EntityAspect.Validate(); // Ok for customer to be in Canada Assert.IsFalse(errors.Any(), "Should be no validation errors."); }
public ActionResult Edit(Customer customer) { if (ModelState.IsValid) { db.Entry(customer).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("Index"); } return View(customer); }
public async Task CustomerMustBeInUs() { var manager = new EntityManager(_serviceName); // new empty EntityManager await manager.FetchMetadata(); // required before creating a new entity var customer = new Customer { CompanyName = "zzz", ContactName = "Shania Twain" }; manager.AttachEntity(customer); try { // add the US-only validator customer.EntityAspect.EntityType.GetProperty("Country") .Validators.Add(new CountryIsUsValidator()); // non-US customers no longer allowed customer.Country = "CA"; var validationErrors = customer.EntityAspect.ValidationErrors; Assert.IsTrue(validationErrors.Any(ve => ve.Message.Contains("Country must start with 'US'")), "Should be a validation error stating Country must start with 'US'."); // back in the USA customer.Country = "USA"; Assert.IsFalse(validationErrors.Any(), "Should be no validation errors."); } finally { Assert.IsTrue(customer.EntityAspect.EntityType.GetProperty("Country") .Validators.Remove(new CountryIsUsValidator())); } }