public async Task EventIsSendToMessageSender() { var senderMock = new Mock <IMessageSender>(MockBehavior.Strict); senderMock.Setup(r => r.SendMessageAsync(It.IsAny <EventMessage>())) .Returns(EmptyTask); senderMock.Setup(r => r.Dispose()); var contextMock = new Mock <IBusContext <string> >(MockBehavior.Strict); contextMock.Setup(bc => bc.CreateMessageSender()) .Returns(senderMock.Object); var target = new EventPublisher <string>(contextMock.Object); var evt = new SomeEvent { SomeNumber = 5 }; await target.PublishEventAsync(evt); senderMock.Verify(r => r.SendMessageAsync(It.Is <EventMessage>(em => em.Topic == "DDD.Core.Application.Test.SomeEvent" && em.EventType == "SomeEvent" && //Encoding.Unicode.GetString(em.Body) == "{\r\n \"SomeNumber\": 5\r\n}" Encoding.Unicode.GetString(em.Body).Contains("\"SomeNumber\"") && Encoding.Unicode.GetString(em.Body).Contains("5") ))); }
public void DispatchingEventsInTheWrongOrderWithANonZeroStartingSequenceNumber( IRepository <string, SomeData> repository, View view, ISequenceResolver sequenceResolver, IViewManager viewManager, SomeEvent firstEvent, SomeEvent secondEvent) { "Given a view repository"._(() => repository = new MemoryRepository <string, SomeData>()); "and a view"._(() => view = new SomeView(repository)); "and a sequence resolver"._(() => sequenceResolver = new CustomSequenceResolver()); "and a view manager"._(ctx => viewManager = ViewManager.ForViews(view).OrderEventsUsing(sequenceResolver).StartAtSequenceNumber(2).Create().Using(ctx)); "and a first event"._(() => firstEvent = new SomeEvent { Sequence = 2, Id = "test2" }); "and a second event"._(() => secondEvent = new SomeEvent { Sequence = 3, Id = "test3" }); "when those events are dispatched out of order"._( () => { viewManager.QueueForDispatch(secondEvent); viewManager.QueueForDispatch(firstEvent); }); "and the operation is given time to process"._(() => Thread.Sleep(1000)); "then the view received the second event last"._(() => repository.Get("root").LastEventId.Should().Be(secondEvent.Id)); "and the view received two events"._(() => repository.Get("root").EventCount.Should().Be(1)); }
public void ProcessEvent(SomeEvent @event) { if (_condition.Matches(@event)) { _action.PerformWork(@event); } }
static async Task MainAsync() { Console.Title = "Samples.ASB.Serialization.Publisher"; var endpointConfiguration = new EndpointConfiguration("Samples.ASB.Serialization.Publisher"); var transport = endpointConfiguration.UseTransport <AzureServiceBusTransport>(); var connectionString = Environment.GetEnvironmentVariable("AzureServiceBus.ConnectionString"); if (string.IsNullOrWhiteSpace(connectionString)) { throw new Exception("Could not read the 'AzureServiceBus.ConnectionString' environment variable. Check the sample prerequisites."); } transport.ConnectionString(connectionString); transport.UseForwardingTopology(); endpointConfiguration.UsePersistence <InMemoryPersistence>(); endpointConfiguration.UseSerialization <JsonSerializer>(); endpointConfiguration.EnableInstallers(); endpointConfiguration.SendFailedMessagesTo("error"); var recoverability = endpointConfiguration.Recoverability(); recoverability.Delayed( customizations: settings => { settings.NumberOfRetries(0); }); var endpointInstance = await Endpoint.Start(endpointConfiguration) .ConfigureAwait(false); try { Console.WriteLine("Press 'e' to publish an event"); Console.WriteLine("Press any other key to exit"); while (true) { var key = Console.ReadKey(); Console.WriteLine(); var eventId = Guid.NewGuid(); if (key.Key != ConsoleKey.E) { break; } var someEvent = new SomeEvent { EventId = eventId }; await endpointInstance.Publish(someEvent) .ConfigureAwait(false); Console.WriteLine($"SomeEvent sent. EventId: {eventId}"); } } finally { await endpointInstance.Stop() .ConfigureAwait(false); } }
public void ClearSomeEvent() { foreach (EventHandler e in SomeEvent.GetInvocationList()) { SomeEvent -= e; } }
private void LecturerSearch(string lecturerInitials, int experience, string phone) { IEnumerable <Subject> request = subjects.Select(x => x); if (lecturerInitials != "") { request = request.Where(item => item.Lecturer.Initials.Contains(lecturerInitials)); SomeEvent.Invoke("Поиск по инициалам преподавателя", request.ToList()); } if (experience > 0) { request = request.Where(item => item.Lecturer.Experience == experience); SomeEvent.Invoke("Поиск по опыту работы", request.ToList()); } if (phone != "( ) - -") { request = request.Where(item => item.Lecturer.Phone.Contains(phone)); SomeEvent.Invoke("Поиск по номеру телефона", request.ToList()); } this.subjects = request.ToList(); ShowSubjectCollection(request); ShowLecturersFromCollection(request); }
public void DoSomething() { if (SomeEvent != null) { SomeEvent.Invoke(); } }
public void CanDispatchMultipleEventsToMultipleViews() { var firstRepository = new MemoryRepository <string, SomeEvent>(); var secondRepository = new MemoryRepository <string, SomeEvent>(); var views = new View[] { new SomeView(firstRepository), new SomeView(secondRepository) }; var snapshotRepository = new MemoryRepository <string, Snapshot>(); var firstEvent = new SomeEvent { Id = "test" }; var secondEvent = new SomeEvent { Id = "test2" }; using (var snapshotManager = new SnapshotManager(views, snapshotRepository, Timeout.Infinite)) { // act snapshotManager.Dispatch(new Event { SequenceNumber = 1, Payload = firstEvent }); snapshotManager.Dispatch(new Event { SequenceNumber = 2, Payload = secondEvent }); // assert firstRepository.Get(firstEvent.Id).Should().Be(firstEvent); firstRepository.Get(secondEvent.Id).Should().Be(secondEvent); secondRepository.Get(firstEvent.Id).Should().Be(firstEvent); secondRepository.Get(secondEvent.Id).Should().Be(secondEvent); } }
protected void OnFoo(EventArgs e) { SomeEvent?.Invoke(this, e); SomeEvent?.Invoke(null, e); // Noncompliant {{Make the sender on this event invocation not null.}} // ^^^^^^^^^^^^^^^^ SomeEvent?.Invoke(this, null); // Noncompliant {{Use 'EventArgs.Empty' instead of null as the event args of this event invocation.}} SomeEvent?.Invoke(null, null); // Noncompliant // Noncompliant@-1 SomeEvent(null, e); // Noncompliant {{Make the sender on this event invocation not null.}} // ^^^^^^^^^^^^^^^^^^ SomeEvent.Invoke(this, e); SomeStaticEvent?.Invoke(null, e); SomeStaticEvent?.Invoke(this, e); // Noncompliant {{Make the sender on this static event invocation null.}} SomeStaticEvent?.Invoke(null, null); // Noncompliant {{Use 'EventArgs.Empty' instead of null as the event args of this event invocation.}} SomeStaticEvent?.Invoke(this, null); // Noncompliant // Noncompliant@-1 SomeStaticEvent(this, e); // Noncompliant {{Make the sender on this static event invocation null.}} SomeEvent?.Invoke(default(object), e); // Compliant - we don't handle default(T) SomeEvent?.Invoke(this, default(EventArgs)); // Compliant - we don't handle default(T) }
public void ProcessEvent(SomeEvent @event) { if (_first.Matches(@event) || _second.Matches(@event)) { _action.PerformWork(@event); } }
public void CanSnapshotSingleViewDuringDispatch() { var repository = new TestRepository(); var views = new View[] { new SomeView(repository) }; var snapshotRepository = new MemoryRepository <string, Snapshot>(); var firstEvent = new SomeEvent { Id = "test" }; var secondEvent = new SomeEvent { Id = "test2" }; using (var snapshotManager = new SnapshotManager(views, snapshotRepository, 20)) { snapshotManager.Dispatch(new Event { SequenceNumber = 1, Payload = firstEvent }); // act var preSnapshotEvent = repository.Get(secondEvent.Id); repository.WaitUntilSnapshotSaveStarted(); repository.WaitUntilSnapshotSaveEnded(); snapshotManager.Dispatch(new Event { SequenceNumber = 2, Payload = secondEvent }); repository.WaitUntilSnapshotSaveEnded(); var postSnapshotEvent = repository.Get(secondEvent.Id); // assert preSnapshotEvent.Should().BeNull(); postSnapshotEvent.Should().Be(secondEvent); } }
public void ReplayedEventsAreClones() { var someEvent = new SomeEvent { ListOfStuff = { "hej", "med", "dig" }, Meta = { { DomainEvent.MetadataKeys.AggregateRootId, Guid.NewGuid().ToString() }, { DomainEvent.MetadataKeys.SequenceNumber, 0.ToString(Metadata.NumberCulture) }, { DomainEvent.MetadataKeys.GlobalSequenceNumber, 0.ToString(Metadata.NumberCulture) }, } }; var eventData = new[] { someEvent } .Select(e => _domainEventSerializer.Serialize(e)) .ToList(); _eventStore.Save(Guid.NewGuid(), eventData); someEvent.ListOfStuff.Add("WHOA?!!? WHERE DID YOU COME FROM??"); var allEvents = _eventStore.Stream() .Select(e => _domainEventSerializer.Deserialize(e)) .OfType <SomeEvent>().ToList(); Assert.That(allEvents.Count, Is.EqualTo(1)); var relevantEvent = allEvents[0]; Assert.That(relevantEvent.ListOfStuff.Count, Is.EqualTo(3), "Oh noes! It appears that the event was changed: {0}", string.Join(" ", relevantEvent.ListOfStuff)); }
public void filtered_listeners_must_be_notified_only_when_condition_were_satisfied() { var listener1 = MockRepository.GenerateMock<IListenTo<SomeEvent>.ThatSatisfy>(); var listener2 = MockRepository.GenerateMock<IListenTo<SomeEvent>.ThatSatisfy>(); var listener3 = MockRepository.GenerateMock<IListenTo<SomeEvent>.All>(); var someEvent = new SomeEvent(); listener1.Expect(x => x.Handle(someEvent)).Repeat.Once(); listener1.Expect(x => x.SatisfiedBy(someEvent)).Return(true); listener2.Expect(x => x.Handle(someEvent)).Repeat.Never(); listener2.Expect(x => x.SatisfiedBy(someEvent)).Return(false); listener3.Expect(x => x.Handle(someEvent)).Repeat.Once(); _eventAggregator.AddListener(listener1); _eventAggregator.AddListener(listener2); _eventAggregator.AddListener(listener3); _eventAggregator.SendMessage(someEvent); listener1.VerifyAllExpectations(); listener2.VerifyAllExpectations(); listener3.VerifyAllExpectations(); }
public void ProcessEvent(SomeEvent @event) { if (_conditions.Any(x => x.Matches(@event))) { _actions.Each(x => x.PerformWork(@event)); } }
public void RunEvents() { while (true) { SomeEvent.Invoke(); } }
public void SubscriptionsWorkLikeExpectedWhenRabbitManagesThemAlsoWhenPublishingWithGenericTypeOtherThanActualType() { // arrange DeleteQueue("test.rabbitsub.publisher"); DeleteQueue("test.rabbitsub.sub1"); var receivedSub1 = new List <int>(); var sub1 = PullOneOutOfTheHat("test.rabbitsub.sub1", receivedSub1.Add); var publisher = PullOneOutOfTheHat("test.rabbitsub.publisher"); // wait a while to allow queues to be initialized Thread.Sleep(1.Seconds()); sub1.Subscribe <SomeEvent>(); Thread.Sleep(0.5.Seconds()); object someEventAsObject = new SomeEvent { Number = 1 }; // act publisher.Publish(someEventAsObject); // assert Thread.Sleep(0.5.Seconds()); receivedSub1.OrderBy(i => i).ToArray().ShouldBe(new[] { 1 }); }
public void ClearEventHandlers() { Delegate[] delegates = SomeEvent.GetInvocationList(); foreach (Delegate delegate in delegates) { SomeEvent -= (EventHandler) delegate; } }
public void RaiseEventOnOtherThread() { Task.Run(async() => { await Task.Delay(TimeSpan.FromSeconds(2)); SomeEvent?.Invoke(); }); }
void Elapsed(object sender, ElapsedEventArgs e) { if (SomeEvent != null) { Console.WriteLine("Hogs in memory: {0}", SomeEvent.GetInvocationList().Count()); } }
public bool NotifyWithFunction(int id) { bool createdArg = false; SomeEvent.Raise(this, () => { createdArg = true; return(new SomeEventArgs(id)); }); return(createdArg); }
private void eventRaiser() { foreach (var item in _queue.GetConsumingEnumerable()) { SomeEvent?.Invoke(item); } Console.WriteLine("Exiting from eventRaiser()"); }
// Start is called before the first frame update void Start() { Observable.FromEvent <SomeEvent, string>( h => msg => h(msg), h => someEvent += h, h => someEvent -= h ) .Subscribe(x => Debug.Log("OnComplateCallback:" + x)); }
public void ChangeState( Action<DomainEvent> inspectbefore, Action<DomainEvent> inspectAfter ) { var evt = new SomeEvent(inspectbefore); RaiseEvent(evt); inspectAfter(evt); }
public bool RaiseEvent(double amount) { if (SomeEvent != null) { SomeEvent.Invoke(amount); return(true); } return(false); }
// the event is private, and we can only subscribe // through this method public void Subscribe(Action callback) { // 'callback' already attached? if (SomeEvent != null && SomeEvent.GetInvocationList().Contains(action)) { return; } SomeEvent += callback; }
public void SubsequentViewPersistence( IRepository <string, SomeData> repository, View view, ISequenceResolver sequenceResolver, IRepository <string, Snapshot> snapshotRepository, IViewManager viewManager, SomeEvent firstEvent, SomeEvent secondEvent, SomeData initialData, SomeData actualInitialData, SomeData subsequentData) { "Given a view repository"._(() => repository = new MemoryRepository <string, SomeData>()); "and some intial data"._( () => initialData = new SomeData { LastEventId = "test2", EventCount = 2, }); "and the repository contains the initial data"._(() => repository.AddOrUpdate("root", initialData)); "and a view"._(() => view = new SomeView(repository)); "and a sequence resolver"._(() => sequenceResolver = new CustomSequenceResolver()); "and a snapshot repository"._(() => snapshotRepository = new MemoryRepository <string, Snapshot>()); "and the snapshot repository contains the initial snapshot data"._( () => snapshotRepository.AddOrUpdate( view.GetType().FullName, new Snapshot { ViewName = view.GetType().FullName, PersistedSequenceNumber = 2, })); "and a view manager"._(ctx => viewManager = ViewManager.ForViews(view) .OrderEventsUsing(sequenceResolver) .SnapshotViewsUsing(snapshotRepository).WithAQuietTimeTimeoutOf(2) .Create().Using(ctx)); "and a third event"._(() => firstEvent = new SomeEvent { Sequence = 3, Id = "test3" }); "and a fourth event"._(() => secondEvent = new SomeEvent { Sequence = 4, Id = "test4" }); "when those events are dispatched"._( () => { viewManager.QueueForDispatch(firstEvent); viewManager.QueueForDispatch(secondEvent); }); "and the operation is given time to process"._(() => Thread.Sleep(1000)); "and the repository is queried initially"._(() => actualInitialData = repository.Get("root")); "and the snapshot is given time to process"._(() => Thread.Sleep(2000)); "and the repository is queried subsequently"._(() => subsequentData = repository.Get("root")); "then the initial query should be empty"._(() => actualInitialData.Should().Be(initialData)); "and the view received the second event last"._(() => subsequentData.LastEventId.Should().Be(secondEvent.Id)); "and the view received two events"._(() => subsequentData.EventCount.Should().Be(4)); }
public EventStarterTwo() { timer = new Timer((delegate(object state) { if (SomeEvent != null) { SomeEvent.Invoke(this, EventArgs.Empty); } }), null, 10 * 1000, 1000 * 10); }
public void ChangeState( Action <DomainEvent> inspectbefore, Action <DomainEvent> inspectAfter ) { var evt = new SomeEvent(inspectbefore); RaiseEvent(evt); inspectAfter(evt); }
public static void InvokeSomeEvent() { // Make sure event is only invoked if someone is listening if (SomeEvent == null) { return; } SomeEvent.Invoke(); }
private void LecturerRegex2_button_Click(object sender, EventArgs e) { Regex regex = new Regex(@"\(\d{2}\)\s\d+[5]-\d{2}-\d{2}"); var request = subjects.Where(item => regex.IsMatch(item.Lecturer.Phone)); SomeEvent.Invoke("Поиск по регулярному выражению 2", request.ToList()); ShowSubjectCollection(request); ShowLecturersFromCollection(request); }
private void LecturerRegex_button_Click(object sender, EventArgs e) { Regex regex = new Regex(@"^\w[Пан]"); var request = subjects.Where(item => regex.IsMatch(item.Lecturer.Initials)); SomeEvent.Invoke("Поиск по регулярному выражению 1", request.ToList()); ShowSubjectCollection(request); ShowLecturersFromCollection(request); }
public void Consume(SomeEvent @event) { this.eventCount++; this.repository.AddOrUpdate( "root", new SomeData { LastEventId = @event.Id, EventCount = eventCount, }); }
public void all_listeners_must_be_notified_of_published_messages() { var listener1 = MockRepository.GenerateMock<IListenTo<SomeEvent>.All>(); var listener2 = MockRepository.GenerateMock<IListenTo<SomeEvent>.All>(); var someEvent = new SomeEvent(); listener1.Expect(x => x.Handle(someEvent)).Repeat.Once(); listener2.Expect(x => x.Handle(someEvent)).Repeat.Once(); _eventAggregator.AddListener(listener1); _eventAggregator.AddListener(listener2); _eventAggregator.SendMessage(someEvent); listener1.VerifyAllExpectations(); listener2.VerifyAllExpectations(); }
protected void Apply(SomeEvent evt) { evt.Inspector(evt); }
public void SubscriptionsWorkLikeExpectedWhenRabbitManagesThemAlsoWhenPublishingWithGenericTypeOtherThanActualType() { // arrange var receivedSub1 = new List<int>(); var sub1 = PullOneOutOfTheHat("test.rabbitsub.sub1", receivedSub1.Add); var publisher = PullOneOutOfTheHat("test.rabbitsub.publisher"); // wait a while to allow queues to be initialized Thread.Sleep(1.Seconds()); sub1.Subscribe<SomeEvent>(); Thread.Sleep(0.5.Seconds()); object someEventAsObject = new SomeEvent { Number = 1 }; // act publisher.Publish(someEventAsObject); // assert Thread.Sleep(0.5.Seconds()); receivedSub1.OrderBy(i => i).ToArray().ShouldBe(new[] { 1 }); }