public DomainAppService(DatabaseContext db, ILookupClientWrapper lookup, IWhoisClient whoisClient) { _lookup = lookup; _whoisClient = whoisClient; _db = db; _domainRepository = new DomainRepository(_db); }
public DomainController() { dbContext = new CaremeDBContext(); repo = new DomainRepository(dbContext); serviceRepo = new ServiceRepository(dbContext); procedureRepo = new ProcedureRepository(dbContext); }
public void WhenAddingEntity_ThenGetAndUpdate() { DatabaseTestUtility.DropCreateFirebrickDatabase(); // Arrange var repository = new DomainRepository(new DatabaseFactory()); Domain newEntity = DefaultModelHelper.DummyPopulatedDomain(); // Act repository.Add(newEntity); repository.Commit(); // Use a new context and repository to verify the vehicle was added var repositoryTwo = new DomainRepository(new DatabaseFactory()); Domain loadedEntity = repositoryTwo.GetById(1); loadedEntity.HostHeader = "NewHostHeader"; repositoryTwo.Update(loadedEntity); repositoryTwo.Commit(); // Use a new context and repository to verify the vehicle was added var repositoryThree = new DomainRepository(new DatabaseFactory()); newEntity = repositoryThree.GetById(1); Assert.NotNull(newEntity); Assert.Equal("NewHostHeader", newEntity.HostHeader); }
public void ShouldModifyTheQueryInExpressionToHaveAnAdditionalWhere() { //Arrange var domain = new TestDomain(); var interceptor = new AppendWhere <Foo>(1, foo => foo.Name == "Test", typeof(AllFoos)); domain.Events = new List <IInterceptor> { interceptor }; domain.ConnectionString = Settings.Default.Connection; //act var inMemoryDomainContext = new InMemoryDomainContext <TestDomain>(); inMemoryDomainContext.Add(new Foo() { Name = "Test" }); inMemoryDomainContext.Add(new Foo() { Name = "Should Not Show up" }); inMemoryDomainContext.Commit(); var repository = new DomainRepository <TestDomain>(inMemoryDomainContext, domain); var emptyQuery = new AllFoos(); var results = repository.Find(emptyQuery); //assert results.Count().Should().Be(1); }
public void Get_All_Ids() { int contentId = CreateTestData("en-AU", out ContentType ct); IScopeProvider provider = ScopeProvider; using (IScope scope = provider.CreateScope()) { DomainRepository repo = CreateRepository(provider); ILanguage lang = LanguageRepository.GetByIsoCode("en-AU"); IContent content = DocumentRepository.Get(contentId); var ids = new List <int>(); for (int i = 0; i < 10; i++) { var domain = (IDomain) new UmbracoDomain("test " + i + ".com") { RootContentId = content.Id, LanguageId = lang.Id }; repo.Save(domain); ids.Add(domain.Id); } IEnumerable <IDomain> all = repo.GetMany(ids.Take(8).ToArray()); Assert.AreEqual(8, all.Count()); } }
public void WhenIScheduleAMeeting() { var scheduleMeetingCommand = new ScheduleMeetingCommand(MEETING_ID, meetingDate, locationId, speakerId, capacity); new DomainDatabaseBootStrapper().ReCreateDatabaseSchema(); var sqliteConnectionString = string.Format("Data Source={0}", DATA_BASE_FILE); var domainEventStorage = new DomainEventStorage<IDomainEvent>(sqliteConnectionString, new BinaryFormatter()); var eventStoreIdentityMap = new EventStoreIdentityMap<IDomainEvent>(); var bus = new DirectBus(new MessageRouter()); var eventStoreUnitOfWork = new EventStoreUnitOfWork<IDomainEvent>(domainEventStorage, eventStoreIdentityMap, bus); var repository = new DomainRepository<IDomainEvent>(eventStoreUnitOfWork, eventStoreIdentityMap); new ReportingDatabaseBootStrapper().ReCreateDatabaseSchema(); reportingRepository = new SQLiteReportingRepository(sqliteConnectionString, new SqlSelectBuilder(), new SqlInsertBuilder(), new SqlUpdateBuilder(), new SqlDeleteBuilder()); handler = new ScheduleMeetingCommandHandler(repository); var messageRouter = new MessageRouter(); messageRouter.Register<ScheduleMeetingCommand>(command => handler.Handle(command)); bus.Publish(scheduleMeetingCommand); //how do we publish to report, directly or via command handler. Looks like by using transaction handler we go through unit of work whose commit method fires events to BUS //so if we have event and then save they get re-ublished and report canpick up }
public void Cant_Create_Duplicate_Domain_Name() { int contentId = CreateTestData("en-AU", out ContentType ct); IScopeProvider provider = ScopeProvider; using (IScope scope = provider.CreateScope()) { DomainRepository repo = CreateRepository(provider); ILanguage lang = LanguageRepository.GetByIsoCode("en-AU"); IContent content = DocumentRepository.Get(contentId); var domain1 = (IDomain) new UmbracoDomain("test.com") { RootContentId = content.Id, LanguageId = lang.Id }; repo.Save(domain1); var domain2 = (IDomain) new UmbracoDomain("test.com") { RootContentId = content.Id, LanguageId = lang.Id }; Assert.Throws <DuplicateNameException>(() => repo.Save(domain2)); } }
public void Can_Create_And_Get_By_Id_Empty_lang() { int contentId = CreateTestData("en-AU", out ContentType ct); IScopeProvider provider = ScopeProvider; using (IScope scope = provider.CreateScope()) { DomainRepository repo = CreateRepository(provider); IContent content = DocumentRepository.Get(contentId); var domain = (IDomain) new UmbracoDomain("test.com") { RootContentId = content.Id }; repo.Save(domain); // re-get domain = repo.Get(domain.Id); Assert.NotNull(domain); Assert.IsTrue(domain.HasIdentity); Assert.Greater(domain.Id, 0); Assert.AreEqual("test.com", domain.DomainName); Assert.AreEqual(content.Id, domain.RootContentId); Assert.IsFalse(domain.LanguageId.HasValue); } }
private Configuration() { /* bus intialisation */ _bus = new MessageBus(); //var eventStore = new SqlServerEventStore(_bus); //var eventStore = new SqlLiteEventStore(_bus); var eventStore = new InMemoryEventStore(_bus, inMemDict ); var repository = new DomainRepository(eventStore); /* Account Domain */ var commandService = new AccountApplicationService(repository); _bus.RegisterHandler<RegisterAccountCommand>(commandService.Handle); _bus.RegisterHandler<DebitAccountCommand>(commandService.Handle); _bus.RegisterHandler<UnlockAccountCommand>(commandService.Handle); var infoProjection = new AccountInfoProjection(); _bus.RegisterHandler<AccountRegisteredEvent>(infoProjection.Handle); _bus.RegisterHandler<AccountLockedEvent>(infoProjection.Handle); _bus.RegisterHandler<AccountUnlockedEvent>(infoProjection.Handle); var balanceProjection = new AccountBalanceProjection(); _bus.RegisterHandler<AccountRegisteredEvent>(balanceProjection.Handle); _bus.RegisterHandler<AccountDebitedEvent>(balanceProjection.Handle); var notification = new NotificationProjection(); _bus.RegisterHandler<AccountRegisteredEvent>(notification.Handle); _bus.RegisterHandler<AccountDebitedEvent>(notification.Handle); _bus.RegisterHandler<AccountLockedEvent>(notification.Handle); _bus.RegisterHandler<AccountUnlockedEvent>(notification.Handle); _bus.RegisterHandler<AccountOverdrawAttemptedEvent>(notification.Handle); _AccountReadModel = new AccountReadModelFacade(balanceProjection, infoProjection, notification); /* News Domain*/ //var newsEventStore = new SqlServerEventStore(_bus); //var newsEventStore = new SqlLiteEventStore(_bus); var newsEventStore = new InMemoryEventStore(_bus, inMemDict); var newsRepository = new DomainRepository(eventStore); /* Register command on the News bounded context */ var newsCommandService = new AccountManager.Models.News.Domain.NewsApplicationService(newsRepository); _bus.RegisterHandler<AccountManager.Models.News.Commands.CreateNewsCommand>(newsCommandService.Handle); _bus.RegisterHandler<AccountManager.Models.News.Commands.PublishNewsCommand>(newsCommandService.Handle); _bus.RegisterHandler<AccountManager.Models.News.Commands.UnpublishNewsCommand>(newsCommandService.Handle); _bus.RegisterHandler<AccountManager.Models.News.Commands.UpdateNewsCommand>(newsCommandService.Handle); _bus.RegisterHandler<AccountManager.Models.News.Commands.DeleteNewsCommand>(newsCommandService.Handle); var _newsProjection = new AccountManager.Models.News.ReadModel.NewsProjection(); _bus.RegisterHandler<AccountManager.Models.News.Events.NewsCreatedEvent>(_newsProjection.Handle); _bus.RegisterHandler<AccountManager.Models.News.Events.NewsPublishedEvent>(_newsProjection.Handle); _bus.RegisterHandler<AccountManager.Models.News.Events.NewsUnpublishedEvent>(_newsProjection.Handle); _bus.RegisterHandler<AccountManager.Models.News.Events.NewsUpdatedEvent>(_newsProjection.Handle); _bus.RegisterHandler<AccountManager.Models.News.Events.NewsDeletedEvent>(_newsProjection.Handle); _NewsReadModel = new NewsReadModelFacade(_newsProjection); /* rehydrate */ var events = eventStore.GetAllEventsEver(); _bus.Publish(events); }
public CommandContext(IDependencyResolver dependencyResolver) { _eventStore = dependencyResolver.Resolve <IEventStore>(); _eventBus = dependencyResolver.Resolve <IEventBus>(); _snapshotStore = dependencyResolver.Resolve <ISnapshotStore>(); _repository = new DomainRepository(_snapshotStore, _eventStore); //dependencyResolver.Resolve<IDomainRepository>(); }
/// <summary> /// SPA request event method responsible for determining the domain and culture of <paramref name="request"/>. /// </summary> /// <param name="request">The current SPA request.</param> protected virtual void FindDomainAndCulture(SpaRequest request) { // Find the domain (sets the "Domain" and "CultureInfo" of "request") DomainRepository.FindDomain(request, request.Arguments.Uri); if (request.Arguments.PageId > 0) { // If a page ID was specifically specified for the request, it may mean that we're // in preview mode or that the "url" parameter isn't specified. In either case, we // need to find the assigned domains of the requested node (or it's ancestor) so we // can determine the sitenode // TODO: Look at the "siteId" parameter as well (may be relevant for virtual content etc.) IPublishedContent c = UmbracoContext.Content.GetById(request.Arguments.PageId); if (c != null) { request.Domain = DomainRepository.DomainForNode(c, null, request.Arguments.QueryString["culture"]); if (request.Domain != null) { request.CultureInfo = request.Domain.Culture; } } } // Make sure to overwrite the variation context VariationContextAccessor.VariationContext = new VariationContext(request.CultureInfo.Name); }
public void WhenIScheduleAMeeting() { var scheduleMeetingCommand = new ScheduleMeetingCommand(MEETING_ID, meetingDate, locationId, speakerId, capacity); new DomainDatabaseBootStrapper().ReCreateDatabaseSchema(); var sqliteConnectionString = string.Format("Data Source={0}", DATA_BASE_FILE); var domainEventStorage = new DomainEventStorage <IDomainEvent>(sqliteConnectionString, new BinaryFormatter()); var eventStoreIdentityMap = new EventStoreIdentityMap <IDomainEvent>(); var bus = new DirectBus(new MessageRouter()); var eventStoreUnitOfWork = new EventStoreUnitOfWork <IDomainEvent>(domainEventStorage, eventStoreIdentityMap, bus); var repository = new DomainRepository <IDomainEvent>(eventStoreUnitOfWork, eventStoreIdentityMap); new ReportingDatabaseBootStrapper().ReCreateDatabaseSchema(); reportingRepository = new SQLiteReportingRepository(sqliteConnectionString, new SqlSelectBuilder(), new SqlInsertBuilder(), new SqlUpdateBuilder(), new SqlDeleteBuilder()); handler = new ScheduleMeetingCommandHandler(repository); var messageRouter = new MessageRouter(); messageRouter.Register <ScheduleMeetingCommand>(command => handler.Handle(command)); bus.Publish(scheduleMeetingCommand); //how do we publish to report, directly or via command handler. Looks like by using transaction handler we go through unit of work whose commit method fires events to BUS //so if we have event and then save they get re-ublished and report canpick up }
public void Get_By_Name() { int contentId = CreateTestData("en-AU", out ContentType ct); IScopeProvider provider = ScopeProvider; using (IScope scope = provider.CreateScope()) { DomainRepository repo = CreateRepository(provider); ILanguage lang = LanguageRepository.GetByIsoCode("en-AU"); IContent content = DocumentRepository.Get(contentId); for (int i = 0; i < 10; i++) { var domain = (IDomain) new UmbracoDomain("test" + i + ".com") { RootContentId = content.Id, LanguageId = lang.Id }; repo.Save(domain); } IDomain found = repo.GetByName("test1.com"); Assert.IsNotNull(found); } }
public void Can_Delete() { int contentId = CreateTestData("en-AU", out ContentType ct); IScopeProvider provider = ScopeProvider; using (IScope scope = provider.CreateScope()) { DomainRepository repo = CreateRepository(provider); ILanguage lang = LanguageRepository.GetByIsoCode("en-AU"); IContent content = DocumentRepository.Get(contentId); var domain = (IDomain) new UmbracoDomain("test.com") { RootContentId = content.Id, LanguageId = lang.Id }; repo.Save(domain); repo.Delete(domain); // re-get domain = repo.Get(domain.Id); Assert.IsNull(domain); } }
public void WhenEntityDeleted_ThenPersists() { DatabaseTestUtility.DropCreateFirebrickDatabase(); // Arrange var repository = new DomainRepository(new DatabaseFactory()); Domain entity = DefaultModelHelper.DummyPopulatedDomain(); // Act repository.Add(entity); repository.Commit(); IEnumerable<Domain> returnedEntities = repository.GetAll(); // Assert Assert.Equal(1, returnedEntities.Count()); // Act repository.Delete(entity); repository.Commit(); // Arrange // Use a new context and repository to verify the vehicle was deleted var repositoryTwo = new DomainRepository(new DatabaseFactory()); IEnumerable<Domain> verifyEntities = repositoryTwo.GetAll(); // Assert Assert.NotNull(verifyEntities); Assert.Equal(0, verifyEntities.Count()); }
/// <summary> /// Updates an existing domain. /// </summary> /// <param name="id">ID of the domain to update.</param> /// <param name="name">The new domain name to set.</param> /// <returns>Returns the updated domain.</returns> /// <exception cref="EntityNotFoundException">Thrown if no matching domain could be found.</exception> public async Task <Domain> UpdateDomain(Guid id, string name) { Domain domain = await GetDomain(id); domain.Name = name; return(await DomainRepository.UpdateDomain(domain)); }
public static async Task <IActionResult> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, TraceWriter log) { // 1. Instantiate dependencies var clockworkApi = new ClockworkApi(); var dnsRepository = new DomainRepository(); // 2. Get the request model var clockworkHook = ClockworkHookRequest.FromQueryString(req.Query); // 3. Decode the DNS Request // The DNS lookup path is in the clockworkHook message var dnsRequest = DnsRequest.FromContent(clockworkHook.Content); // 4. Handle the request if (dnsRequest.RequestType == DnsRequestType.Register) { // 3.1 If this is a registration, register the payload against the from number // await dnsRepository.Register(clockworkHook.From, dnsRequest.Payload); } else { if (dnsRequest?.Payload == "info.cern.ch") { // 3.2 Send a text to the From address with the result } } return(new StatusCodeResult(200)); }
private DomainRepository CreateRepository(IScopeProvider provider) { var accessor = (IScopeAccessor)provider; var domainRepository = new DomainRepository(accessor, AppCaches.NoCache, LoggerFactory.CreateLogger <DomainRepository>()); return(domainRepository); }
public void Get_All_Without_Wildcards() { int contentId = CreateTestData("en-AU", out ContentType ct); IScopeProvider provider = ScopeProvider; using (IScope scope = provider.CreateScope()) { DomainRepository repo = CreateRepository(provider); ILanguage lang = LanguageRepository.GetByIsoCode("en-AU"); IContent content = DocumentRepository.Get(contentId); for (int i = 0; i < 10; i++) { var domain = (IDomain) new UmbracoDomain((i % 2 == 0) ? "test " + i + ".com" : ("*" + i)) { RootContentId = content.Id, LanguageId = lang.Id }; repo.Save(domain); } IEnumerable <IDomain> all = repo.GetAll(false); Assert.AreEqual(5, all.Count()); } }
private Configuration() { _bus = new MessageBus(); var eventStore = new SqlEventStore(_bus); var repository = new DomainRepository(eventStore); var commandService = new AccountApplicationService(repository); _bus.RegisterHandler<RegisterAccountCommand>(commandService.Handle); _bus.RegisterHandler<DebitAccountCommand>(commandService.Handle); _bus.RegisterHandler<UnlockAccountCommand>(commandService.Handle); var infoProjection = new AccountInfoProjection(); _bus.RegisterHandler<AccountRegisteredEvent>(infoProjection.Handle); _bus.RegisterHandler<AccountLockedEvent>(infoProjection.Handle); _bus.RegisterHandler<AccountUnlockedEvent>(infoProjection.Handle); var balanceProjection = new AccountBalanceProjection(); _bus.RegisterHandler<AccountRegisteredEvent>(balanceProjection.Handle); _bus.RegisterHandler<AccountDebitedEvent>(balanceProjection.Handle); var notification = new NotificationProjection(); _bus.RegisterHandler<AccountRegisteredEvent>(notification.Handle); _bus.RegisterHandler<AccountDebitedEvent>(notification.Handle); _bus.RegisterHandler<AccountLockedEvent>(notification.Handle); _bus.RegisterHandler<AccountUnlockedEvent>(notification.Handle); _bus.RegisterHandler<OverdrawAttemptedEvent>(notification.Handle); _readModel = new ReadModelFacade(balanceProjection, infoProjection, notification); var events = eventStore.GetAllEventsEver(); _bus.Publish(events); }
/// <summary> /// Creates a new domain with a given name. /// </summary> /// <param name="name">The name of the domain to create.</param> /// <returns>Returns the newly created domain.</returns> /// <exception cref="EntityAlreadyExsistsException">Thrown if the domain name is already taken.</exception> public async Task <Domain> CreateDomain(string name) { if (await DomainRepository.GetDomain(name) != null) { throw new EntityAlreadyExsistsException("Domain", name); } return(await DomainRepository.CreateDomain(name)); }
protected CoreManager(DomainRepository repository, IQueryInclude <TEntity> queryInclude, Dictionary <TSortColumn, Expression <Func <TEntity, object> > > sortDictionary, ILogger <CoreManager <TEntity, TRequest, TSortColumn> > logger) : base(repository, logger) { _queryInclude = queryInclude; _sortDictionary = sortDictionary; }
/// <summary> /// 异步获取域名 /// </summary> public async Task <DomainDto> GetDomainByIdAsync(Guid id) { var entity = await DomainRepository.FindAsync(id); var result = entity.ToDto(); return(result); }
public SetActiveStatusRequestValidator(DomainRepository repository) { _repository = repository; RuleFor(x => x) .Must(x => NotAny(_repository, QueryPredicates.ChangedStatus <TEntity>(x.Id, x.IsActive))) .WithError(ValidationCodes.Common.Cmn044, values: typeof(TEntity).Name); }
/// <summary> /// 修改域名 /// </summary> public async Task UpdateAsync(DomainUpdateRequest request) { var entity = await DomainRepository.FindAsync(request.DomainId); request.MapTo(entity); await DomainRepository.UpdateAsync(entity); await UnitOfWork.CommitAsync(); }
protected IDomainRepository CreateDomainRepository(IBus bus) { var eventMappings = new NServiceBusDomainEventMappingFactory().CreateMappingCollection(); var eventPersistence = new InProcEventPersistence(); var eventPublisher = new NServiceBusEventPublisher(bus, eventMappings); var eventStore = new EventStore(eventPersistence, eventPublisher); var domainRepository = new DomainRepository(eventStore); return domainRepository; }
public void ShouldThrowExceptionWhenNoDomainEventExistForAnAggregate() { var id = Guid.NewGuid(); var events = new List<DomainEvent>(); var fakeEventStore = MockRepository.GenerateMock<IEventStore>(); fakeEventStore.Stub(x => x.GetEventsForAggregate<EmptyDomainObject>(id)).Return(events); var repository = new DomainRepository(fakeEventStore); var aggregateRoot = repository.Get<EmptyDomainObject>(id); }
public ActionResult Index() { using (DomainRepository domain_repository = new DomainRepository()) { ViewBag.items = domain_repository.All(); } return(View()); }
/// <summary> /// Gets a domain by its unique ID. /// </summary> /// <param name="id">ID of the domain to get.</param> /// <returns>Returns the domain.</returns> /// <exception cref="EntityNotFoundException">Thrown if no matching domain could be found.</exception> public async Task <Domain> GetDomain(Guid id) { Domain domain = await DomainRepository.GetDomain(id); if (domain == null) { throw new EntityNotFoundException("Domain", id); } return(domain); }
protected IDomainRepository CreateDomainRepository(IBus bus) { var eventMappings = new NServiceBusDomainEventMappingFactory().CreateMappingCollection(); var eventPersistence = new InProcEventPersistence(); var eventPublisher = new NServiceBusEventPublisher(bus, eventMappings); var eventStore = new EventStore(eventPersistence, eventPublisher); var domainRepository = new DomainRepository(eventStore); return(domainRepository); }
public void ShouldThrowExceptionWhenNoDomainEventExistForAnAggregate() { var id = Guid.NewGuid(); var events = new List <DomainEvent>(); var fakeEventStore = MockRepository.GenerateMock <IEventStore>(); fakeEventStore.Stub(x => x.GetEventsForAggregate <EmptyDomainObject>(id)).Return(events); var repository = new DomainRepository(fakeEventStore); var aggregateRoot = repository.Get <EmptyDomainObject>(id); }
/// <summary> /// Gets domains, optionally filtered by name. /// </summary> /// <param name="filter">A string to filter domain names with.</param> /// <returns>Returns domains.</returns> public async Task <IEnumerable <Domain> > GetDomains(string filter = null) { if (filter == null) { return(await DomainRepository.GetDomains()); } else { return(await DomainRepository.SearchDomainsByName(filter)); } }
public void ShouldSaveAggregateRoot() { var id = Guid.NewGuid(); var fakeEventStore = MockRepository.GenerateMock<IEventStore>(); var aggregateRoot = new EmptyDomainObject(id); fakeEventStore.Expect(x => x.SaveEvents(id, aggregateRoot.OutstandingEvents)); var repository = new DomainRepository(fakeEventStore); repository.Save(aggregateRoot); fakeEventStore.VerifyAllExpectations(); Assert.That(aggregateRoot.OutstandingEvents.Count, Is.EqualTo(0)); }
public void GetById_returns_the_right_aggregate_with_the_defined_Id_and_type() { Given("a set of events with different aggregate ids in an event store", testContext => { var aggregateId = Uuid.NewId(); testContext.State.AggregateId = aggregateId; var eventStore = new InMemoryEventStore(); eventStore.Insert(aggregateId, "Customer", new List <DomainEvent> { new CustomerCreated(), new CustomerNameChanged() }); eventStore.Insert(aggregateId, "Customer", new List <DomainEvent> { new AddressStreetChanged() }); eventStore.Insert(Uuid.NewId(), "Customer", new List <DomainEvent> { new CustomerCreated() }); eventStore.Insert(Uuid.NewId(), "Customer", new List <DomainEvent> { new CustomerCreated() }); testContext.State.EventStore = eventStore; }) .And("an empty snapshot store", testContext => { testContext.State.SnapshotStore = new InMemorySnapshotStore(); }) .And("a configured domain context", testContext => { var eventBus = new Mock <IEventBus>().Object; IEventStore eventStore = testContext.State.EventStore; ISnapshotStore snapshotStore = testContext.State.SnapshotStore; var domainRepository = new DomainRepository(eventStore, snapshotStore); var domainContext = new DomainContext(eventBus, eventStore, snapshotStore, domainRepository); testContext.State.DomainContext = domainContext; }) .When("GetById for a defined aggregate type with and events contained in the event store with the defined aggregate id is called", testContext => { var aggregate = ((DomainContext)testContext.State.DomainContext).GetById <Customer>( testContext.State.AggregateId); testContext.State.Aggregate = aggregate; }) .Then("it should return a valid aggregate", testContext => { object obj = testContext.State.Aggregate; obj.Should().NotBeNull(); obj.Should().BeOfType <Customer>(); }); }
public void TestDeleteDraftItem() { ItemSetUp(); With.Transaction(delegate { DomainRepository <T> .Delete(DraftItem); }); Assert.IsNull(DomainRepository <T> .GetGlobal(DraftItem.ObjectId)); Assert.IsNull(DomainRepository <T> .GetDraft(DraftItem.ObjectId)); }
/// <summary> /// Initializes a new instance of the <see cref="UnitOfWork" /> class. /// </summary> /// <param name="context">The context.</param> public UnitOfWork(AppDbContext context) { _context = context; Authors = new AuthorRepository(_context); BookBorrows = new BookBorrowRepository(_context); BookEditions = new BookEditionRepository(_context); Books = new BookRepository(_context); Domains = new DomainRepository(_context); Publishers = new PublisherRepository(_context); Users = new UserRepository(_context); }
public IEnumerable Handle(CreateSchedule command) { // TODO: Do we allow multiple schedules for var agRoot = ScheduleFactory.CreateSchedule(command); DomainRepository.AddSchedule(agRoot); return(new object[] { ScheduleFactory.EventFactory.ScheduleCreated(agRoot) }); // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! // NOTE: Don't use yield return, as it can cause silent failures in execution //yield return ScheduleFactory.EventFactory.ScheduleCreated(agRoot); }
private DomainRepository CreateRepository(IDatabaseUnitOfWork unitOfWork, out ContentTypeRepository contentTypeRepository, out ContentRepository contentRepository, out LanguageRepository languageRepository) { var templateRepository = new TemplateRepository(unitOfWork, CacheHelper.CreateDisabledCacheHelper(), Logger, SqlSyntax, Mock.Of <IFileSystem>(), Mock.Of <IFileSystem>(), Mock.Of <ITemplatesSection>()); var tagRepository = new TagRepository(unitOfWork, CacheHelper.CreateDisabledCacheHelper(), Logger, SqlSyntax); contentTypeRepository = new ContentTypeRepository(unitOfWork, CacheHelper.CreateDisabledCacheHelper(), Logger, SqlSyntax, templateRepository); contentRepository = new ContentRepository(unitOfWork, CacheHelper.CreateDisabledCacheHelper(), Logger, SqlSyntax, contentTypeRepository, templateRepository, tagRepository, Mock.Of <IContentSection>()); languageRepository = new LanguageRepository(unitOfWork, CacheHelper.CreateDisabledCacheHelper(), Logger, SqlSyntax); var domainRepository = new DomainRepository(unitOfWork, CacheHelper.CreateDisabledCacheHelper(), Logger, SqlSyntax); return(domainRepository); }
public void GettingExistingByIdReturnsAggregateWhenFound() { var aggregateRootId = Guid.NewGuid(); var eventStore = new Mock<IEventStore>(); eventStore.Setup(x => x.GetEvents(aggregateRootId, It.IsAny<int>())).Returns(new[] { new MyTestEvent() }); var snapshotStore = new Mock<ISnapshotStore>().Object; var eventBus = new Mock<IEventBus>().Object; var repository = new DomainRepository(eventStore.Object, snapshotStore, eventBus); var fetchedAggregateRoot = repository.GetExistingById<MyTestAggregateRoot>(aggregateRootId); Assert.IsNotNull(fetchedAggregateRoot); }
protected override void Context() { new DomainDatabaseBootStrapper().ReCreateDatabaseSchema(); var sqliteConnectionString = string.Format("Data Source={0}", DATA_BASE_FILE); var domainEventStorage = new DomainEventStorage<IDomainEvent>(sqliteConnectionString, new BinaryFormatter()); var eventStoreIdentityMap = new EventStoreIdentityMap<IDomainEvent>(); var eventStoreUnitOfWork = new EventStoreUnitOfWork<IDomainEvent>(domainEventStorage, eventStoreIdentityMap, MockRepository.GenerateStub<IBus>()); repository = new DomainRepository<IDomainEvent>(eventStoreUnitOfWork, eventStoreIdentityMap); scheduleMeetingCommand = new ScheduleMeetingCommand(meetingId, meetingTime, locationId, speakerId, CAPACITY); scheduleMeetingCommandHandler = new ScheduleMeetingCommandHandler(repository); }
public void Test() { var newMessages = new List<object>(); var bus = new MessageBus(); bus.RegisterHandler<object>(newMessages.Add); var eventStore = new InMemoryEventStore(bus, GivenTheseEvents()); var repository = new DomainRepository(eventStore); RegisterHandler(bus, repository); bus.Handle(WhenThisHappens()); var expected = TheseEventsShouldOccur(); Assert.AreEqual(expected.Count(), newMessages.Count); }
public void GettingExistingByIdThrowsExceptionWhenNotFound() { var eventStore = new Mock<IEventStore>().Object; var snapshotStore = new Mock<ISnapshotStore>().Object; var eventBus = new Mock<IEventBus>().Object; var repository = new DomainRepository(eventStore, snapshotStore, eventBus); var aggregateRootId = Guid.NewGuid(); var exception = CustomAsserts.Throws<AggregateRootNotFoundException>(() => repository.GetExistingById<MyTestAggregateRoot>(aggregateRootId) ); Assert.AreEqual(aggregateRootId, exception.AggregateRootId); Assert.AreEqual(typeof(MyTestAggregateRoot), exception.Type); }
public void ShouldGetAggregateRootById() { var id = Guid.NewGuid(); var events = new List<DomainEvent> { new EmptyDomainEvent(id) { Version = 1 } }; var fakeEventStore = MockRepository.GenerateMock<IEventStore>(); fakeEventStore.Stub(x => x.GetEventsForAggregate<EmptyDomainObject>(id)).Return(events); var repository = new DomainRepository(fakeEventStore); var aggregateRoot = repository.Get<EmptyDomainObject>(id); Assert.That(aggregateRoot.Version, Is.EqualTo(1)); }
public void ShouldRegisterOneEventHandlerForPostSave() { //arrange var domain = new TestDomain(); var testPreSaveInterceptor = new TestEventInterceptor<AfterSave>(1); domain.Events = new List<IInterceptor> { testPreSaveInterceptor }; domain.ConnectionString = Settings.Default.Connection; //act var repo = new DomainRepository<TestDomain>(new DomainContext<TestDomain>(domain), domain); repo.Context.Commit(); //assert testPreSaveInterceptor.WasCalled.Should().BeTrue(); }
private static void InitializeRepository() { var db = new EmbeddableDocumentStore() { UseEmbeddedHttpServer = true }; NonAdminHttp.EnsureCanListenToWhenInNonAdminContext(8081); db.Configuration.Port = 8081; db.Initialize(); DocumentStore = db; var eventStore = new RavenDbEventStore(db, _bus); var repository = new DomainRepository(eventStore); DomainRepository = repository; }
public void ShouldRegisterTwoEventHandlersForPreSaveAndHonorPriority() { //arrange var domain = new TestDomain(); var testPreSaveInterceptor = new TestEventInterceptor<BeforeSave>(1); var testPreSaveInterceptor2 = new TestEventInterceptor<BeforeSave>(2); domain.Events = new List<IInterceptor> { testPreSaveInterceptor, testPreSaveInterceptor2, }; domain.ConnectionString = Settings.Default.Connection; //act var repo = new DomainRepository<TestDomain>(new DomainContext<TestDomain>(domain), domain); repo.Context.Commit(); //assert testPreSaveInterceptor.WasCalled.Should().BeTrue(); testPreSaveInterceptor2.WasCalled.Should().BeTrue(); testPreSaveInterceptor.CallTime.Should().BeBefore(testPreSaveInterceptor2.CallTime); }
public void Test() { var newMessages = new List<object>(); var bus = new MessageBus(); bus.RegisterHandler<object>(newMessages.Add); var eventStore = new InMemoryEventStore(bus, GivenTheseEvents()); var repository = new DomainRepository(eventStore); RegisterHandler(bus, repository); try { bus.Handle(WhenThisHappens()); } catch(Exception e) { var expectedException = ThisExceptionShouldOccur(); if(expectedException == null) Assert.Fail(e.Message); if(expectedException.GetType().IsAssignableFrom(e.GetType())) { Assert.AreEqual(expectedException.Message, e.Message); return; } Assert.Fail("Expected exception of type {0} with message {1} but got exception of type {2} with message {3}", expectedException.GetType(), expectedException.Message, e.GetType(), e.Message); } var expectedEvents = TheseEventsShouldOccur().ToList(); var comparer = new CompareObjects(); if(!comparer.Compare(expectedEvents, newMessages)) { Assert.Fail(comparer.DifferencesString); } }
public void Start() { //IServiceBus bus = ServiceBusFactory.New(cfg => //{ // cfg.ReceiveFrom("loopback://localhost/temp"); //}); //InMemoryDomainRespository repo = new InMemoryDomainRespository(); DomainRepository repo = new DomainRepository(EventDbContext.Create("EventStore")); DomainEntry entry = new DomainEntry(repo); Guid id = Guid.NewGuid(); entry.ExecuteCommand<CreateNetworkDevice>(new CreateNetworkDevice(id, "SESM-01")); entry.ExecuteCommand<SetNetworkDeviceInactive>(new SetNetworkDeviceInactive(id)); entry.ExecuteCommand<SetNetworkDeviceActive>(new SetNetworkDeviceActive(id)); var a = 1; //bus.Publish(new CreateNetworkDevice(Guid.NewGuid(), "TESTAR")); }
public void BootStrapTheApplication() { EventStoreDatabaseBootStrapper.BootStrap(); ReportingDatabaseBootStrapper.BootStrap(); var bus = new FakeBus(); ServiceLocator.Bus = bus; //var storage = new InMemoryEventStore(bus); //var storage = new NHibernateSqliteEventStore(bus, NHibernateSessionHelper.CreateSessionFactory(), new BinaryFormatter()); var storage = new SqliteEventStore(bus, new BinaryFormatter(), "Data Source=eventStore.db3"); var rep = new DomainRepository<InventoryItem>(storage); var commands = new InventoryCommandHandlers(rep); bus.RegisterHandler<CheckInItemsToInventory>(commands.Handle); bus.RegisterHandler<CreateInventoryItem>(commands.Handle); bus.RegisterHandler<DeactivateInventoryItem>(commands.Handle); bus.RegisterHandler<RemoveItemsFromInventory>(commands.Handle); bus.RegisterHandler<RenameInventoryItem>(commands.Handle); var sqlInsertBuilder = new SqlInsertBuilder(); var sqlSelectBuilder = new SqlSelectBuilder(); var sqlUpdateBuilder = new SqlUpdateBuilder(); var sqlDeleteBuilder = new SqlDeleteBuilder(); var reportingRepository = new SQLiteReportingRepository("Data Source=reportingDataBase.db3", sqlSelectBuilder, sqlInsertBuilder, sqlUpdateBuilder, sqlDeleteBuilder); var detail = new InventoryItemDetailViewHandler(reportingRepository); ServiceLocator.ReportingRepository = reportingRepository; bus.RegisterHandler<InventoryItemCreated>(detail.Handle); bus.RegisterHandler<InventoryItemDeactivated>(detail.Handle); bus.RegisterHandler<InventoryItemRenamed>(detail.Handle); bus.RegisterHandler<ItemsCheckedInToInventory>(detail.Handle); bus.RegisterHandler<ItemsRemovedFromInventory>(detail.Handle); var list = new InventoryItemListViewHandler(reportingRepository); bus.RegisterHandler<InventoryItemCreated>(list.Handle); bus.RegisterHandler<InventoryItemRenamed>(list.Handle); bus.RegisterHandler<InventoryItemDeactivated>(list.Handle); }
int Run() { var testTypes = typeof(AccountShouldBeLockedAfterThreeOverdraws).Assembly.GetTypes().Where(x => typeof(TestBase).IsAssignableFrom(x) && x.IsAbstract == false); foreach (var type in testTypes) { var test = Activator.CreateInstance(type) as TestBase; var newMessages = new List<object>(); var bus = new MessageBus(); bus.RegisterHandler<object>(newMessages.Add); var eventStore = new InMemoryEventStore(bus, test.GivenTheseEvents()); var repository = new DomainRepository(eventStore); test.RegisterHandler(bus, repository); printGivens(type, test); var command = test.WhenThisHappens(); Exception exception = null; var expectedException = test.ThisExceptionShouldOccur(); try { bus.Handle(command); } catch(Exception e) { exception = e; } var foundException = printException(expectedException, exception, command); if(foundException) continue; ; printThens(test.TheseEventsShouldOccur().ToList(), newMessages, command); Console.WriteLine(); Console.WriteLine(new string('=', 40)); Console.WriteLine(); } return _suuccess ? 0 : -1; }
public void WhenGetAllFromEmptyDatabase_ThenReturnsEmptyCollection() { DatabaseTestUtility.DropCreateFirebrickDatabase(); var repository = new DomainRepository(new DatabaseFactory()); IEnumerable<Domain> actual = repository.GetAll(); Assert.NotNull(actual); var actualList = new List<Domain>(actual); Assert.Equal(0, actualList.Count); }