Repository: OKTAYKIR/EventFlow.Example Branch: master Commit: 5f1ea82a6317 Files: 42 Total size: 66.5 KB Directory structure: gitextract_bi2if15r/ ├── .dockerignore ├── .github/ │ └── workflows/ │ └── dotnetcore.yml ├── .gitignore ├── EventFlow.Example/ │ ├── Aggregates/ │ │ ├── CommandHandlers/ │ │ │ ├── ExampleCommandHandler.cs │ │ │ └── ResetCommandHandler.cs │ │ ├── Commands/ │ │ │ ├── ExampleCommand.cs │ │ │ └── ResetCommand.cs │ │ ├── Decoraters/ │ │ │ └── LogCommandBus.cs │ │ ├── Events/ │ │ │ ├── ExampleEvent.cs │ │ │ ├── ExampleId.cs │ │ │ └── ResetEvent.cs │ │ ├── ExampleAggregate.cs │ │ ├── ReadModels/ │ │ │ └── ExampleReadModel.cs │ │ ├── Sagas/ │ │ │ ├── Events/ │ │ │ │ ├── ExampleSagaCompletedEvent.cs │ │ │ │ └── ExampleSagaStartedEvent.cs │ │ │ ├── ExampleSaga.cs │ │ │ ├── ExampleSagaId.cs │ │ │ ├── SagaExtension.cs │ │ │ └── SagaLocator.cs │ │ ├── Snapshots/ │ │ │ ├── ExampleSnapshot.cs │ │ │ └── ExampleSnapshotVersion.cs │ │ └── Subscribers/ │ │ └── ExampleSyncSubscriber.cs │ ├── EventFlow.Example.csproj │ ├── Jobs/ │ │ └── ExampleJobs.cs │ ├── Models/ │ │ └── CommandReturnResult.cs │ ├── Program.cs │ └── PublishCommand.cs ├── EventFlow.Tests/ │ ├── EventFlow.Tests.csproj │ ├── IntegrationTestBase.cs │ └── IntegrationTests.cs ├── EventFlowExamples.sln ├── EventStore/ │ ├── EventStore.csproj │ └── EventStoreExtension.cs ├── LICENSE ├── README.md ├── SyncEventHandler/ │ ├── ExampleAggregate.cs │ ├── ExampleEvent.cs │ ├── ExampleSyncSubscriber.cs │ ├── Program.cs │ └── SyncEventHandler.csproj ├── _config.yml └── build/ └── docker-compose.yml ================================================ FILE CONTENTS ================================================ ================================================ FILE: .dockerignore ================================================ **/.classpath **/.dockerignore **/.env **/.git **/.gitignore **/.project **/.settings **/.toolstarget **/.vs **/.vscode **/*.*proj.user **/*.dbmdl **/*.jfm **/azds.yaml **/bin **/charts **/docker-compose* **/Dockerfile* **/node_modules **/npm-debug.log **/obj **/secrets.dev.yaml **/values.dev.yaml LICENSE README.md ================================================ FILE: .github/workflows/dotnetcore.yml ================================================ # This is a basic workflow to help you get started with Actions name: CI # Controls when the action will run. Triggers the workflow on push or pull request # events but only for the master branch on: push: branches: [ master ] pull_request: branches: [ master ] # A workflow run is made up of one or more jobs that can run sequentially or in parallel jobs: # This workflow contains a single job called "build" build: # The type of runner that the job will run on runs-on: ubuntu-latest # Steps represent a sequence of tasks that will be executed as part of the job steps: - uses: actions/checkout@v2 - name: Setup .NET Core uses: actions/setup-dotnet@v1 with: dotnet-version: 3.1.101 - name: Build with dotnet run: dotnet build --configuration Release - name: sonar-scanner uses: Warchant/setup-sonar-scanner@v1 - name: Build the stack run: docker-compose -f build/docker-compose.yml up -d - name: Sleep uses: jakejarvis/wait-action@master with: time: '5s' - name: Check running containers run: docker ps -a - name: Check logs run: docker-compose -f build/docker-compose.yml logs - name: Tests run: dotnet test EventFlow.Tests/EventFlow.Tests.csproj --configuration Release ================================================ FILE: .gitignore ================================================ ## Ignore Visual Studio temporary files, build results, and ## files generated by popular Visual Studio add-ons. ## ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore # User-specific files *.suo *.user *.userosscache *.sln.docstates # User-specific files (MonoDevelop/Xamarin Studio) *.userprefs # Build results [Dd]ebug/ [Dd]ebugPublic/ [Rr]elease/ [Rr]eleases/ x64/ x86/ bld/ [Bb]in/ [Oo]bj/ [Ll]og/ # Visual Studio 2015/2017 cache/options directory .vs/ # Uncomment if you have tasks that create the project's static files in wwwroot #wwwroot/ # Visual Studio 2017 auto generated files Generated\ Files/ # MSTest test Results [Tt]est[Rr]esult*/ [Bb]uild[Ll]og.* # NUNIT *.VisualState.xml TestResult.xml # Build Results of an ATL Project [Dd]ebugPS/ [Rr]eleasePS/ dlldata.c # Benchmark Results BenchmarkDotNet.Artifacts/ # .NET Core project.lock.json project.fragment.lock.json artifacts/ **/Properties/launchSettings.json # StyleCop StyleCopReport.xml # Files built by Visual Studio *_i.c *_p.c *_i.h *.ilk *.meta *.obj *.iobj *.pch *.pdb *.ipdb *.pgc *.pgd *.rsp *.sbr *.tlb *.tli *.tlh *.tmp *.tmp_proj *.log *.vspscc *.vssscc .builds *.pidb *.svclog *.scc # Chutzpah Test files _Chutzpah* # Visual C++ cache files ipch/ *.aps *.ncb *.opendb *.opensdf *.sdf *.cachefile *.VC.db *.VC.VC.opendb # Visual Studio profiler *.psess *.vsp *.vspx *.sap # Visual Studio Trace Files *.e2e # TFS 2012 Local Workspace $tf/ # Guidance Automation Toolkit *.gpState # ReSharper is a .NET coding add-in _ReSharper*/ *.[Rr]e[Ss]harper *.DotSettings.user # JustCode is a .NET coding add-in .JustCode # TeamCity is a build add-in _TeamCity* # DotCover is a Code Coverage Tool *.dotCover # AxoCover is a Code Coverage Tool .axoCover/* !.axoCover/settings.json # Visual Studio code coverage results *.coverage *.coveragexml # NCrunch _NCrunch_* .*crunch*.local.xml nCrunchTemp_* # MightyMoose *.mm.* AutoTest.Net/ # Web workbench (sass) .sass-cache/ # Installshield output folder [Ee]xpress/ # DocProject is a documentation generator add-in DocProject/buildhelp/ DocProject/Help/*.HxT DocProject/Help/*.HxC DocProject/Help/*.hhc DocProject/Help/*.hhk DocProject/Help/*.hhp DocProject/Help/Html2 DocProject/Help/html # Click-Once directory publish/ # Publish Web Output *.[Pp]ublish.xml *.azurePubxml # Note: Comment the next line if you want to checkin your web deploy settings, # but database connection strings (with potential passwords) will be unencrypted *.pubxml *.publishproj # Microsoft Azure Web App publish settings. Comment the next line if you want to # checkin your Azure Web App publish settings, but sensitive information contained # in these scripts will be unencrypted PublishScripts/ # NuGet Packages *.nupkg # The packages folder can be ignored because of Package Restore **/[Pp]ackages/* # except build/, which is used as an MSBuild target. !**/[Pp]ackages/build/ # Uncomment if necessary however generally it will be regenerated when needed #!**/[Pp]ackages/repositories.config # NuGet v3's project.json files produces more ignorable files *.nuget.props *.nuget.targets # Microsoft Azure Build Output csx/ *.build.csdef # Microsoft Azure Emulator ecf/ rcf/ # Windows Store app package directories and files AppPackages/ BundleArtifacts/ Package.StoreAssociation.xml _pkginfo.txt *.appx # Visual Studio cache files # files ending in .cache can be ignored *.[Cc]ache # but keep track of directories ending in .cache !*.[Cc]ache/ # Others ClientBin/ ~$* *~ *.dbmdl *.dbproj.schemaview *.jfm *.pfx *.publishsettings orleans.codegen.cs # Including strong name files can present a security risk # (https://github.com/github/gitignore/pull/2483#issue-259490424) #*.snk # Since there are multiple workflows, uncomment next line to ignore bower_components # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) #bower_components/ # RIA/Silverlight projects Generated_Code/ # Backup & report files from converting an old project file # to a newer Visual Studio version. Backup files are not needed, # because we have git ;-) _UpgradeReport_Files/ Backup*/ UpgradeLog*.XML UpgradeLog*.htm ServiceFabricBackup/ *.rptproj.bak # SQL Server files *.mdf *.ldf *.ndf # Business Intelligence projects *.rdl.data *.bim.layout *.bim_*.settings *.rptproj.rsuser # Microsoft Fakes FakesAssemblies/ # GhostDoc plugin setting file *.GhostDoc.xml # Node.js Tools for Visual Studio .ntvs_analysis.dat node_modules/ # Visual Studio 6 build log *.plg # Visual Studio 6 workspace options file *.opt # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) *.vbw # Visual Studio LightSwitch build output **/*.HTMLClient/GeneratedArtifacts **/*.DesktopClient/GeneratedArtifacts **/*.DesktopClient/ModelManifest.xml **/*.Server/GeneratedArtifacts **/*.Server/ModelManifest.xml _Pvt_Extensions # Paket dependency manager .paket/paket.exe paket-files/ # FAKE - F# Make .fake/ # JetBrains Rider .idea/ *.sln.iml # CodeRush .cr/ # Python Tools for Visual Studio (PTVS) __pycache__/ *.pyc # Cake - Uncomment if you are using it # tools/** # !tools/packages.config # Tabs Studio *.tss # Telerik's JustMock configuration file *.jmconfig # BizTalk build output *.btp.cs *.btm.cs *.odx.cs *.xsd.cs # OpenCover UI analysis results OpenCover/ # Azure Stream Analytics local run output ASALocalRun/ # MSBuild Binary and Structured Log *.binlog # NVidia Nsight GPU debugger configuration file *.nvuser # MFractors (Xamarin productivity tool) working folder .mfractor/ ================================================ FILE: EventFlow.Example/Aggregates/CommandHandlers/ExampleCommandHandler.cs ================================================ using System; using System.Threading; using System.Threading.Tasks; using EventFlow.Commands; using EventFlow.Jobs; using EventFlowExample.Aggregates.Commands; using EventFlowExample.Aggregates.Events; using EventFlowExample.Jobs; using EventFlowExample.Models; namespace EventFlowExample.Aggregates.CommandHandlers { public class ExampleCommandHandler : CommandHandler { private readonly IJobScheduler _jobScheduler; public ExampleCommandHandler(IJobScheduler jobScheduler) { _jobScheduler = jobScheduler; } public override async Task ExecuteCommandAsync( ExampleAggregate aggregate, ExampleCommand command, CancellationToken cancellationToken) { var executionResult = aggregate.SetMagicNumer(command.MagicNumber); await _jobScheduler .ScheduleAsync(new ExampleJob("Example job"), TimeSpan.FromSeconds(10), CancellationToken.None) .ConfigureAwait(false); return await Task.FromResult(new CommandReturnResult(executionResult.IsSuccess, aggregate)); } } } ================================================ FILE: EventFlow.Example/Aggregates/CommandHandlers/ResetCommandHandler.cs ================================================ using System.Threading; using System.Threading.Tasks; using EventFlow.Aggregates.ExecutionResults; using EventFlow.Commands; using EventFlowExample.Aggregates.Commands; using EventFlowExample.Aggregates.Events; namespace EventFlowExample.Aggregates.CommandHandlers { public class ResetCommandHandler : CommandHandler { public override Task ExecuteCommandAsync( ExampleAggregate aggregate, ResetCommand command, CancellationToken cancellationToken) { var executionResult = aggregate.ResetMagicNumber(); return Task.FromResult(executionResult); } } } ================================================ FILE: EventFlow.Example/Aggregates/Commands/ExampleCommand.cs ================================================ using EventFlow.Commands; using EventFlowExample.Aggregates.Events; using EventFlowExample.Models; namespace EventFlowExample.Aggregates.Commands { public class ExampleCommand : Command { public ExampleCommand( ExampleId aggregateId, //ISourceId sourceId, //optional int magicNumber) : base(aggregateId // ,sourceId //optional ) { MagicNumber = magicNumber; } public int MagicNumber { get; } } } ================================================ FILE: EventFlow.Example/Aggregates/Commands/ResetCommand.cs ================================================ using EventFlow.Aggregates.ExecutionResults; using EventFlow.Commands; using EventFlowExample.Aggregates.Events; namespace EventFlowExample.Aggregates.Commands { public class ResetCommand : Command { public ResetCommand( ExampleId aggregateId) : base(aggregateId ) { } } } ================================================ FILE: EventFlow.Example/Aggregates/Decoraters/LogCommandBus.cs ================================================ using EventFlow; using EventFlow.Aggregates; using EventFlow.Aggregates.ExecutionResults; using EventFlow.Commands; using EventFlow.Core; using System; using System.Threading; using System.Threading.Tasks; namespace EventFlowExample { public class LogCommandBus : ICommandBus { private readonly ICommandBus _internalCommandBus; public LogCommandBus(ICommandBus commandBus) { _internalCommandBus = commandBus; } public Task PublishAsync(ICommand command, CancellationToken cancellationToken) where TAggregate : IAggregateRoot where TIdentity : IIdentity where TExecutionResult : IExecutionResult { Console.WriteLine("**********" + command.AggregateId.ToString()); return _internalCommandBus.PublishAsync(command, cancellationToken); } } } ================================================ FILE: EventFlow.Example/Aggregates/Events/ExampleEvent.cs ================================================ using EventFlow.Aggregates; using EventFlow.EventStores; namespace EventFlowExample.Aggregates.Events { [EventVersion("example", 1)] public class ExampleEvent : AggregateEvent { public ExampleEvent(int magicNumber) { MagicNumber = magicNumber; } public int MagicNumber { get; } } } ================================================ FILE: EventFlow.Example/Aggregates/Events/ExampleId.cs ================================================ using EventFlow.Core; namespace EventFlowExample.Aggregates.Events { public class ExampleId : IIdentity { public ExampleId(string value) { Value = value; } public string Value { get; } } } ================================================ FILE: EventFlow.Example/Aggregates/Events/ResetEvent.cs ================================================ using EventFlow.Aggregates; using EventFlow.EventStores; namespace EventFlowExample.Aggregates.Events { [EventVersion("reset", 1)] public class ResetEvent : AggregateEvent { public ResetEvent() { } } } ================================================ FILE: EventFlow.Example/Aggregates/ExampleAggregate.cs ================================================ using EventFlow.Aggregates; using EventFlow.Aggregates.ExecutionResults; using EventFlow.Snapshots; using EventFlow.Snapshots.Strategies; using EventFlowExample.Aggregates.Events; using EventFlowExample.Aggregates.Snapshots; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace EventFlowExample.Aggregates { public class ExampleAggregate : SnapshotAggregateRoot, IEmit //optional { #region Aggregate Variables private int? _magicNumber; private int _counter = 0; #endregion public ExampleAggregate(ExampleId id) : base(id, SnapshotEveryFewVersionsStrategy.With(SnapshotEveryVersion)) { // SetSourceIdHistory(int.MaxValue); //optional; } #region Snapshots public const int SnapshotEveryVersion = 100; public IReadOnlyCollection SnapshotVersions { get; private set; } = new ExampleSnapshotVersion[] { }; protected override Task CreateSnapshotAsync(CancellationToken cancellationToken) { return Task.FromResult(new ExampleSnaphost( _magicNumber, _counter, Enumerable.Empty())); } protected override Task LoadSnapshotAsync(ExampleSnaphost snapshot, ISnapshotMetadata metadata, CancellationToken cancellationToken) { _magicNumber = snapshot.MagicNumber; _counter = snapshot.Counter; SnapshotVersions = snapshot.PreviousVersions; return Task.FromResult(0); } #endregion // Method invoked by our command public IExecutionResult SetMagicNumer(int magicNumber) { Emit(new ExampleEvent(magicNumber)); return ExecutionResult.Success(); } public IExecutionResult ResetMagicNumber() { Emit(new ResetEvent()); return ExecutionResult.Success(); } // We apply the event as part of the event sourcing system. EventFlow // provides several different methods for doing this, e.g. state objects, // the Apply method is merely the simplest public void Apply(ExampleEvent aggregateEvent) { _magicNumber = aggregateEvent.MagicNumber; _counter += _magicNumber.Value; } public void Apply(ResetEvent aggregateEvent) { _magicNumber = 0; _counter = 0; } } } ================================================ FILE: EventFlow.Example/Aggregates/ReadModels/ExampleReadModel.cs ================================================ // The MIT License (MIT) using EventFlow.Aggregates; using EventFlow.ReadStores; using EventFlowExample.Aggregates.Events; using System.Collections.Generic; namespace EventFlowExample.Aggregates.ReadModels { public class ExampleReadModel : IReadModel, IAmReadModelFor { public List MagicNumber { get; private set; } = new List(); public void Apply( IReadModelContext context, IDomainEvent domainEvent) { MagicNumber.Add(domainEvent.AggregateEvent.MagicNumber); } } } ================================================ FILE: EventFlow.Example/Aggregates/Sagas/Events/ExampleSagaCompletedEvent.cs ================================================ using EventFlow.Aggregates; using EventFlow.EventStores; namespace EventFlowExample.Aggregates.Sagas.Events { [EventVersion("example_saga_completed", 1)] public class ExampleSagaCompletedEvent : AggregateEvent { public ExampleSagaCompletedEvent() { } } } ================================================ FILE: EventFlow.Example/Aggregates/Sagas/Events/ExampleSagaStartedEvent.cs ================================================ using EventFlow.Aggregates; using EventFlow.EventStores; namespace EventFlowExample.Aggregates.Sagas.Events { [EventVersion("example_saga_started", 1)] public class ExampleSagaStartedEvent : AggregateEvent { public ExampleSagaStartedEvent(int magicNumber) { MagicNumber = magicNumber; } public int MagicNumber { get; } } } ================================================ FILE: EventFlow.Example/Aggregates/Sagas/ExampleSaga.cs ================================================ using EventFlow.Aggregates; using EventFlow.Exceptions; using EventFlow.Sagas; using EventFlow.Sagas.AggregateSagas; using EventFlowExample.Aggregates.Commands; using EventFlowExample.Aggregates.Events; using EventFlowExample.Aggregates.Sagas.Events; using System.Threading; using System.Threading.Tasks; namespace EventFlowExample.Aggregates.Sagas { public class ExampleSaga : AggregateSaga, ISagaIsStartedBy, ISagaHandles, IEmit { int MagicNumber { get; set; } public ExampleSaga(ExampleSagaId id) : base(id) { } public Task HandleAsync( IDomainEvent domainEvent, ISagaContext sagaContext, CancellationToken cancellationToken) { // This check is redundant! We do it to verify EventFlow works correctly if (State != SagaState.New) throw DomainError.With("Saga must be new!"); Emit(new ExampleSagaStartedEvent(domainEvent.AggregateEvent.MagicNumber)); Publish(new ResetCommand(domainEvent.AggregateIdentity)); return Task.CompletedTask; } public Task HandleAsync( IDomainEvent domainEvent, ISagaContext sagaContext, CancellationToken cancellationToken) { // This check is redundant! We do it to verify EventFlow works correctly if (State != SagaState.Running) throw DomainError.With("Saga must be running!"); Emit(new ExampleSagaCompletedEvent()); return Task.FromResult(0); } public void Apply(ExampleSagaStartedEvent @event) { // Update our aggregate state with relevant order details MagicNumber = @event.MagicNumber; } public void Apply(ExampleSagaCompletedEvent @event) { Complete(); } } } ================================================ FILE: EventFlow.Example/Aggregates/Sagas/ExampleSagaId.cs ================================================ using EventFlow.Sagas; using EventFlow.ValueObjects; namespace EventFlowExample.Aggregates.Sagas { public class ExampleSagaId : SingleValueObject, ISagaId { public ExampleSagaId(string value) : base(value) { } } } ================================================ FILE: EventFlow.Example/Aggregates/Sagas/SagaExtension.cs ================================================ using EventFlow; using EventFlow.Extensions; using EventFlowExample.Aggregates.Sagas.Events; namespace EventFlowExample.Aggregates.Sagas { public static class SagaExtension { public static IEventFlowOptions ConfigureSagas(this IEventFlowOptions options) { IEventFlowOptions eventFlowOptions = options.AddEvents(typeof(ExampleSagaStartedEvent)) .AddEvents(typeof(ExampleSagaCompletedEvent)) .AddSagas(typeof(ExampleSaga)) .RegisterServices(sr => { sr.RegisterType(typeof(OrderSagaLocator)); }); return eventFlowOptions; } } } ================================================ FILE: EventFlow.Example/Aggregates/Sagas/SagaLocator.cs ================================================ using EventFlow.Aggregates; using EventFlow.Sagas; using System.Threading; using System.Threading.Tasks; namespace EventFlowExample.Aggregates.Sagas { public class OrderSagaLocator : ISagaLocator { public Task LocateSagaAsync( IDomainEvent domainEvent, CancellationToken cancellationToken) { //TODO: var event_version = domainEvent.Metadata["event_version"]; var orderSagaId = new ExampleSagaId($"saga-{event_version}"); return Task.FromResult(orderSagaId); } } } ================================================ FILE: EventFlow.Example/Aggregates/Snapshots/ExampleSnapshot.cs ================================================ using EventFlow.Snapshots; using System; using System.Collections.Generic; using System.Linq; namespace EventFlowExample.Aggregates.Snapshots { [Serializable] [SnapshotVersion("example", 1)] public class ExampleSnaphost : ISnapshot { #region Variables public int? MagicNumber { get; } public int Counter { get; } public IReadOnlyCollection PreviousVersions { get; } #endregion public ExampleSnaphost(int? magicNumber, int counter, IEnumerable previousVersions) { MagicNumber = magicNumber; Counter = counter; PreviousVersions = (previousVersions ?? Enumerable.Empty()).ToList(); } } } ================================================ FILE: EventFlow.Example/Aggregates/Snapshots/ExampleSnapshotVersion.cs ================================================ namespace EventFlowExample.Aggregates.Snapshots { public enum ExampleSnapshotVersion { } } ================================================ FILE: EventFlow.Example/Aggregates/Subscribers/ExampleSyncSubscriber.cs ================================================ using System; using System.Threading; using System.Threading.Tasks; using EventFlow.Aggregates; using EventFlow.Subscribers; using EventFlowExample.Aggregates.Events; namespace EventFlowExample.Aggregates.Subscribers { public class ExampleSyncSubscriber : ISubscribeSynchronousTo { public Task HandleAsync(IDomainEvent domainEvent, CancellationToken cancellationToken) { return Task.Run(() => { Console.WriteLine("++++++++" + domainEvent.ToString()); }); } } } ================================================ FILE: EventFlow.Example/EventFlow.Example.csproj ================================================ Exe netcoreapp2.2 Oktay Kır EventFlowExample DEBUG;TRACE all runtime; build; native; contentfiles; analyzers; buildtransitive ================================================ FILE: EventFlow.Example/Jobs/ExampleJobs.cs ================================================ using EventFlow.Configuration; using EventFlow.Jobs; using System; using System.Threading; using System.Threading.Tasks; namespace EventFlowExample.Jobs { [JobVersion("ExampleJob", 1)] public class ExampleJob : IJob { public ExampleJob(string message) { Message = message; } public string Message { get; } public Task ExecuteAsync( IResolver resolver, CancellationToken cancellationToken) { Console.WriteLine(Message); return Task.CompletedTask; } } } ================================================ FILE: EventFlow.Example/Models/CommandReturnResult.cs ================================================ using EventFlow.Aggregates; using EventFlow.Aggregates.ExecutionResults; namespace EventFlowExample.Models { public class CommandReturnResult : ExecutionResult { public CommandReturnResult(bool isSuccess, IAggregateRoot aggregateRoot) { IsSuccess = isSuccess; AggregateRoot = aggregateRoot; } public override bool IsSuccess { get; } public IAggregateRoot AggregateRoot { get; } } } ================================================ FILE: EventFlow.Example/Program.cs ================================================ namespace EventFlowExample { class Program { static void Main(string[] args) { new PublishCommand().PublishCommandAsync().Wait(); } } } ================================================ FILE: EventFlow.Example/PublishCommand.cs ================================================ using Autofac; using EventFlow; using EventFlow.Aggregates.ExecutionResults; using EventFlow.Autofac.Extensions; using EventFlow.Configuration; using EventFlow.EventStores; using EventFlow.Extensions; using EventFlow.MongoDB.Extensions; using EventFlow.RabbitMQ; using EventFlow.RabbitMQ.Extensions; using EventFlow.Snapshots.Strategies; using EventFlowExample.Aggregates.CommandHandlers; using EventFlowExample.Aggregates.Commands; using EventFlowExample.Aggregates.Events; using EventFlowExample.Aggregates.Snapshots; using EventFlowExample.Jobs; using MongoDB.Driver; using System; using System.Diagnostics; using System.Threading; using System.Threading.Tasks; namespace EventFlowExample { public class PublishCommand { #region Variables ICommandBus CommandBus { get; set; } private const string SNAPSHOT_CONTAINER_NAME = "snapshots"; #endregion public PublishCommand() { } public static ExampleId GetStreamName(string tenantName, string eventName, Guid? aggregateId = null) => new ExampleId($"{tenantName.ToLowerInvariant()}_{eventName.ToLowerInvariant()}-{(aggregateId.HasValue ? aggregateId.ToString() : Guid.NewGuid().ToString())}"); void DecorateCommandBus(IServiceRegistration sr) { sr.Decorate((r, cb) => new LogCommandBus(cb)); } public async Task PublishCommandAsync() { var client = new MongoClient("mongodb://localhost:27017"); using (var resolver = EventFlowOptions.New .UseAutofacContainerBuilder(new ContainerBuilder()) // Must be the first line! .Configure(c => c.ThrowSubscriberExceptions = true) .AddEvents(typeof(ExampleEvent)) .AddEvents(typeof(ResetEvent)) .AddCommands(typeof(ExampleCommand)) .AddCommands(typeof(ResetCommand)) .AddCommandHandlers(typeof(ExampleCommandHandler)) .AddCommandHandlers(typeof(ResetCommandHandler)) .ConfigureEventStore() .ConfigureMongoDb(client, SNAPSHOT_CONTAINER_NAME) .AddSnapshots(typeof(ExampleSnaphost)) .UseMongoDbSnapshotStore() .RegisterServices(sr => sr.Register(i => SnapshotEveryFewVersionsStrategy.Default)) .RegisterServices(DecorateCommandBus) .PublishToRabbitMq(RabbitMqConfiguration.With(new Uri(@"amqp://test:test@localhost:5672"), true, 4, "eventflow")) //.ConfigureSagas() //.UseNullLog() //.UseInMemoryReadStoreFor() .Configure(c => c.IsAsynchronousSubscribersEnabled = true) //.AddAsynchronousSubscriber() //.RegisterServices(s => { // s.Register(Lifetime.Singleton); // s.Register(Lifetime.Singleton); //}) //.AddSubscribers(new Type[] { typeof(ExampleSyncSubscriber) }) // .UseHangfireJobScheduler() .AddJobs(typeof(ExampleJob)) .CreateResolver()) { Int32 magicNumber = 2; CommandBus = resolver.Resolve(); var clock = new Stopwatch(); clock.Start(); ExampleId exampleId = GetStreamName("Tenant", "EXAMPLE"); for (int i = 0; i < 1; i++) { IExecutionResult result = await CommandBus.PublishAsync( new ExampleCommand(exampleId, magicNumber), CancellationToken.None) .ConfigureAwait(false); #region Comments //result.IsSuccess.Should().BeTrue(); //IAggregateStore aggregateStore = resolver.Resolve(); //var @object = aggregateStore.LoadAsync(exampleId, CancellationToken.None); ////Obsolete ////IEventStore eventStore = resolver.Resolve(); ////var aggregate = await eventStore.LoadAggregateAsync(exampleId, CancellationToken.None); ////state of our aggregate root //var queryProcessor = resolver.Resolve(); //var result = await queryProcessor.ProcessAsync( // new ReadModelByIdQuery(exampleId), // CancellationToken.None) // .ConfigureAwait(false); //// Verify that the read model has the expected magic number //exampleReadModel.MagicNumber.Should().Be(42); #endregion } clock.Stop(); Console.WriteLine("Duration: " + clock.ElapsedMilliseconds + "ms"); } Console.ReadLine(); } } } ================================================ FILE: EventFlow.Tests/EventFlow.Tests.csproj ================================================ netcoreapp3.1 false all runtime; build; native; contentfiles; analyzers; buildtransitive ================================================ FILE: EventFlow.Tests/IntegrationTestBase.cs ================================================ using EventFlow.Configuration; using System; using EventFlowExample; using MongoDB.Driver; namespace EventFlow.Tests { public abstract class IntegrationTestBase : IDisposable { #region Variables public ICommandBus CommandBus { get; set; } public const string SNAPSHOT_CONTAINER_NAME = "snapshots"; public Uri RabbitMqUri = new Uri(@"amqp://test:test@localhost:5672"); public MongoClient MongoClient => new MongoClient("mongodb://localhost:27017"); #endregion public void DecorateCommandBus(IServiceRegistration sr) { sr.Decorate((r, cb) => new LogCommandBus(cb)); } public virtual void Dispose(bool isDisposing) { if (!isDisposing) return; } public void Dispose() { Dispose(true); } } } ================================================ FILE: EventFlow.Tests/IntegrationTests.cs ================================================ using Autofac; using CommandLine.Text; using EventFlow.Aggregates; using EventFlow.Autofac.Extensions; using EventFlow.EventStores; using EventFlow.Extensions; using EventFlow.MongoDB.Extensions; using EventFlow.Queries; using EventFlow.RabbitMQ; using EventFlow.RabbitMQ.Extensions; using EventFlow.Snapshots.Strategies; using EventFlowExample; using EventFlowExample.Aggregates; using EventFlowExample.Aggregates.CommandHandlers; using EventFlowExample.Aggregates.Commands; using EventFlowExample.Aggregates.Events; using EventFlowExample.Aggregates.ReadModels; using EventFlowExample.Aggregates.Snapshots; using EventFlowExample.Jobs; using EventFlowExample.Models; using FluentAssertions; using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using Xunit; namespace EventFlow.Tests { public class IntegrationTests : IntegrationTestBase { [Fact] public async Task PassingTest() { using (var resolver = EventFlowOptions.New .UseAutofacContainerBuilder(new ContainerBuilder()) .Configure(c => c.ThrowSubscriberExceptions = true) .AddEvents(typeof(ExampleEvent)) .AddEvents(typeof(ResetEvent)) .AddCommands(typeof(ExampleCommand)) .AddCommands(typeof(ResetCommand)) .AddCommandHandlers(typeof(ExampleCommandHandler)) .AddCommandHandlers(typeof(ResetCommandHandler)) .ConfigureEventStore() .ConfigureMongoDb(MongoClient, SNAPSHOT_CONTAINER_NAME) .AddSnapshots(typeof(ExampleSnaphost)) .UseMongoDbSnapshotStore() .UseInMemoryReadStoreFor() .RegisterServices(sr => sr.Register(i => SnapshotEveryFewVersionsStrategy.Default)) .RegisterServices(DecorateCommandBus) .PublishToRabbitMq(RabbitMqConfiguration.With(RabbitMqUri, true, 4, "eventflow")) .Configure(c => c.IsAsynchronousSubscribersEnabled = true) .AddJobs(typeof(ExampleJob)) .CreateResolver()) { Int32 magicNumber = 2; CommandBus = resolver.Resolve(); ExampleId exampleId = PublishCommand.GetStreamName("Tenant", "EXAMPLE"); CommandReturnResult result = await CommandBus.PublishAsync( new ExampleCommand(exampleId, magicNumber), CancellationToken.None) .ConfigureAwait(false); IAggregateStore aggregateStore = resolver.Resolve(); var @aggregate = await aggregateStore.LoadAsync(exampleId, CancellationToken.None); //Command side result.IsSuccess.Should().BeTrue(); result.AggregateRoot.Should().NotBeNull(); result.AggregateRoot.Version.Should().Be(1); result.AggregateRoot.Name.Value.Should().Be("ExampleAggregate"); result.AggregateRoot.GetIdentity().Value.Should().Be(exampleId.Value); @aggregate.Should().NotBeNull(); result.AggregateRoot.Should().Equals(@aggregate); } } [Fact] public async Task ReadModelTest() { using (var resolver = EventFlowOptions.New .UseAutofacContainerBuilder(new ContainerBuilder()) .Configure(c => c.ThrowSubscriberExceptions = true) .AddEvents(typeof(ExampleEvent)) .AddEvents(typeof(ResetEvent)) .AddCommands(typeof(ExampleCommand)) .AddCommands(typeof(ResetCommand)) .AddCommandHandlers(typeof(ExampleCommandHandler)) .AddCommandHandlers(typeof(ResetCommandHandler)) .ConfigureEventStore() .ConfigureMongoDb(MongoClient, SNAPSHOT_CONTAINER_NAME) .AddSnapshots(typeof(ExampleSnaphost)) .UseMongoDbSnapshotStore() .UseInMemoryReadStoreFor() .RegisterServices(sr => sr.Register(i => SnapshotEveryFewVersionsStrategy.Default)) .RegisterServices(DecorateCommandBus) .PublishToRabbitMq(RabbitMqConfiguration.With(RabbitMqUri, true, 4, "eventflow")) .Configure(c => c.IsAsynchronousSubscribersEnabled = true) .AddJobs(typeof(ExampleJob)) .CreateResolver()) { Int32 magicNumber = 2; CommandBus = resolver.Resolve(); ExampleId exampleId = PublishCommand.GetStreamName("Tenant", "EXAMPLE"); CommandReturnResult result = await CommandBus.PublishAsync( new ExampleCommand(exampleId, magicNumber), CancellationToken.None) .ConfigureAwait(false); var queryProcessor = resolver.Resolve(); ExampleReadModel exampleReadModel = await queryProcessor.ProcessAsync( new ReadModelByIdQuery(exampleId), CancellationToken.None) .ConfigureAwait(false); exampleReadModel.Should().NotBeNull(); exampleReadModel.MagicNumber.Should().ContainSingle(); exampleReadModel.MagicNumber.First().Should().Be(2); } } } } ================================================ FILE: EventFlowExamples.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 16 VisualStudioVersion = 16.0.30104.148 MinimumVisualStudioVersion = 10.0.40219.1 Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EventFlow.Example", "EventFlow.Example\EventFlow.Example.csproj", "{F67006E8-2887-4B2C-8049-63BDC8AE0F00}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EventStore", "EventStore\EventStore.csproj", "{DF87F930-BF1C-4932-9C51-75591E14FEAE}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "EventFlow.Tests", "EventFlow.Tests\EventFlow.Tests.csproj", "{2B5AB9C1-0C47-4475-A3F9-3A72C34E15F6}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU Release|Any CPU = Release|Any CPU EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {F67006E8-2887-4B2C-8049-63BDC8AE0F00}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {F67006E8-2887-4B2C-8049-63BDC8AE0F00}.Debug|Any CPU.Build.0 = Debug|Any CPU {F67006E8-2887-4B2C-8049-63BDC8AE0F00}.Release|Any CPU.ActiveCfg = Release|Any CPU {F67006E8-2887-4B2C-8049-63BDC8AE0F00}.Release|Any CPU.Build.0 = Release|Any CPU {DF87F930-BF1C-4932-9C51-75591E14FEAE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {DF87F930-BF1C-4932-9C51-75591E14FEAE}.Debug|Any CPU.Build.0 = Debug|Any CPU {DF87F930-BF1C-4932-9C51-75591E14FEAE}.Release|Any CPU.ActiveCfg = Release|Any CPU {DF87F930-BF1C-4932-9C51-75591E14FEAE}.Release|Any CPU.Build.0 = Release|Any CPU {2B5AB9C1-0C47-4475-A3F9-3A72C34E15F6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {2B5AB9C1-0C47-4475-A3F9-3A72C34E15F6}.Debug|Any CPU.Build.0 = Debug|Any CPU {2B5AB9C1-0C47-4475-A3F9-3A72C34E15F6}.Release|Any CPU.ActiveCfg = Release|Any CPU {2B5AB9C1-0C47-4475-A3F9-3A72C34E15F6}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {9DC7F542-AB1D-4C23-81B9-1889AEC99EEF} EndGlobalSection EndGlobal ================================================ FILE: EventStore/EventStore.csproj ================================================ netstandard2.0 ================================================ FILE: EventStore/EventStoreExtension.cs ================================================ using System; using System.Data.Common; using EventFlow; using EventFlow.EventStores.EventStore.Extensions; using EventFlow.Extensions; using EventFlow.MetadataProviders; using EventStore.ClientAPI; using EventStore.ClientAPI.SystemData; namespace EventFlow.EventStores { public static class EventStoreExtension { public static IEventFlowOptions ConfigureEventStore(this IEventFlowOptions options) { string eventStoreUrl = "tcp://localhost:1113"; string connectionString = $"ConnectTo={eventStoreUrl}; HeartBeatTimeout=500"; Uri eventStoreUri = GetUriFromConnectionString(connectionString); var connectionSettings = ConnectionSettings.Create() .EnableVerboseLogging() .KeepReconnecting() .KeepRetrying() .SetDefaultUserCredentials(new UserCredentials("admin", "changeit")) .Build(); IEventFlowOptions eventFlowOptions = options .AddMetadataProvider() .UseEventStoreEventStore(eventStoreUri, connectionSettings); return eventFlowOptions; } private static Uri GetUriFromConnectionString(string connectionString) { DbConnectionStringBuilder builder = new DbConnectionStringBuilder { ConnectionString = connectionString }; string connectTo = (string)builder["ConnectTo"]; return connectTo == null ? null : new Uri(connectTo); } } } ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [2019] [Oktay Kır] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ # EventFlow.Example ![Hits](https://hitcounter.pythonanywhere.com/count/tag.svg?url=https://github.com/OKTAYKIR/EventFlow.Example) ![GitHub issues](https://img.shields.io/github/issues/OKTAYKIR/EventFlow.Example) ![Build Status](https://github.com/OKTAYKIR/EventFlow.Example/workflows/CI/badge.svg) [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg)](#contributing) DDD+CQRS+Event-sourcing examples using EventFlow following CQRS-ES architecture. It is configured with RabbitMQ, MongoDB(Snapshot store), PostgreSQL(Read store), EventStore(GES). It's targeted to .Net Core 2.2 and include [docker compose file](/build/docker-compose.yml). ## Event Sourcing/CQRS Architecture The most common CQRS/ES architecture would look like following diagram ![OverallArchitecture](https://github.com/OKTAYKIR/EventFlow.Example/blob/master/Images/architecture_diagram.png) The example consists of the following concepts, each shown below - Aggregates - Command bus and commands - Synchronous subscriber - Event store ([GES](https://eventstore.com/)) - In-memory read model. - Snapshots ([MongoDb](https://www.mongodb.com/)) - Sagas - Event publising (In-memory, [RabbitMq](https://www.rabbitmq.com/)) - Metadata - Command bus decorator, custom value object, custom execution result, ... ## Configuration ```csharp var resolver = EventFlowOptions.New .UseAutofacContainerBuilder(new ContainerBuilder()) .Configure(c => c.ThrowSubscriberExceptions = true) .AddEvents(typeof(ExampleEvent)) .AddEvents(typeof(ResetEvent)) .AddCommands(typeof(ExampleCommand)) .AddCommands(typeof(ResetCommand)) .AddCommandHandlers(typeof(ExampleCommandHandler)) .AddCommandHandlers(typeof(ResetCommandHandler)) .ConfigureEventStore() .ConfigureMongoDb(client, SNAPSHOT_CONTAINER_NAME) .AddSnapshots(typeof(ExampleSnaphost)) .UseMongoDbSnapshotStore() .RegisterServices(sr => sr.Register(i => SnapshotEveryFewVersionsStrategy.Default)) .RegisterServices(DecorateCommandBus) .PublishToRabbitMq(RabbitMqConfiguration.With(new Uri(@"amqp://test:test@localhost:5672"), true, 4, "eventflow")) .UseInMemoryReadStoreFor() .AddJobs(typeof(ExampleJob)) .CreateResolver()); ``` ## 📦 Stack * [EventFlow](https://github.com/eventflow/EventFlow) * [EventStore](https://eventstore.com) * [RabbitMQ](https://www.rabbitmq.com) * [MongoDB](https://www.mongodb.com) * [PostgreSQL](https://www.postgresql.org) * [Docker](https://www.docker.com) ## 🤝 Contributing 1. Fork it ( https://github.com/OKTAYKIR/EventFlow.Example/fork ) 2. Create your feature branch (`git checkout -b my-new-feature`) 3. Commit your changes (`git commit -am 'Add some feature'`) 4. Push to the branch (`git push origin my-new-feature`) 5. Create a new Pull Request ## ✨ Contributors ![GitHub Contributors Image](https://contrib.rocks/image?repo=OKTAYKIR/EventFlow.Example) ## Show your support Please ⭐️ this repository if this project helped you! ## 📝 License Apache-2.0 © [Oktay Kır](https://www.linkedin.com/in/oktay-kır-phd-9402955a) ================================================ FILE: SyncEventHandler/ExampleAggregate.cs ================================================ //// The MIT License (MIT) //// //// Copyright (c) 2015-2017 Rasmus Mikkelsen //// Copyright (c) 2015-2017 eBay Software Foundation //// https://github.com/eventflow/EventFlow //// //// Permission is hereby granted, free of charge, to any person obtaining a copy of //// this software and associated documentation files (the "Software"), to deal in //// the Software without restriction, including without limitation the rights to //// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of //// the Software, and to permit persons to whom the Software is furnished to do so, //// subject to the following conditions: //// //// The above copyright notice and this permission notice shall be included in all //// copies or substantial portions of the Software. //// //// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS //// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR //// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER //// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN //// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. //using EventFlow.Aggregates; //using EventFlow.Aggregates.ExecutionResults; //using SyncEventHandler; //namespace EventFlow.Documentation.GettingStarted //{ // /// The aggregate root // public class ExampleAggregate : // AggregateRoot, // IEmit //optional // { // private int? _magicNumber; // public ExampleAggregate(WizloId id) : base(id) { // // SetSourceIdHistory(int.MaxValue); //optional; // } // // Method invoked by our command // public IExecutionResult SetMagicNumer(int magicNumber) // { // if (_magicNumber.HasValue) // return ExecutionResult.Failed("Magic number already set"); // Emit(new ExampleEvent(magicNumber)); // return ExecutionResult.Success(); // } // // We apply the event as part of the event sourcing system. EventFlow // // provides several different methods for doing this, e.g. state objects, // // the Apply method is merely the simplest // public void Apply(ExampleEvent aggregateEvent) // { // _magicNumber = aggregateEvent.MagicNumber; // } // } //} ================================================ FILE: SyncEventHandler/ExampleEvent.cs ================================================ //// The MIT License (MIT) //// //// Copyright (c) 2015-2017 Rasmus Mikkelsen //// Copyright (c) 2015-2017 eBay Software Foundation //// https://github.com/eventflow/EventFlow //// //// Permission is hereby granted, free of charge, to any person obtaining a copy of //// this software and associated documentation files (the "Software"), to deal in //// the Software without restriction, including without limitation the rights to //// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of //// the Software, and to permit persons to whom the Software is furnished to do so, //// subject to the following conditions: //// //// The above copyright notice and this permission notice shall be included in all //// copies or substantial portions of the Software. //// //// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS //// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR //// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER //// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN //// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. //// //using EventFlow.Aggregates; //using EventFlow.EventStores; //using SyncEventHandler; //namespace EventFlow.Documentation.GettingStarted //{ // /// A basic event containing some information // [EventVersion("example", 1)] // public class ExampleEvent : // AggregateEvent // { // public ExampleEvent(int magicNumber) // { // MagicNumber = magicNumber; // } // public int MagicNumber { get; } // } //} ================================================ FILE: SyncEventHandler/ExampleSyncSubscriber.cs ================================================ // The MIT License (MIT) // // Copyright (c) 2015-2017 Rasmus Mikkelsen // Copyright (c) 2015-2017 eBay Software Foundation // https://github.com/eventflow/EventFlow // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation files (the "Software"), to deal in // the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do so, // subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS // FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER // IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN // CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. using System; using System.Threading; using System.Threading.Tasks; using EventFlow.Aggregates; using EventFlow.Aggregates.ExecutionResults; using EventFlow.Subscribers; using EventFlowExample.Aggregates; using EventFlowExample.Aggregates.Events; using SyncEventHandler; namespace EventFlow.Documentation.GettingStarted { public class ExampleSyncSubscriber : ISubscribeSynchronousTo { public Task HandleAsync(IDomainEvent domainEvent, CancellationToken cancellationToken) { return Task.Run(() => { Console.WriteLine("+++++++++++++++++++++++++++++++++++++++++++++++" + domainEvent.ToString()); }); } } } ================================================ FILE: SyncEventHandler/Program.cs ================================================ using EventFlow; using EventFlow.Aggregates; using EventFlow.Configuration; using EventFlow.EventStores; using EventFlow.Extensions; using EventFlow.Hangfire.Extensions; using EventFlow.RabbitMQ; using EventFlow.RabbitMQ.Integrations; using EventFlow.Subscribers; using EventFlowExample.Aggregates; using EventFlowExample.Aggregates.Events; using EventFlowExample.Jobs; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using RabbitMQ.Client; using RabbitMQ.Client.Events; using System; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace SyncEventHandler { class Program { public static async Task Main(string[] args) { var builder = new HostBuilder() .ConfigureAppConfiguration((host, config) => { config.SetBasePath(Directory.GetCurrentDirectory()); }) .ConfigureServices( (hostcontext, services) => { EventFlowOptions.New .UseHangfireJobScheduler() .AddJobs(typeof(ExampleJob)); //.Configure(cfg => cfg.IsAsynchronousSubscribersEnabled = true) //.PublishToRabbitMq(RabbitMqConfiguration.With(new Uri(@"amqp://test:test@localhost:5672"), true, 4, "eventflow")) //.AddAsynchronousSubscriber() //.RegisterServices(s => //{ // s.Register(Lifetime.Singleton); // s.Register(Lifetime.Singleton); //}); }) .ConfigureLogging((hostingContext, logging) => { }); await builder.RunConsoleAsync(); Console.ReadLine(); } } } ================================================ FILE: SyncEventHandler/SyncEventHandler.csproj ================================================ Exe netcoreapp2.2 ================================================ FILE: _config.yml ================================================ theme: jekyll-theme-slate ================================================ FILE: build/docker-compose.yml ================================================ version: '3' services: rabbitmq: image: "rabbitmq:3-management" container_name: rabbitmq environment: RABBITMQ_ERLANG_COOKIE: "SWQOKODSQALRPCLNMEQG" RABBITMQ_DEFAULT_USER: "test" RABBITMQ_DEFAULT_PASS: "test" RABBITMQ_DEFAULT_VHOST: "/" ports: - "15672:15672" - "5672:5672" labels: NAME: "rabbitmq" eventstore: image: eventstore/eventstore:release-5.0.1 container_name: eventstore ports: - 2113:2113 - 1113:1113 restart: always healthcheck: test: ["CMD-SHELL", "curl -sf http://localhost:2113/stats || exit 1"] interval: 5s timeout: 2s environment: - EVENTSTORE_RUN_PROJECTIONS=all - EVENTSTORE_START_STANDARD_PROJECTIONS=TRUE snapshot_store: image: mongo:latest ports: - 27017:27017 readstore: image: postgres:10.6-alpine container_name: readstore environment: - POSTGRES_DB=testdb - POSTGRES_USER=dbadmin - POSTGRES_PASSWORD=dbadmin command: - -c - max_prepared_transactions=100 ports: - "5433:5432"