Full Code of OKTAYKIR/EventFlow.Example for AI

master 5f1ea82a6317 cached
42 files
66.5 KB
15.9k tokens
75 symbols
1 requests
Download .txt
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<ExampleAggregate, ExampleId, CommandReturnResult, ExampleCommand>
    {
        private readonly IJobScheduler _jobScheduler;

        public ExampleCommandHandler(IJobScheduler jobScheduler)
        {
            _jobScheduler = jobScheduler;
        }

        public override async Task<CommandReturnResult> 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<ExampleAggregate, ExampleId, IExecutionResult, ResetCommand>
    {
        public override Task<IExecutionResult> 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<ExampleAggregate, ExampleId, CommandReturnResult>
    {
        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<ExampleAggregate, ExampleId, IExecutionResult>
    {
        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<TExecutionResult> PublishAsync<TAggregate, TIdentity, TExecutionResult>(ICommand<TAggregate, TIdentity, TExecutionResult> command, CancellationToken cancellationToken)
            where TAggregate : IAggregateRoot<TIdentity>
            where TIdentity : IIdentity
            where TExecutionResult : IExecutionResult
        {
            Console.WriteLine("**********" + command.AggregateId.ToString());
            return _internalCommandBus.PublishAsync<TAggregate, TIdentity, TExecutionResult>(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<ExampleAggregate, ExampleId>
    {
        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<ExampleAggregate, ExampleId>
    {
        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<ExampleAggregate, ExampleId, ExampleSnaphost>,
                                    IEmit<ExampleEvent> //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<ExampleSnapshotVersion> SnapshotVersions { get; private set; } = new ExampleSnapshotVersion[] { };

        protected override Task<ExampleSnaphost> CreateSnapshotAsync(CancellationToken cancellationToken)
        {
            return Task.FromResult(new ExampleSnaphost(
                                   _magicNumber,
                                   _counter,
                                   Enumerable.Empty<ExampleSnapshotVersion>()));
        }

        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<ExampleAggregate, ExampleId, ExampleEvent>
    {
        public List<int> MagicNumber { get; private set; } = new List<int>();

        public void Apply(
            IReadModelContext context,
            IDomainEvent<ExampleAggregate, ExampleId, ExampleEvent> 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<ExampleSaga, ExampleSagaId>
    {
        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<ExampleSaga, ExampleSagaId>
    {
        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<ExampleSaga, ExampleSagaId, OrderSagaLocator>,
                               ISagaIsStartedBy<ExampleAggregate, ExampleId, ExampleEvent>,
                               ISagaHandles<ExampleAggregate, ExampleId, ResetEvent>,
                               IEmit<ExampleSagaStartedEvent>
    {
         int MagicNumber { get; set; }
       
         public ExampleSaga(ExampleSagaId id) : base(id)
         {
         }
       
         public Task HandleAsync(
             IDomainEvent<ExampleAggregate, ExampleId, ExampleEvent> 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<ExampleAggregate, ExampleId, ResetEvent> 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<string>, 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<ISagaId> LocateSagaAsync(
          IDomainEvent domainEvent,
          CancellationToken cancellationToken)
        {
            //TODO:
            var event_version = domainEvent.Metadata["event_version"];
            var orderSagaId = new ExampleSagaId($"saga-{event_version}");

            return Task.FromResult<ISagaId>(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<ExampleSnapshotVersion> PreviousVersions { get; }
        #endregion

        public ExampleSnaphost(int? magicNumber,    
                               int counter, 
                               IEnumerable<ExampleSnapshotVersion> previousVersions)
        {
            MagicNumber = magicNumber;
            Counter = counter;
            PreviousVersions = (previousVersions ?? Enumerable.Empty<ExampleSnapshotVersion>()).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<ExampleAggregate, ExampleId, ExampleEvent>
    {
        public Task HandleAsync(IDomainEvent<ExampleAggregate, ExampleId, ExampleEvent> domainEvent, CancellationToken cancellationToken)
        {
            return Task.Run(() =>
            { 
                Console.WriteLine("++++++++" + domainEvent.ToString());
            });
        }            
    }
}

================================================
FILE: EventFlow.Example/EventFlow.Example.csproj
================================================
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.2</TargetFramework>
    <Authors>Oktay Kır</Authors>
	<RootNamespace>EventFlowExample</RootNamespace>
  </PropertyGroup>
  
 <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <DefineConstants>DEBUG;TRACE</DefineConstants>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Autofac" Version="4.9.4" />
    <PackageReference Include="BenchmarkDotNet" Version="0.12.0" />
    <PackageReference Include="coverlet.collector" Version="1.1.0">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
    <PackageReference Include="EventFlow" Version="0.77.4077" />
    <PackageReference Include="EventFlow.Autofac" Version="0.77.4023" />
    <PackageReference Include="EventFlow.MongoDB" Version="0.76.4014" />
    <PackageReference Include="EventFlow.RabbitMQ" Version="0.77.4023" />
    <PackageReference Include="EventStore.Client" Version="5.0.5" />
    <PackageReference Include="FluentAssertions" Version="5.9.0" />
    <PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="3.0.0" />
    <PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.9.5" />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\EventStore\EventStore.csproj" />
  </ItemGroup>
</Project>


================================================
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<ICommandBus>((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<Aggregates.ReadModels.ExampleReadModel>()
                                                  .Configure(c => c.IsAsynchronousSubscribersEnabled = true)
                                                  //.AddAsynchronousSubscriber<ExampleAggregate, Aggregates.Events.ExampleId, ExampleEvent, RabbitMqConsumePersistanceService>()
                                                  //.RegisterServices(s => {
                                                  //    s.Register<IHostedService, RabbitConsumePersistenceService>(Lifetime.Singleton);
                                                  //    s.Register<IHostedService, RabbitMqConsumePersistanceService>(Lifetime.Singleton);
                                                  //})
                                                  //.AddSubscribers(new Type[] { typeof(ExampleSyncSubscriber) })
                                                 // .UseHangfireJobScheduler()
                                                  .AddJobs(typeof(ExampleJob))
                                                  .CreateResolver())
            {
                Int32 magicNumber = 2;
                CommandBus = resolver.Resolve<ICommandBus>();

                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<IAggregateStore>();
                    //var @object = aggregateStore.LoadAsync<ExampleAggregate, ExampleId>(exampleId, CancellationToken.None);

                    ////Obsolete
                    ////IEventStore eventStore = resolver.Resolve<IEventStore>();
                    ////var aggregate = await eventStore.LoadAggregateAsync<ExampleAggregate, ExampleId>(exampleId, CancellationToken.None);

                    ////state of our aggregate root
                    //var queryProcessor = resolver.Resolve<IQueryProcessor>();
                    //var result = await queryProcessor.ProcessAsync(
                    //     new ReadModelByIdQuery<ExampleReadModel>(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
================================================
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>

    <IsPackable>false</IsPackable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="EventFlow" Version="0.77.4077" />
    <PackageReference Include="EventFlow.Autofac" Version="0.77.4023" />
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.5.0" />
    <PackageReference Include="MongoDB.Driver" Version="2.10.4" />
    <PackageReference Include="xunit" Version="2.4.0" />
    <PackageReference Include="xunit.runner.visualstudio" Version="2.4.0" />
    <PackageReference Include="coverlet.collector" Version="1.1.0">
      <PrivateAssets>all</PrivateAssets>
      <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
    </PackageReference>
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\EventFlow.Example\EventFlow.Example.csproj" />
  </ItemGroup>

</Project>


================================================
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<ICommandBus>((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<ExampleReadModel>()
                                                  .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<ICommandBus>();
                
                ExampleId exampleId = PublishCommand.GetStreamName("Tenant", "EXAMPLE");

                CommandReturnResult result = await CommandBus.PublishAsync(
                       new ExampleCommand(exampleId, magicNumber), CancellationToken.None)
                       .ConfigureAwait(false);

                IAggregateStore aggregateStore = resolver.Resolve<IAggregateStore>();
                var @aggregate = await aggregateStore.LoadAsync<ExampleAggregate, ExampleId>(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<ExampleReadModel>()
                                                  .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<ICommandBus>();

                ExampleId exampleId = PublishCommand.GetStreamName("Tenant", "EXAMPLE");

                CommandReturnResult result = await CommandBus.PublishAsync(
                       new ExampleCommand(exampleId, magicNumber), CancellationToken.None)
                       .ConfigureAwait(false);

                var queryProcessor = resolver.Resolve<IQueryProcessor>();
                ExampleReadModel exampleReadModel = await queryProcessor.ProcessAsync(
                     new ReadModelByIdQuery<ExampleReadModel>(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
================================================
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="EventFlow.EventStores.EventStore" Version="0.77.4023" />
  </ItemGroup>

</Project>


================================================
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<AddGuidMetadataProvider>()
                .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<Aggregates.ReadModels.ExampleReadModel>()
    .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<ExampleAggregate, WizloId>,
//        IEmit<ExampleEvent> //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<ExampleAggregate, WizloId>
//    {
//        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<ExampleAggregate, WizloId, ExampleEvent>
    {
        public Task HandleAsync(IDomainEvent<ExampleAggregate, WizloId, ExampleEvent> 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<ExampleAggregate, WizloId, ExampleEvent, RabbitMqConsumePersistanceService>()
                            //.RegisterServices(s =>
                            //{
                            //    s.Register<IHostedService, RabbitConsumePersistenceService>(Lifetime.Singleton);
                            //    s.Register<IHostedService, RabbitMqConsumePersistanceService>(Lifetime.Singleton);
                            //});
                   })
               .ConfigureLogging((hostingContext, logging) => { });

            await builder.RunConsoleAsync();

            Console.ReadLine();
        }
    }
}


================================================
FILE: SyncEventHandler/SyncEventHandler.csproj
================================================
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.2</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="EventFlow" Version="0.77.4077" />
    <PackageReference Include="EventFlow.RabbitMQ" Version="0.77.4023" />
    <PackageReference Include="Microsoft.Extensions.Hosting" Version="3.0.0" />
    <PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="3.0.0" />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\EventFlow.Example\EventFlow.Example.csproj" />
  </ItemGroup>

</Project>


================================================
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"

Download .txt
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
Download .txt
SYMBOL INDEX (75 symbols across 28 files)

FILE: EventFlow.Example/Aggregates/CommandHandlers/ExampleCommandHandler.cs
  class ExampleCommandHandler (line 13) | public class ExampleCommandHandler :
    method ExampleCommandHandler (line 18) | public ExampleCommandHandler(IJobScheduler jobScheduler)
    method ExecuteCommandAsync (line 23) | public override async Task<CommandReturnResult> ExecuteCommandAsync(

FILE: EventFlow.Example/Aggregates/CommandHandlers/ResetCommandHandler.cs
  class ResetCommandHandler (line 10) | public class ResetCommandHandler : CommandHandler<ExampleAggregate, Exam...
    method ExecuteCommandAsync (line 12) | public override Task<IExecutionResult> ExecuteCommandAsync(

FILE: EventFlow.Example/Aggregates/Commands/ExampleCommand.cs
  class ExampleCommand (line 7) | public class ExampleCommand : Command<ExampleAggregate, ExampleId, Comma...
    method ExampleCommand (line 9) | public ExampleCommand(

FILE: EventFlow.Example/Aggregates/Commands/ResetCommand.cs
  class ResetCommand (line 7) | public class ResetCommand : Command<ExampleAggregate, ExampleId, IExecut...
    method ResetCommand (line 9) | public ResetCommand(

FILE: EventFlow.Example/Aggregates/Decoraters/LogCommandBus.cs
  class LogCommandBus (line 12) | public class LogCommandBus : ICommandBus
    method LogCommandBus (line 16) | public LogCommandBus(ICommandBus commandBus)
    method PublishAsync (line 21) | public Task<TExecutionResult> PublishAsync<TAggregate, TIdentity, TExe...

FILE: EventFlow.Example/Aggregates/Events/ExampleEvent.cs
  class ExampleEvent (line 6) | [EventVersion("example", 1)]
    method ExampleEvent (line 9) | public ExampleEvent(int magicNumber)

FILE: EventFlow.Example/Aggregates/Events/ExampleId.cs
  class ExampleId (line 5) | public class ExampleId : IIdentity
    method ExampleId (line 7) | public ExampleId(string value)

FILE: EventFlow.Example/Aggregates/Events/ResetEvent.cs
  class ResetEvent (line 6) | [EventVersion("reset", 1)]
    method ResetEvent (line 9) | public ResetEvent()

FILE: EventFlow.Example/Aggregates/ExampleAggregate.cs
  class ExampleAggregate (line 14) | public class ExampleAggregate : SnapshotAggregateRoot<ExampleAggregate, ...
    method ExampleAggregate (line 22) | public ExampleAggregate(ExampleId id) : base(id, SnapshotEveryFewVersi...
    method CreateSnapshotAsync (line 31) | protected override Task<ExampleSnaphost> CreateSnapshotAsync(Cancellat...
    method LoadSnapshotAsync (line 39) | protected override Task LoadSnapshotAsync(ExampleSnaphost snapshot, IS...
    method SetMagicNumer (line 51) | public IExecutionResult SetMagicNumer(int magicNumber)
    method ResetMagicNumber (line 58) | public IExecutionResult ResetMagicNumber()
    method Apply (line 68) | public void Apply(ExampleEvent aggregateEvent)
    method Apply (line 75) | public void Apply(ResetEvent aggregateEvent)

FILE: EventFlow.Example/Aggregates/ReadModels/ExampleReadModel.cs
  class ExampleReadModel (line 9) | public class ExampleReadModel :
    method Apply (line 15) | public void Apply(

FILE: EventFlow.Example/Aggregates/Sagas/Events/ExampleSagaCompletedEvent.cs
  class ExampleSagaCompletedEvent (line 6) | [EventVersion("example_saga_completed", 1)]
    method ExampleSagaCompletedEvent (line 9) | public ExampleSagaCompletedEvent()

FILE: EventFlow.Example/Aggregates/Sagas/Events/ExampleSagaStartedEvent.cs
  class ExampleSagaStartedEvent (line 6) | [EventVersion("example_saga_started", 1)]
    method ExampleSagaStartedEvent (line 9) | public ExampleSagaStartedEvent(int magicNumber)

FILE: EventFlow.Example/Aggregates/Sagas/ExampleSaga.cs
  class ExampleSaga (line 13) | public class ExampleSaga : AggregateSaga<ExampleSaga, ExampleSagaId, Ord...
    method ExampleSaga (line 20) | public ExampleSaga(ExampleSagaId id) : base(id)
    method HandleAsync (line 24) | public Task HandleAsync(
    method HandleAsync (line 40) | public Task HandleAsync(
    method Apply (line 53) | public void Apply(ExampleSagaStartedEvent @event)
    method Apply (line 59) | public void Apply(ExampleSagaCompletedEvent @event)

FILE: EventFlow.Example/Aggregates/Sagas/ExampleSagaId.cs
  class ExampleSagaId (line 6) | public class ExampleSagaId : SingleValueObject<string>, ISagaId
    method ExampleSagaId (line 8) | public ExampleSagaId(string value) : base(value)

FILE: EventFlow.Example/Aggregates/Sagas/SagaExtension.cs
  class SagaExtension (line 7) | public static class SagaExtension
    method ConfigureSagas (line 9) | public static IEventFlowOptions ConfigureSagas(this IEventFlowOptions ...

FILE: EventFlow.Example/Aggregates/Sagas/SagaLocator.cs
  class OrderSagaLocator (line 8) | public class OrderSagaLocator : ISagaLocator
    method LocateSagaAsync (line 10) | public Task<ISagaId> LocateSagaAsync(

FILE: EventFlow.Example/Aggregates/Snapshots/ExampleSnapshot.cs
  class ExampleSnaphost (line 8) | [Serializable]
    method ExampleSnaphost (line 19) | public ExampleSnaphost(int? magicNumber,

FILE: EventFlow.Example/Aggregates/Snapshots/ExampleSnapshotVersion.cs
  type ExampleSnapshotVersion (line 3) | public enum ExampleSnapshotVersion

FILE: EventFlow.Example/Aggregates/Subscribers/ExampleSyncSubscriber.cs
  class ExampleSyncSubscriber (line 10) | public class ExampleSyncSubscriber : ISubscribeSynchronousTo<ExampleAggr...
    method HandleAsync (line 12) | public Task HandleAsync(IDomainEvent<ExampleAggregate, ExampleId, Exam...

FILE: EventFlow.Example/Jobs/ExampleJobs.cs
  class ExampleJob (line 9) | [JobVersion("ExampleJob", 1)]
    method ExampleJob (line 12) | public ExampleJob(string message)
    method ExecuteAsync (line 19) | public Task ExecuteAsync(

FILE: EventFlow.Example/Models/CommandReturnResult.cs
  class CommandReturnResult (line 6) | public class CommandReturnResult : ExecutionResult
    method CommandReturnResult (line 8) | public CommandReturnResult(bool isSuccess, IAggregateRoot aggregateRoot)

FILE: EventFlow.Example/Program.cs
  class Program (line 3) | class Program
    method Main (line 5) | static void Main(string[] args)

FILE: EventFlow.Example/PublishCommand.cs
  class PublishCommand (line 25) | public class PublishCommand
    method PublishCommand (line 32) | public PublishCommand()
    method GetStreamName (line 36) | public static ExampleId GetStreamName(string tenantName, string eventN...
    method DecorateCommandBus (line 39) | void DecorateCommandBus(IServiceRegistration sr)
    method PublishCommandAsync (line 44) | public async Task PublishCommandAsync()

FILE: EventFlow.Tests/IntegrationTestBase.cs
  class IntegrationTestBase (line 8) | public abstract class IntegrationTestBase : IDisposable
    method DecorateCommandBus (line 17) | public void DecorateCommandBus(IServiceRegistration sr)
    method Dispose (line 22) | public virtual void Dispose(bool isDisposing)
    method Dispose (line 28) | public void Dispose()

FILE: EventFlow.Tests/IntegrationTests.cs
  class IntegrationTests (line 30) | public class IntegrationTests : IntegrationTestBase
    method PassingTest (line 32) | [Fact]
    method ReadModelTest (line 79) | [Fact]

FILE: EventStore/EventStoreExtension.cs
  class EventStoreExtension (line 12) | public static class EventStoreExtension
    method ConfigureEventStore (line 14) | public static IEventFlowOptions ConfigureEventStore(this IEventFlowOpt...
    method GetUriFromConnectionString (line 34) | private static Uri GetUriFromConnectionString(string connectionString)

FILE: SyncEventHandler/ExampleSyncSubscriber.cs
  class ExampleSyncSubscriber (line 36) | public class ExampleSyncSubscriber : ISubscribeSynchronousTo<ExampleAggr...
    method HandleAsync (line 38) | public Task HandleAsync(IDomainEvent<ExampleAggregate, WizloId, Exampl...

FILE: SyncEventHandler/Program.cs
  class Program (line 26) | class Program
    method Main (line 28) | public static async Task Main(string[] args)
Condensed preview — 42 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (73K chars).
[
  {
    "path": ".dockerignore",
    "chars": 316,
    "preview": "**/.classpath\n**/.dockerignore\n**/.env\n**/.git\n**/.gitignore\n**/.project\n**/.settings\n**/.toolstarget\n**/.vs\n**/.vscode\n"
  },
  {
    "path": ".github/workflows/dotnetcore.yml",
    "chars": 1399,
    "preview": "# This is a basic workflow to help you get started with Actions\n\nname: CI\n\n# Controls when the action will run. Triggers"
  },
  {
    "path": ".gitignore",
    "chars": 5582,
    "preview": "## Ignore Visual Studio temporary files, build results, and\n## files generated by popular Visual Studio add-ons.\n##\n## G"
  },
  {
    "path": "EventFlow.Example/Aggregates/CommandHandlers/ExampleCommandHandler.cs",
    "chars": 1238,
    "preview": "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing EventFlow.Commands;\nusing EventFlow.Jobs;\nusin"
  },
  {
    "path": "EventFlow.Example/Aggregates/CommandHandlers/ResetCommandHandler.cs",
    "chars": 725,
    "preview": "using System.Threading;\nusing System.Threading.Tasks;\nusing EventFlow.Aggregates.ExecutionResults;\nusing EventFlow.Comma"
  },
  {
    "path": "EventFlow.Example/Aggregates/Commands/ExampleCommand.cs",
    "chars": 581,
    "preview": "using EventFlow.Commands;\nusing EventFlowExample.Aggregates.Events;\nusing EventFlowExample.Models;\n\nnamespace EventFlowE"
  },
  {
    "path": "EventFlow.Example/Aggregates/Commands/ResetCommand.cs",
    "chars": 392,
    "preview": "using EventFlow.Aggregates.ExecutionResults;\nusing EventFlow.Commands;\nusing EventFlowExample.Aggregates.Events;\n\nnamesp"
  },
  {
    "path": "EventFlow.Example/Aggregates/Decoraters/LogCommandBus.cs",
    "chars": 1034,
    "preview": "using EventFlow;\nusing EventFlow.Aggregates;\nusing EventFlow.Aggregates.ExecutionResults;\nusing EventFlow.Commands;\nusi"
  },
  {
    "path": "EventFlow.Example/Aggregates/Events/ExampleEvent.cs",
    "chars": 372,
    "preview": "using EventFlow.Aggregates;\nusing EventFlow.EventStores;\n\nnamespace EventFlowExample.Aggregates.Events\n{\n    [EventVersi"
  },
  {
    "path": "EventFlow.Example/Aggregates/Events/ExampleId.cs",
    "chars": 246,
    "preview": "using EventFlow.Core;\n\nnamespace EventFlowExample.Aggregates.Events\n{\n    public class ExampleId : IIdentity\n    {\n     "
  },
  {
    "path": "EventFlow.Example/Aggregates/Events/ResetEvent.cs",
    "chars": 271,
    "preview": "using EventFlow.Aggregates;\nusing EventFlow.EventStores;\n\nnamespace EventFlowExample.Aggregates.Events\n{\n    [EventVersi"
  },
  {
    "path": "EventFlow.Example/Aggregates/ExampleAggregate.cs",
    "chars": 2730,
    "preview": "using EventFlow.Aggregates;\nusing EventFlow.Aggregates.ExecutionResults;\nusing EventFlow.Snapshots;\nusing EventFlow.Snap"
  },
  {
    "path": "EventFlow.Example/Aggregates/ReadModels/ExampleReadModel.cs",
    "chars": 660,
    "preview": "// The MIT License (MIT)\nusing EventFlow.Aggregates;\nusing EventFlow.ReadStores;\nusing EventFlowExample.Aggregates.Event"
  },
  {
    "path": "EventFlow.Example/Aggregates/Sagas/Events/ExampleSagaCompletedEvent.cs",
    "chars": 323,
    "preview": "using EventFlow.Aggregates;\nusing EventFlow.EventStores;\n\nnamespace EventFlowExample.Aggregates.Sagas.Events\n{\n    [Even"
  },
  {
    "path": "EventFlow.Example/Aggregates/Sagas/Events/ExampleSagaStartedEvent.cs",
    "chars": 412,
    "preview": "using EventFlow.Aggregates;\nusing EventFlow.EventStores;\n\nnamespace EventFlowExample.Aggregates.Sagas.Events\n{\n    [Even"
  },
  {
    "path": "EventFlow.Example/Aggregates/Sagas/ExampleSaga.cs",
    "chars": 2271,
    "preview": "using EventFlow.Aggregates;\nusing EventFlow.Exceptions;\nusing EventFlow.Sagas;\nusing EventFlow.Sagas.AggregateSagas;\nus"
  },
  {
    "path": "EventFlow.Example/Aggregates/Sagas/ExampleSagaId.cs",
    "chars": 260,
    "preview": "using EventFlow.Sagas;\nusing EventFlow.ValueObjects;\n\nnamespace EventFlowExample.Aggregates.Sagas\n{\n    public class Ex"
  },
  {
    "path": "EventFlow.Example/Aggregates/Sagas/SagaExtension.cs",
    "chars": 892,
    "preview": "using EventFlow;\nusing EventFlow.Extensions;\nusing EventFlowExample.Aggregates.Sagas.Events;\n\nnamespace EventFlowExampl"
  },
  {
    "path": "EventFlow.Example/Aggregates/Sagas/SagaLocator.cs",
    "chars": 589,
    "preview": "using EventFlow.Aggregates;\nusing EventFlow.Sagas;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace Eve"
  },
  {
    "path": "EventFlow.Example/Aggregates/Snapshots/ExampleSnapshot.cs",
    "chars": 855,
    "preview": "using EventFlow.Snapshots;\nusing System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace EventFlowExamp"
  },
  {
    "path": "EventFlow.Example/Aggregates/Snapshots/ExampleSnapshotVersion.cs",
    "chars": 104,
    "preview": "namespace EventFlowExample.Aggregates.Snapshots\n{\n    public enum ExampleSnapshotVersion\n    {\n    }\n}\n"
  },
  {
    "path": "EventFlow.Example/Aggregates/Subscribers/ExampleSyncSubscriber.cs",
    "chars": 648,
    "preview": "using System;\nusing System.Threading;\nusing System.Threading.Tasks;\nusing EventFlow.Aggregates;\nusing EventFlow.Subscrib"
  },
  {
    "path": "EventFlow.Example/EventFlow.Example.csproj",
    "chars": 1509,
    "preview": "<Project Sdk=\"Microsoft.NET.Sdk\">\n\n  <PropertyGroup>\n    <OutputType>Exe</OutputType>\n    <TargetFramework>netcoreapp2.2"
  },
  {
    "path": "EventFlow.Example/Jobs/ExampleJobs.cs",
    "chars": 585,
    "preview": "using EventFlow.Configuration;\nusing EventFlow.Jobs;\nusing System;\nusing System.Threading;\nusing System.Threading.Tasks"
  },
  {
    "path": "EventFlow.Example/Models/CommandReturnResult.cs",
    "chars": 461,
    "preview": "using EventFlow.Aggregates;\nusing EventFlow.Aggregates.ExecutionResults;\n\nnamespace EventFlowExample.Models\n{\n    publi"
  },
  {
    "path": "EventFlow.Example/Program.cs",
    "chars": 184,
    "preview": "namespace EventFlowExample\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            new "
  },
  {
    "path": "EventFlow.Example/PublishCommand.cs",
    "chars": 6235,
    "preview": "using Autofac;\nusing EventFlow;\nusing EventFlow.Aggregates.ExecutionResults;\nusing EventFlow.Autofac.Extensions;\nusing "
  },
  {
    "path": "EventFlow.Tests/EventFlow.Tests.csproj",
    "chars": 963,
    "preview": "<Project Sdk=\"Microsoft.NET.Sdk\">\n\n  <PropertyGroup>\n    <TargetFramework>netcoreapp3.1</TargetFramework>\n\n    <IsPackab"
  },
  {
    "path": "EventFlow.Tests/IntegrationTestBase.cs",
    "chars": 889,
    "preview": "using EventFlow.Configuration;\nusing System;\nusing EventFlowExample;\nusing MongoDB.Driver;\n\nnamespace EventFlow.Tests\n{"
  },
  {
    "path": "EventFlow.Tests/IntegrationTests.cs",
    "chars": 6845,
    "preview": "using Autofac;\nusing CommandLine.Text;\nusing EventFlow.Aggregates;\nusing EventFlow.Autofac.Extensions;\nusing EventFlow.E"
  },
  {
    "path": "EventFlowExamples.sln",
    "chars": 2101,
    "preview": "\nMicrosoft Visual Studio Solution File, Format Version 12.00\n# Visual Studio Version 16\nVisualStudioVersion = 16.0.3010"
  },
  {
    "path": "EventStore/EventStore.csproj",
    "chars": 256,
    "preview": "<Project Sdk=\"Microsoft.NET.Sdk\">\n\n  <PropertyGroup>\n    <TargetFramework>netstandard2.0</TargetFramework>\n  </PropertyG"
  },
  {
    "path": "EventStore/EventStoreExtension.cs",
    "chars": 1540,
    "preview": "using System;\nusing System.Data.Common;\nusing EventFlow;\nusing EventFlow.EventStores.EventStore.Extensions;\nusing Event"
  },
  {
    "path": "LICENSE",
    "chars": 11343,
    "preview": "                                 Apache License\n                           Version 2.0, January 2004\n                   "
  },
  {
    "path": "README.md",
    "chars": 3105,
    "preview": "# EventFlow.Example\n![Hits](https://hitcounter.pythonanywhere.com/count/tag.svg?url=https://github.com/OKTAYKIR/EventFlo"
  },
  {
    "path": "SyncEventHandler/ExampleAggregate.cs",
    "chars": 2516,
    "preview": "//// The MIT License (MIT)\n//// \n//// Copyright (c) 2015-2017 Rasmus Mikkelsen\n//// Copyright (c) 2015-2017 eBay Softwar"
  },
  {
    "path": "SyncEventHandler/ExampleEvent.cs",
    "chars": 1783,
    "preview": "//// The MIT License (MIT)\n//// \n//// Copyright (c) 2015-2017 Rasmus Mikkelsen\n//// Copyright (c) 2015-2017 eBay Softwar"
  },
  {
    "path": "SyncEventHandler/ExampleSyncSubscriber.cs",
    "chars": 2029,
    "preview": "// The MIT License (MIT)\n// \n// Copyright (c) 2015-2017 Rasmus Mikkelsen\n// Copyright (c) 2015-2017 eBay Software Founda"
  },
  {
    "path": "SyncEventHandler/Program.cs",
    "chars": 2122,
    "preview": "using EventFlow;\nusing EventFlow.Aggregates;\nusing EventFlow.Configuration;\nusing EventFlow.EventStores;\nusing EventFlo"
  },
  {
    "path": "SyncEventHandler/SyncEventHandler.csproj",
    "chars": 623,
    "preview": "<Project Sdk=\"Microsoft.NET.Sdk\">\n\n  <PropertyGroup>\n    <OutputType>Exe</OutputType>\n    <TargetFramework>netcoreapp2.2"
  },
  {
    "path": "_config.yml",
    "chars": 25,
    "preview": "theme: jekyll-theme-slate"
  },
  {
    "path": "build/docker-compose.yml",
    "chars": 1130,
    "preview": "version: '3'\n\nservices:\n  \n  rabbitmq:\n    image: \"rabbitmq:3-management\"\n    container_name: rabbitmq\n    environment:\n"
  }
]

About this extraction

This page contains the full source code of the OKTAYKIR/EventFlow.Example GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 42 files (66.5 KB), approximately 15.9k tokens, and a symbol index with 75 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!