public async Task Null_or_empty_or_whitespace_ETags_are_not_saved_in_the_snapshot() { var account = new CustomerAccount() .Apply(new RequestSpam { ETag = "" }) .Apply(new RequestSpam { ETag = " " }) .Apply(new RequestSpam { ETag = null }); var repository = new InMemorySnapshotRepository(); await repository.SaveSnapshot(account); var snapshot = await repository.GetSnapshot(account.Id); snapshot.ETags .Should() .BeEmpty(); }
public void TestGetCustomerAccountByNumber() { string accountNumber = "000111222"; try { var customerAccount = new CustomerAccount() { ID = Guid.NewGuid().ToString(), AccountName = accountNumber, Owner = "aaron", RatePlan = 1, AccountCode = "AC" + accountNumber, AccountNumber = accountNumber, Inserted = DateTime.UtcNow.ToString("o") }; using (var db = new SIPSorceryEntities()) { db.CustomerAccounts.AddObject(customerAccount); db.SaveChanges(); } CustomerAccountDataLayer customerAccountDataLayer = new CustomerAccountDataLayer(); var checkCustomerAccount = customerAccountDataLayer.Get("aaron", accountNumber); Assert.IsNotNull(checkCustomerAccount); Assert.AreEqual(customerAccount.ID, checkCustomerAccount.ID); } finally { TestHelper.ExecuteQuery("delete from customeraccount where accountnumber = '" + accountNumber + "'"); } }
public void Reserving_a_unique_value_can_happen_during_command_validation() { // arrange var name = Any.CamelCaseName(); var firstCall = true; Configuration.Current.ReservationService = new FakeReservationService((value, scope, actor) => { if (firstCall) { firstCall = false; return true; } return false; }); // act var account1 = new CustomerAccount(); account1.Apply(new RequestUserName { UserName = name }); account1.ConfirmSave(); var account2 = new CustomerAccount(); var secondAttempt = account2.Validate(new RequestUserName { UserName = name }); // assert secondAttempt.ShouldBeInvalid(string.Format("The user name {0} is taken. Please choose another.", name)); }
public static CustomerAccount CreateCustomer(CustomerAccount customerAccount) { if (CustomerAccounts.Any(o => o.Email == customerAccount.Email)) throw new Exception($"Customer with a Email address of '{customerAccount.Email}' already exists."); customerAccount.DateCreated = DateTime.UtcNow; CustomerAccounts.Add(customerAccount); return customerAccount; }
public void When_no_authorization_rules_have_been_configured_for_a_given_command_then_checks_are_unauthorized() { var customer = new Customer(); var account = new CustomerAccount(); var addEmail = new ChangeEmailAddress(); customer.IsAuthorizedTo(addEmail, account) .Should().Be(false); }
public void CustomerAccountHasLateFeesSpecification_Should_Not_Be_Satisfied_By_A_Customer_With_Late_Fees_When_Used_With_A_NotSpecification() { CustomerAccount customerWithLateFess = new CustomerAccount() { LateFees = 100 }; ISpecification <CustomerAccount> specification = new CustomerAccountHasLateFeesSpecification(); Assert.IsFalse(specification.Not().IsSatisfiedBy(customerWithLateFess)); }
public void CustomerAccountHasLateFeesSpecification_Should_Not_Be_Satisfied_By_A_Customer_With_Zero_Late_Fees() { CustomerAccount customerWithNoLateFess = new CustomerAccount() { LateFees = 0 }; CustomerAccountHasLateFeesSpecification specification = new CustomerAccountHasLateFeesSpecification(); Assert.IsFalse(specification.IsSatisfiedBy(customerWithNoLateFess)); }
public void HasReachedRentalThresholdSpecification_Should_NoBe_Satistfied_By_A_Customer_Who_Has_Made_Less_Than_5_Rentals_This_Month() { CustomerAccount customerWith5RentalsThisMonth = new CustomerAccount() { NumberOfRentalsThisMonth = 1 }; HasReachedRentalThresholdSpecification specification = new HasReachedRentalThresholdSpecification(); Assert.IsFalse(specification.IsSatisfiedBy(customerWith5RentalsThisMonth)); }
private static void AddContractsToInvoice(Invoice invoice, CustomerAccountInvoiceItem invoiceItem, CustomerAccount activeContract) { if (activeContract.WasActiveOn(invoice.BillCycle.Date)) { var contractsForBilling = activeContract.GetListOfContractsToBill(invoice.BillCycle).ToList(); //TODO Review. invoiceItem.AttachedContractItems.AddRange( //contractsForBilling.Select(c => c.PopulateInvoiceAttachedContractItems()).ToList()); contractsForBilling.ForEach(c => c.LastBilled = invoice.BillCycle); } }
private void ApplySales(UserSpecificPrice price, Product p, CustomerAccount currentUser, List <Promotion> sales) { if (sales == null) { return; } foreach (var promo in sales) { promo.ApplyToProduct(CurrentRequestContext, p, price, currentUser); } }
public void CustomerAccountStillActiveSpecification_Should_Not_Be_Satisfied_By_An_Active_Customer_When_Used_With_A_NotSpecification() { CustomerAccount customerActive = new CustomerAccount() { AccountActive = true }; ISpecification <CustomerAccount> specification = new CustomerAccountStillActiveSpecification(); Assert.IsFalse(specification.Not().IsSatisfiedBy(customerActive)); }
public void ComputeReducingRepayment(CustomerAccount act, double nyears, double interestRate) { double rate = (interestRate) / 100; double x = 1 - Math.Pow((1 + rate), -(nyears * 12)); act.LoanMonthlyRepay = ((decimal)act.LoanAmount * (decimal)rate) / (decimal)x; act.LoanPrincipalRemaining = (decimal)act.LoanAmount; act.LoanMonthlyInterestRepay = (decimal)rate * act.LoanPrincipalRemaining; act.LoanMonthlyPrincipalRepay = act.LoanMonthlyRepay - act.LoanMonthlyInterestRepay; }
public IHttpActionResult GetCustomerAccount(Guid id) { CustomerAccount customerAccount = db.CustomerAccounts.Find(id); if (customerAccount == null) { return(NotFound()); } return(Ok(customerAccount)); }
private List <RoleInfo> GetCustomerRoles(CustomerAccount customer) { var user = DnnUserController.Instance.GetUser(_portalId, Convert.ToInt32(customer.Bvin)); var roles = RoleController.Instance.GetUserRoles(user, true); var activeroles = from role in roles where role.ExpiryDate != DateTime.MinValue && role.ExpiryDate > DateTime.Now select role; return(activeroles.OfType <RoleInfo>().ToList()); }
public void CustomerAccountStillActiveSpecification_Should_Be_Satisfied_By_An_Active_Customer() { CustomerAccount customerActive = new CustomerAccount() { AccountActive = true }; CustomerAccountStillActiveSpecification specification = new CustomerAccountStillActiveSpecification(); Assert.IsTrue(specification.IsSatisfiedBy(customerActive)); }
public void CustomerAccountStillActiveSpecification_Should_Not_Be_Satisfied_By_A_Customer_Who_Is_Not_Active() { CustomerAccount customerNotActive = new CustomerAccount() { AccountActive = false }; CustomerAccountStillActiveSpecification specification = new CustomerAccountStillActiveSpecification(); Assert.IsFalse(specification.IsSatisfiedBy(customerNotActive)); }
public ActionResult Details(int Id) { CustomerAccount account = new CustomerAccount(); account = actRepo.GetById(Id); if (account == null) { return(new HttpStatusCodeResult(HttpStatusCode.NotFound)); } return(PartialView("_Details", account)); }
public static async Task <bool> IsRewardsAssigned(this CustomerAccount customerAccount, IApiContext apiContext) { var attributeResource = new AttributeResource(apiContext); var attribute = await attributeResource.GetAttributeAsync(AttributeConstants.RewardsAssigned); var customerAttributeResource = new CustomerAttributeResource(apiContext); var attributeCustomer = await customerAttributeResource.GetAccountAttributeAsync(customerAccount.Id, attribute.AttributeFQN); return(attributeCustomer != null && attributeCustomer.Values.Any(a => a.Equals(true))); }
public CustomerAccount Create(DbDataReader reader) { CustomerAccount entity = null; while (reader.Read()) { entity = Read(reader); } return(entity); }
public ActionResult Edit([Bind(Include = "ID,AccountNumber,AccountName,BranchID,AccountBalance,DateCreated,DaysCount,dailyInterestAccrued,LoanInterestRatePerMonth,AccountType,AccountStatus,SavingsWithdrawalCount,CurrentLien,CustomerID,LoanAmount,LoanMonthlyRepay,LoanMonthlyInterestRepay,LoanMonthlyPrincipalRepay,LoanPrincipalRemaining,TermsOfLoan,ServicingAccountID")] CustomerAccount customerAccount) { if (ModelState.IsValid) { db.Entry(customerAccount).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.BranchID = new SelectList(db.Branches, "ID", "Name", customerAccount.BranchID); return(View(customerAccount)); }
public async Task StartAsync(IDialogContext context) { //This is a test so I am filling up CustomerAccount data here CustomerAccount ca = new CustomerAccount(); ca.FirstName = "Oyen"; ca.Email = "*****@*****.**"; context.UserData.SetValue <CustomerAccount>("CustomerAccount", ca); context.Wait(this.MessageReceivedAsync); }
public async Task When_instantiated_from_a_snapshot_the_aggregate_version_is_correct() { var customerAccount = new CustomerAccount(new CustomerAccountSnapshot { AggregateId = Any.Guid(), EmailAddress = Any.Email(), Version = 12 }); customerAccount.Version.Should().Be(12); }
}//end method public void ComputeFixedRepayment(CustomerAccount act, double nyears, double interestRate) { decimal totalAmountToRepay = 0; double nMonth = nyears * 12; double totalInterest = (interestRate) / 100 * nMonth * (double)act.LoanAmount; totalAmountToRepay = (decimal)totalInterest + (decimal)act.LoanAmount; act.LoanMonthlyRepay = (totalAmountToRepay / (12 * (decimal)nyears)); act.LoanMonthlyPrincipalRepay = Convert.ToDecimal((double)act.LoanAmount / nMonth); act.LoanMonthlyInterestRepay = Convert.ToDecimal(totalInterest / nMonth); act.LoanPrincipalRemaining = (decimal)act.LoanAmount; }
public void GivenExistingAccount_WhenDepositMoneyToAccount_ThenAccountBalanceShouldBeEqualMoneyDeposited() { //arrange int accountId = 1; var account = new CustomerAccount(accountId); int moneyToDeposit = 100; //act account.Deposit(moneyToDeposit); //assert Assert.AreEqual(account.Balance, moneyToDeposit); }
public ActionResult Delete(string id) { CustomerAccount u = MTApp.CurrentCustomer; if (u != null) { u.DeleteAddress(id); MTApp.MembershipServices.UpdateCustomer(u); } return(RedirectToAction("Index")); }
public bool AddNewCustomerAccount(CustomerAccount model) { Execute("InsertNewCustomerAccount", new { ClientCustRef = model.ClientCustRef, Email = model.Email, Password = model.Password, ClientID = model.ClientId, EnroleCode = model.EnrolmentCode }, CommandType.StoredProcedure); return(true); }
public void SavedAccountComaparison() { AccountList accList = new AccountList(false); CustomerAccount bobAccount = new CustomerAccount(1, 38.50m, 1, "Bob", "password", "Bob Shanks", false); accList.AddCustomerAccount(bobAccount); accList.SaveCustomerData(); accList.LoadCustomerData(); var newAcc = accList.GetAccountById(bobAccount.GetAccountId()); Assert.IsTrue(bobAccount.ToString() == newAcc.ToString()); }
public async Task <CustomerAccount> GetCustomerByCustomerNo(string customerNo) { CustomerAccount customer = null; if (customerNo == null) { return(customer); } customer = await _repository.GetCustomerByCustomerNo(customerNo); return(customer); }
public async Task When_an_aggregate_has_pending_events_then_creating_a_snapshot_throws() { var account = new CustomerAccount().Apply(new RequestSpam()); await Configuration.Current.Repository<CustomerAccount>().Save(account); await account.ApplyAsync(new NotifyOrderCanceled()); var repository = Configuration.Current.SnapshotRepository(); Action save = () => repository.SaveSnapshot(account).Wait(); save.ShouldThrow<InvalidOperationException>() .WithMessage("A snapshot can only be created from an aggregate having no pending events. Save the aggregate before creating a snapshot."); }
public CustomerAccount Add(CustomerAccount item) { this.SetBaseFields((BaseModel)item); using (SqlConnection connection = GetConnection()) { var id = connection.Insert(item); var returnObject = connection.Get <CustomerAccount>(id); return(returnObject); } }
static async Task <bool> CheckBooleanAttributeIsSet(CustomerAccount customerAccount, IApiContext apiContext, string attributeName) { var attributeResource = new AttributeResource(apiContext); var attribute = await attributeResource.GetAttributeAsync(attributeName); attribute.AttributeFQN = attribute.AttributeFQN.ToLower(); var customerAttributeResource = new CustomerAttributeResource(apiContext); var attributeCustomer = await customerAttributeResource.GetAccountAttributeAsync(customerAccount.Id, attribute.AttributeFQN); return(attributeCustomer != null && attributeCustomer.Values.Any(a => a.Equals(true))); }
public CustomerAccount Update(CustomerAccount item) { this.SetBaseFields((BaseModel)item); using (SqlConnection connection = GetConnection()) { connection.Update(item); var returnObject = connection.Get <CustomerAccount>(item.CustomerId); return(returnObject); } }
protected void btnSubmit_Click(object sender, System.Web.UI.ImageClickEventArgs e) { this.MessageBox1.ClearMessage(); if (this.ValidateSelections() == true) { if (o != null) { SaveInfoToOrder(true); //we can't put this in "SaveInfoToOrder" because //that is called multiple times on the page OrderNote note = new OrderNote(); note.Note = InstructionsField.Text; note.IsPublic = false; o.Notes.Add(note); MTApp.OrderServices.Orders.Update(o); // Save as Order MerchantTribe.Commerce.BusinessRules.OrderTaskContext c = new MerchantTribe.Commerce.BusinessRules.OrderTaskContext(MTApp); c.UserId = string.Empty; // Use currently selected user for process new order context CustomerAccount u = GetSelectedUserAccount(); if (u != null) { if (u.Bvin != string.Empty) { c.UserId = u.Bvin; o.UserID = u.Bvin; } } c.Order = o; if (MerchantTribe.Commerce.BusinessRules.Workflow.RunByName(c, MerchantTribe.Commerce.BusinessRules.WorkflowNames.ProcessNewOrder)) { Response.Redirect("ViewOrder.aspx?id=" + o.bvin); } else { // Show Errors string errorString = string.Empty; for (int i = 0; i <= c.Errors.Count - 1; i++) { errorString += c.Errors[i].Description + "<br />"; } if (errorString.Length > 0) { this.MessageBox1.ShowWarning(errorString); } } } } }
public ActionResult Edit(CustomerAccountViewModel model) { ViewData["Branches"] = context.Branches.ToList(); if (ModelState.IsValid) { CustomerAccount customerAccount = context.CustomerAccounts.Find(model.Id); customerAccount.Branch = context.Branches.Find(model.BranchID); context.SaveChanges(); return(RedirectToAction("Index")); } return(View(model)); }
public async Task Consume(ConsumeContext <AccountRegistered> context) { var customer = new CustomerAccount { FirstName = context.Message.FirstName, Surname = context.Message.Surname, Email = context.Message.Email, IsVerified = false }; await _repository.Add(customer, "customers"); }
public void A_Composite_Of_Two_Satisfied_Specifications_Should_Not_Be_Satisfied_When_Used_With_A_NotSpecification() { CustomerAccount customerActive = new CustomerAccount() { AccountActive = true, LateFees = 100 }; ISpecification <CustomerAccount> specificationActive = new CustomerAccountStillActiveSpecification(); ISpecification <CustomerAccount> specificationLateFees = new CustomerAccountHasLateFeesSpecification(); Assert.IsFalse(specificationActive.And(specificationLateFees).Not().IsSatisfiedBy(customerActive)); }
public async Task ETags_are_saved_in_the_snapshot() { var etag = Any.Guid().ToString(); var account = new CustomerAccount().Apply(new RequestSpam { ETag = etag }); await Configuration.Current.Repository<CustomerAccount>().Save(account); var repository = Configuration.Current.SnapshotRepository(); await repository.SaveSnapshot(account); var snapshot = await repository.GetSnapshot(account.Id) as CustomerAccountSnapshot; snapshot.ETags.MayContain(etag).Should().BeTrue(); }
public async Task ETags_are_saved_in_the_snapshot() { var etag = Any.Guid().ToString(); var account = new CustomerAccount().Apply(new RequestSpam { ETag = etag }); account.ConfirmSave(); var repository = new InMemorySnapshotRepository(); await repository.SaveSnapshot(account); var snapshot = await repository.GetSnapshot(account.Id); snapshot.ETags .Should() .Contain(etag); }
public void IsDenied_overrides_other_authorizations() { AuthorizationFor<Customer>.ToApply<SuspendAccount>.ToA<CustomerAccount>.IsDenied(); AuthorizationFor<Customer>.ToApplyAnyCommand.ToA<CustomerAccount>.Requires((c1, c2) => c1.Id == c2.Id); Guid customerId = Guid.NewGuid(); var customerAccount = new CustomerAccount(customerId); var customerPrincipal = new Customer { Id = customerId, IsAuthenticated = true }; customerPrincipal.IsAuthorizedTo(new ChangeEmailAddress(), customerAccount) .Should().BeTrue(); customerPrincipal.IsAuthorizedTo(new SuspendAccount(), customerAccount) .Should().BeFalse(); }
public async Task A_scheduled_command_can_schedule_other_commands() { // ARRANGE var email = Any.Email(); Console.WriteLine(new { clockName, email }); var account = new CustomerAccount() .Apply(new ChangeEmailAddress(email)) .Apply(new SendMarketingEmailOn(Clock.Now().AddDays(1))) .Apply(new RequestSpam()); await accountRepository.Save(account); // ACT var result = await clockTrigger.AdvanceClock(clockName, TimeSpan.FromDays(10)); Console.WriteLine(result.ToLogString()); await SchedulerWorkComplete(); // ASSERT account = await accountRepository.GetLatest(account.Id); Console.WriteLine(account.Events() .Select(e => string.Format("{0}: {1}{2}\n", e.EventName(), e.Timestamp, e.IfTypeIs<IScheduledCommand<CustomerAccount>>() .Then(s => " --> DUE: " + s.DueTime) .ElseDefault())) .ToLogString()); account.Events() .OfType<CommandScheduled<CustomerAccount>>() .Count() .Should() .Be(3); account.Events() .Last() .Should() .BeOfType<CommandScheduled<CustomerAccount>>(); }
public async Task When_a_scheduled_command_fails_and_the_clock_is_advanced_again_then_it_can_be_retried() { // ARRANGE var account = new CustomerAccount() .Apply(new ChangeEmailAddress { NewEmailAddress = Any.Email() }); account .Apply(new SendMarketingEmailOn(Clock.Now().AddDays(5))) .Apply(new RequestNoSpam()); await accountRepository.Save(account); // ACT await clockTrigger.AdvanceClock(clockName, TimeSpan.FromDays(6)); account.CommunicationsSent.Count().Should().Be(0); // requesting spam will unblock the original scheduled command if it is re-attempted account = await accountRepository.GetLatest(account.Id); account.Apply(new RequestSpam()); await accountRepository.Save(account); await clockTrigger.AdvanceClock(clockName, TimeSpan.FromMinutes(1)); // ASSERT account = await accountRepository.GetLatest(account.Id); account.CommunicationsSent.Count().Should().Be(1); }
public void IsDenied_does_not_need_to_specify_a_resource_type_for_the_command() { AuthorizationFor<Customer>.ToApply<UnsuspendAccount>.IsDenied(); AuthorizationFor<Customer>.ToApplyAnyCommand.ToA<CustomerAccount>.Requires((c1, c2) => c1.Id == c2.Id); Guid customerId = Guid.NewGuid(); var customerAccount = new CustomerAccount(customerId); var customerPrincipal = new Customer { Id = customerId, IsAuthenticated = true }; customerPrincipal.IsAuthorizedTo(new ChangeEmailAddress(), customerAccount) .Should().BeTrue(); customerPrincipal.IsAuthorizedTo(new UnsuspendAccount(), customerAccount) .Should().BeFalse(); }
public void AddToCustomerAccounts(CustomerAccount customerAccount) { base.AddObject("CustomerAccounts", customerAccount); }
public async Task Attempting_to_re_source_an_aggregate_that_was_instantiated_using_a_snapshot_succeeds_if_the_specified_version_is_at_or_after_the_snapshot() { var originalEmail = Any.Email(); var customerAccount = new CustomerAccount(new CustomerAccountSnapshot { AggregateId = Any.Guid(), Version = 10, EmailAddress = originalEmail }); customerAccount.Apply(new ChangeEmailAddress(Any.Email())); var accountAtv10 = customerAccount.AsOfVersion(10); accountAtv10.Version.Should().Be(10); accountAtv10.EmailAddress.Should().Be(originalEmail); }
public override void Update(CustomerAccount aggregate) { aggregate.CommunicationsSent.Add(EmailSubject); }
public static CustomerAccount CreateCustomerAccount(int customerID, int primaryExpirationMonth, int primaryExpirationYear, int primaryCreditCardTypeID, int secondaryExpirationMonth, int secondaryExpirationYear, int secondaryCreditCardTypeID) { CustomerAccount customerAccount = new CustomerAccount(); customerAccount.CustomerID = customerID; customerAccount.PrimaryExpirationMonth = primaryExpirationMonth; customerAccount.PrimaryExpirationYear = primaryExpirationYear; customerAccount.PrimaryCreditCardTypeID = primaryCreditCardTypeID; customerAccount.SecondaryExpirationMonth = secondaryExpirationMonth; customerAccount.SecondaryExpirationYear = secondaryExpirationYear; customerAccount.SecondaryCreditCardTypeID = secondaryCreditCardTypeID; return customerAccount; }
public override void Update(CustomerAccount aggregate) { aggregate.CommunicationsSent.Add(string.Format("Your order has shipped! (Order #{0})", OrderNumber)); }
public async Task When_instantiated_from_a_snapshot_the_aggregate_version_is_correct() { var customerAccount = new CustomerAccount(new CustomerAccountSnapshot { AggregateId = Any.Guid(), EmailAddress = Any.Email(), Version = 12 }); customerAccount.Version.Should().Be(12); }
public async Task Accessing_event_history_from_an_aggregate_instantiated_using_a_snapshot_throws() { var customerAccount = new CustomerAccount(new CustomerAccountSnapshot { AggregateId = Any.Guid(), Version = 10, EmailAddress = Any.Email() }); Action getEvents = ()=> customerAccount.Events(); getEvents.ShouldThrow<InvalidOperationException>() .And .Message .Should() .Contain("Aggregate was sourced from a snapshot, so event history is unavailable."); }
public async Task Attempting_to_re_source_an_aggregate_that_was_instantiated_using_a_snapshot_throws_if_the_specified_version_is_prior_to_the_snapshot() { var originalEmail = Any.Email(); var customerAccount = new CustomerAccount(new CustomerAccountSnapshot { AggregateId = Any.Guid(), Version = 10, EmailAddress = originalEmail }); Action rollBack = () => customerAccount.AsOfVersion(9); rollBack.ShouldThrow<InvalidOperationException>() .And .Message .Should() .Contain("Snapshot version is later than specified version."); }
public async Task When_a_command_is_scheduled_but_an_exception_is_thrown_in_a_handler_then_an_error_is_recorded() { Configuration.Current.UseDependency(_ => new CustomerAccount.OrderEmailConfirmer { SendOrderConfirmationEmail = x => { throw new Exception("drat!"); } }); // create a customer account var customer = new CustomerAccount(Any.Guid()) .Apply(new ChangeEmailAddress(Any.Email())); await accountRepository.Save(customer); var order = new Order(new CreateOrder(Any.FullName()) { CustomerId = customer.Id }); await orderRepository.Save(order); // act order.Apply(new Cancel()); await orderRepository.Save(order); await clockTrigger.AdvanceClock(clockName, TimeSpan.FromMinutes(1.2)); using (var db = new CommandSchedulerDbContext()) { db.Errors .Where(e => e.ScheduledCommand.AggregateId == customer.Id) .Should() .Contain(e => e.Error.Contains("drat!")); } }
/// <summary> /// 创建客户账户 /// </summary> /// <param name="customerId"></param> /// <returns></returns> public ActionResult CreateCustomerAccount(int? customerId) { if (customerId == null) { throw new LogicalException(); } Customer customer = this.CustomerService.FindById(customerId.GetValueOrDefault()); if (customer == null) { throw new LogicalException(); } if (this.Request.IsPost()) { CustomerAccount customerAccount = new CustomerAccount() { Customer = customer }; TryUpdateModel(customerAccount, new[] { "AccountNumber" }); if (string.IsNullOrEmpty(customerAccount.AccountNumber)) { ModelState.AddModelError("AccountNumber", "账号不能为空"); } if (ModelState.IsValid) { this.CustomerService.SaveCustomerAccount(customerAccount); return View("CloseModalDialog"); } } return View("CustomerAccount/Create"); }
public async Task When_a_command_is_scheduled_but_the_event_that_triggered_it_was_not_successfully_written_then_the_command_is_not_applied() { VirtualClock.Start(); // create a customer account var customer = new CustomerAccount(Any.Guid()) .Apply(new ChangeEmailAddress(Any.Email())); await accountRepository.Save(customer); var order = new Order(new CreateOrder(Any.FullName()) { CustomerId = customer.Id }); // act // cancel the order but don't save it order.Apply(new Cancel()); // assert // verify that the customer did not receive the scheduled NotifyOrderCanceled command customer = await accountRepository.GetLatest(customer.Id); customer.Events().Last().Should().BeOfType<CustomerAccount.EmailAddressChanged>(); using (var db = new CommandSchedulerDbContext()) { db.ScheduledCommands .Where(c => c.AggregateId == customer.Id) .Should() .ContainSingle(c => c.AppliedTime == null && c.DueTime == null); } }
public async Task Repeated_ETags_are_not_repeated_in_the_snapshot() { var account = new CustomerAccount() .Apply(new RequestSpam { ETag = "a" }) .Apply(new RequestSpam { ETag = "a" }); account.ConfirmSave(); var repository = new InMemorySnapshotRepository(); await repository.SaveSnapshot(account); var snapshot = await repository.GetSnapshot(account.Id); snapshot.ETags .Should() .ContainSingle(etag => etag == "a"); }
public static CustomerAccount UpdateCustomer(long customerId, CustomerAccount customerAccount) { if (CustomerAccounts.All(o => o.CustomerId != customerId)) throw new Exception(ERR_MISSING_CUSTOMER.Fmt(customerId)); return CustomerAccounts.First(o => o.CustomerId == customerId).Update(customerAccount); }
public async Task An_aggregate_instantiated_from_a_snapshot_adds_new_events_at_the_correct_sequence_number() { var customerAccount = new CustomerAccount(new CustomerAccountSnapshot { AggregateId = Any.Guid(), EmailAddress = Any.Email(), Version = 12 }); customerAccount.Apply(new RequestNoSpam()); customerAccount.Version.Should().Be(13); customerAccount.PendingEvents.Last().SequenceNumber.Should().Be(13); }