예제 #1
0
 public EntityFrameworkSagaRepository(SagaDbContextFactory sagaDbContextFactory, IsolationLevel isolationLevel = IsolationLevel.ReadCommitted, bool optimistic = false, IRelationalEntityMetadataHelper relationalEntityMetadataHelper = null)
 {
     _sagaDbContextFactory           = sagaDbContextFactory;
     _isolationLevel                 = isolationLevel;
     _optimistic                     = optimistic;
     _relationalEntityMetadataHelper = relationalEntityMetadataHelper ?? new EntityFrameworkMetadataHelper();
 }
예제 #2
0
            public When_pre_inserting_in_an_invalid_state_with_ef()
            {
                SagaDbContextFactory sagaDbContextFactory =
                    () => new SagaDbContext <Instance, EntityFrameworkInstanceMap>(SagaDbContextFactoryProvider.GetLocalDbConnectionString());

                _repository = new EntityFrameworkSagaRepository <Instance>(sagaDbContextFactory);
            }
        public BasketManager(string cs, string sasKeyName, string sasKeyValue, string serviceNamespace)
        {
            _scheduler          = CreateScheduler();
            _dbConnectionString = cs;
            //    _basketStore = basketStore;
            _credentials = TokenProvider.CreateSharedAccessSignatureTokenProvider(sasKeyName, sasKeyValue);
            // _namespaceClient = new NamespaceManager(ServiceBusEnvironment.CreateServiceUri("sb", ServiceNamespace, string.Empty), _credentials);

            Console.WriteLine("DB init ... ");
            //var dbConnectionString =
            //    @"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\DOM\AzureTopicPOC\Abt.Result.WebApi\BasketSagaData.mdf;Integrated Security=True";
            // DB
            SagaDbContextFactory sagaDbContextFactory = () => new SagaDbContext <BasketSaga, BasketDataMap>(_dbConnectionString);

            using (var dbConnection = new SqlConnection(_dbConnectionString))
            {
                dbConnection.Open();
                var cmd = dbConnection.CreateCommand();
                cmd.CommandText = "DELETE FROM BasketSagas";
                cmd.ExecuteNonQuery();
            }
            Console.WriteLine("Persistence Data Table flushed ... ");

            _repository = new Lazy <ISagaRepository <BasketSaga> >(() => new EntityFrameworkSagaRepository <BasketSaga>(sagaDbContextFactory));

            Init();
        }
예제 #4
0
        public bool Start(HostControl hostControl)
        {
            _log.Info("Creating bus...");

            _machine = new LoadDataSaga();

            SagaDbContextFactory sagaDbContextFactory = () => new SagaDbContext <LoadData, LoadDataMap>(DbContextFactoryProvider.ConnectionString);

            //_repository = new Lazy<ISagaRepository<LoadData>>(() => new EntityFrameworkSagaRepository<LoadData>(sagaDbContextFactory));
            _repository = new InMemorySagaRepository <LoadData>();

            _busControl = Bus.Factory.CreateUsingRabbitMq(x =>
            {
                IRabbitMqHost host = x.Host(new Uri(Consts.RabbitMqAddress), h =>
                {
                    h.Username(Consts.User);
                    h.Password(Consts.Pass);
                });

                x.ReceiveEndpoint(host, Consts.LoadDataQueue, e =>
                {
                    e.PrefetchCount = 8;
                    e.StateMachineSaga(_machine, _repository);
                });
            });

            _log.Info("Starting bus...");

            TaskUtil.Await(() => _busControl.StartAsync());

            return(true);
        }
예제 #5
0
        private static IBusControl ConfigureReadBus()
        {
            var expertTaggingStateMachine = new SampleSaga();

            SagaDbContextFactory sagaDbContextFactory =
                () => new SagaDbContext <SampleSagaState, SampleSagaMapping>("default");

            var stateMachineRepository = new EntityFrameworkSagaRepository <SampleSagaState>(sagaDbContextFactory);

            var busControl = Bus.Factory.CreateUsingAzureServiceBus(cfg =>
            {
                cfg.UseNLog();

                IServiceBusHost host = cfg.Host(ConfigurationManager.AppSettings["azureServiceBus:ConnectionString"],
                                                hcfg => { });

                cfg.ReceiveEndpoint(host, "sample_queue", ecfg =>
                {
                    ecfg.StateMachineSaga(expertTaggingStateMachine, stateMachineRepository);
                });
            });

            var observer = new ReceiveObserver(true);

            busControl.ConnectReceiveObserver(observer);

            return(busControl);
        }
예제 #6
0
        public bool Start(HostControl hostControl)
        {
            _log.Info("Creating bus...");

            _machine = new ShoppingCartStateMachine();

            SagaDbContextFactory sagaDbContextFactory =
                () => new SagaDbContext <ShoppingCart, ShoppingCartMap>(SagaDbContextFactoryProvider.ConnectionString);

            _repository = new Lazy <ISagaRepository <ShoppingCart> >(
                () => new EntityFrameworkSagaRepository <ShoppingCart>(sagaDbContextFactory));

            _busControl = Bus.Factory.CreateUsingRabbitMq(x =>
            {
                IRabbitMqHost host = x.Host(new Uri(ConfigurationManager.AppSettings["RabbitMQHost"]), h =>
                {
                    h.Username("guest");
                    h.Password("guest");
                });

                x.ReceiveEndpoint(host, "shopping_cart_state", e =>
                {
                    e.PrefetchCount = 8;
                    e.StateMachineSaga(_machine, _repository.Value);
                });

                x.ReceiveEndpoint(host, ConfigurationManager.AppSettings["SchedulerQueueName"], e =>
                {
                    // For MT4.0, prefetch must be set for Quartz prior to anything else
                    e.PrefetchCount = 1;
                    x.UseMessageScheduler(e.InputAddress);

                    e.Consumer(() => new ScheduleMessageConsumer(_scheduler));
                    e.Consumer(() => new CancelScheduledMessageConsumer(_scheduler));
                });
            });

            _log.Info("Starting bus...");

            try
            {
                _busHandle = MassTransit.Util.TaskUtil.Await <BusHandle>(() => _busControl.StartAsync());

                _scheduler.JobFactory = new MassTransitJobFactory(_busControl);

                _scheduler.Start();
            }
            catch (Exception)
            {
                _scheduler.Shutdown();
                throw;
            }

            return(true);
        }
예제 #7
0
        ISagaRepository <BookingRequestState> GetSagaRepository()
        {
            _sagaDbContextFactory = () => new SagaDbContext <BookingRequestState, BookingRequestStateMap>(LocalDatabaseSelector.ConnectionString);

            using (var context = _sagaDbContextFactory())
            {
                context.Database.CreateIfNotExists();
            }

            return(new EntityFrameworkSagaRepository <BookingRequestState>(_sagaDbContextFactory));
        }
예제 #8
0
        ISagaRepository<BookingRequestState> GetSagaRepository()
        {
            _sagaDbContextFactory = () => new SagaDbContext<BookingRequestState, BookingRequestStateMap>(LocalDatabaseSelector.ConnectionString);

            using (var context = _sagaDbContextFactory())
            {
                context.Database.CreateIfNotExists();
            }

            return new EntityFrameworkSagaRepository<BookingRequestState>(_sagaDbContextFactory);
        }
        public bool Start(HostControl hostControl)
        {
            _log.Info("Creating bus...");
            _machine = new ShoppingCartStateMachine();
            SagaDbContextFactory sagaDbContextFactory = () => new SagaDbContext <ShoppingCart, ShoppingCartMap>(SagaDbContextFactoryProvider.ConnectionString);

            _repository = new Lazy <ISagaRepository <ShoppingCart> >(() => new EntityFrameworkSagaRepository <ShoppingCart>(sagaDbContextFactory));

            _busControl = Bus.Factory.CreateUsingAzureServiceBus(x =>
            {
                var serviceUri = ServiceBusEnvironment.CreateServiceUri("sb", ConfigurationManager.AppSettings["AzureSbNamespace"], "");

                var host = x.Host(serviceUri, h =>
                {
                    h.OperationTimeout = TimeSpan.FromMinutes(5);
                    h.TokenProvider    = TokenProvider.CreateSharedAccessSignatureTokenProvider(ConfigurationManager.AppSettings["AzureSbKeyName"], ConfigurationManager.AppSettings["AzureSbSharedAccessKey"], TimeSpan.FromDays(1), TokenScope.Namespace);
                });

                x.ReceiveEndpoint(host, "shopping_cart_state", e =>
                {
                    e.PrefetchCount = 8;
                    e.StateMachineSaga(_machine, _repository.Value);
                });

                x.ReceiveEndpoint(host, ConfigurationManager.AppSettings["SchedulerQueueName"], e =>
                {
                    e.PrefetchCount = 1;
                    x.UseMessageScheduler(e.InputAddress);

                    e.Consumer(() => new ScheduleMessageConsumer(_scheduler));
                    e.Consumer(() => new CancelScheduledMessageConsumer(_scheduler));
                });
            });

            _log.Info("Starting bus...");

            try
            {
                _busHandle = MassTransit.Util.TaskUtil.Await <BusHandle>(() => _busControl.StartAsync());

                _scheduler.JobFactory = new MassTransitJobFactory(_busControl);

                _scheduler.Start();
            }
            catch (Exception)
            {
                _scheduler.Shutdown();
                throw;
            }

            return(true);
        }
        public bool Start(HostControl hostControl)
        {
            _log.Info("Creating bus...");

            _metrics         = new RoutingSlipMetrics("Routing Slip");
            _activityMetrics = new RoutingSlipMetrics("Validate Activity");

            _machine = new RoutingSlipStateMachine();

            SagaDbContextFactory sagaDbContextFactory =
                () => new SagaDbContext <RoutingSlipState, RoutingSlipStateSagaMap>(SagaDbContextFactoryProvider.ConnectionString);

            _repository = new Lazy <ISagaRepository <RoutingSlipState> >(
                () => new EntityFrameworkSagaRepository <RoutingSlipState>(sagaDbContextFactory));

            _busControl = Bus.Factory.CreateUsingRabbitMq(x =>
            {
                IRabbitMqHost host = x.Host(new Uri(ConfigurationManager.AppSettings["RabbitMQHost"]), h =>
                {
                    h.Username("samplecourier");
                    h.Password("samplecourier");
                });

                x.ReceiveEndpoint(host, "routing_slip_metrics", e =>
                {
                    e.PrefetchCount = 100;
                    e.UseRetry(Retry.None);
                    e.Consumer(() => new RoutingSlipMetricsConsumer(_metrics));
                });

                x.ReceiveEndpoint(host, "routing_slip_activity_metrics", e =>
                {
                    e.PrefetchCount = 100;
                    e.UseRetry(Retry.None);
                    e.Consumer(() => new RoutingSlipActivityConsumer(_activityMetrics, "Validate"));
                });

                x.ReceiveEndpoint(host, "routing_slip_state", e =>
                {
                    e.PrefetchCount = 8;
                    e.UseConcurrencyLimit(1);
                    e.StateMachineSaga(_machine, _repository.Value);
                });
            });

            _log.Info("Starting bus...");

            _busControl.StartAsync().Wait();

            return(true);
        }
예제 #11
0
            protected override void ConfigureInMemoryReceiveEndpoint(IInMemoryReceiveEndpointConfigurator configurator)
            {
                _discarded = GetTask <bool>();

                _simpleStateMachine = new SimpleStateMachine(x =>
                {
                    _discarded.TrySetResult(true);
                });

                _sagaDbContextFactory =
                    () => new SagaDbContext <SimpleState, SimpleStateMap>(SagaDbContextFactoryProvider.GetLocalDbConnectionString());
                _simpleStateRepository = new Lazy <ISagaRepository <SimpleState> >(() => new EntityFrameworkSagaRepository <SimpleState>(_sagaDbContextFactory));


                configurator.StateMachineSaga(_simpleStateMachine, _simpleStateRepository.Value);

                base.ConfigureInMemoryReceiveEndpoint(configurator);
            }
예제 #12
0
        static void Main(string[] args)
        {
            MapperMappings.Map();

            var    sagaStateMachine             = new BookStateMachine();
            string connectionString             = ConfigurationManager.ConnectionStrings["sagabook"].ConnectionString;
            SagaDbContextFactory contextFactory = () =>
                                                  new SagaDbContext <Book, SagaInstanceMap>(connectionString);
            var repository = new EntityFrameworkSagaRepository <Book>(contextFactory, optimistic: true);

            var busControl = Bus.Factory.CreateUsingRabbitMq(x =>
            {
                var host = x.Host(new Uri("rabbitmq://domer-ss/"), h =>
                {
                    h.Username("admin");
                    h.Password("admin");
                });

                x.ReceiveEndpoint(host, "book_guest", e =>
                {
                    e.StateMachineSaga(sagaStateMachine, repository);
                });
            });

            busControl.Start();
            ConsoleKey consoleKey = ConsoleKey.NoName;

            do
            {
                if (consoleKey == ConsoleKey.F1)
                {
                    busControl.Publish <Message1>(new { Message = "Hello World 1!" });
                }

                if (consoleKey == ConsoleKey.F2)
                {
                    busControl.Publish <Message2>(new { Message = "Hello World 2!" });
                }
            } while ((consoleKey = Console.ReadKey().Key) != ConsoleKey.Escape);

            busControl.Stop();
        }
예제 #13
0
        public bool Start(HostControl hostControl)
        {
            _log.Info("Creating bus...");

            var connectionString = ConfigurationManager.AppSettings["DatabaseConnectionString"];

            SagaDbContextFactory sagaDbContextFactory = () => new SagaDbContext <RegistrationStateInstance, RegistrationStateInstanceMap>(connectionString);

            _sagaRepository = new EntityFrameworkSagaRepository <RegistrationStateInstance>(sagaDbContextFactory);

            _busControl = Bus.Factory.CreateUsingAzureServiceBus(cfg =>
            {
                var host = cfg.Host(ConfigurationManager.AppSettings["Microsoft.ServiceBus.ConnectionString"], h =>
                {
                });

                EndpointConvention.Map <ProcessRegistration>(
                    host.Settings.ServiceUri.GetDestinationAddress(ConfigurationManager.AppSettings["ProcessRegistrationQueueName"]));

                cfg.ReceiveEndpoint(host, ConfigurationManager.AppSettings["RegistrationStateQueueName"], e =>
                {
                    e.PrefetchCount = 16;

                    var paritioner = cfg.CreatePartitioner(8);

                    var machine = new RegistrationStateMachine();

                    e.StateMachineSaga(machine, _sagaRepository, x =>
                    {
                        x.Message <RegistrationReceived>(m => m.UsePartitioner(paritioner, p => p.Message.SubmissionId));
                        x.Message <RegistrationCompleted>(m => m.UsePartitioner(paritioner, p => p.Message.SubmissionId));
                    });
                });
            });

            _log.Info("Starting bus...");

            _busControl.Start();

            return(true);
        }
예제 #14
0
        public static void Main(string[] args)
        {
            var bus = Bus.Factory.CreateUsingRabbitMq(configurator =>
            {
                var host = configurator.Host(new Uri("rabbitmq://localhost"), hostConfigurator =>
                {
                    hostConfigurator.Username("guest");
                    hostConfigurator.Password("guest");
                });

                var saga = new ShoppingCartSaga();

                SagaDbContextFactory sagaDbContextFactory =
                    () => new SagaDbContext <ShoppingCart, ShoppingCartMap>("Data Source=.;Initial Catalog=SagasExample;Integrated Security=True");

                var repository = new Lazy <ISagaRepository <ShoppingCart> >(
                    () => new EntityFrameworkSagaRepository <ShoppingCart>(sagaDbContextFactory));

                configurator.ReceiveEndpoint(host, "SagaExample.ShoppingCarts", e =>
                {
                    e.PrefetchCount = 8;
                    e.StateMachineSaga(saga, repository.Value);
                });

                configurator.UseInMemoryScheduler();

                configurator.ReceiveEndpoint(host, "SagaExample.Puppies", e =>
                {
                    e.Consumer <ShowSadPuppyConsumer>();
                });
            });

            bus.Start();

            Console.WriteLine("Started cart service.");

            Console.ReadLine();
        }
예제 #15
0
        private IBusControl ConfigureBus()
        {
            var quoteStateMachine = new TradeStateMachine();

            SagaDbContextFactory quoteDbContextFactory =
                () => new PersistedTradeDbContext();

            var quoteRepo = new Lazy <ISagaRepository <PersistedTrade> >(
                () => new EntityFrameworkSagaRepository <PersistedTrade>(quoteDbContextFactory));


            return(BusConfigurator.ConfigureBus((cfg, host) =>
            {
                cfg.ReceiveEndpoint(
                    host,
                    "trade_saga",
                    e =>
                {
                    e.UseInMemoryOutbox();
                    e.StateMachineSaga(quoteStateMachine, quoteRepo.Value);
                });
            }));
        }
예제 #16
0
 public Locating_an_existing_ef_saga()
 {
     sagaDbContextFactory = () => new SagaDbContext<SimpleSaga, SimpleSagaMap>(SagaDbContextFactoryProvider.GetLocalDbConnectionString());
     _sagaRepository = new Lazy<ISagaRepository<SimpleSaga>>(() => new EntityFrameworkSagaRepository<SimpleSaga>(sagaDbContextFactory));
 }
예제 #17
0
        public static void Main(string[] args)
        {
            var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "data");

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            AppDomain.CurrentDomain.SetData("DataDirectory", path);

            var builder = new ContainerBuilder();

            builder.RegisterType <TheGreatSaga>().AsSelf().SingleInstance();

            builder.Register(
                context =>
            {
                SagaDbContextFactory factory = () => new TheGreatSagaDbContext();
                return(new EntityFrameworkSagaRepository <TheGreatState>(factory, optimistic: true));
            }).As <ISagaRepository <TheGreatState> >()
            .SingleInstance();

            builder.Register(
                context =>
            {
                var busControl = Bus.Factory.CreateUsingRabbitMq(
                    cfg =>
                {
                    cfg.UseNLog();
                    var host = cfg.Host(
                        new Uri("rabbitmq://localhost/"),
                        h =>
                    {
                        h.Username("guest");
                        h.Password("guest");
                    });

                    cfg.ReceiveEndpoint(
                        host,
                        "Wiggly.Wombat.TheGreatSaga",
                        epc =>
                    {
                        epc.UseInMemoryOutbox();
                        epc.UseRetry(
                            x =>
                        {
                            x.Handle <DbUpdateConcurrencyException>();
                            x.Interval(5, TimeSpan.FromMilliseconds(100));
                        });                                 // Add Retry Middleware for Optimistic Concurrency


                        var repository = context.Resolve <ISagaRepository <TheGreatState> >();
                        var saga       = context.Resolve <TheGreatSaga>();

                        ushort concurrency = 8;
                        epc.PrefetchCount  = (ushort)(concurrency * 2);

                        epc.UsePartitioner(
                            concurrency,
                            cc =>
                        {
                            if (cc.TryGetMessage(out ConsumeContext <IUpdateGreatState> createSagaContext))
                            {
                                return(createSagaContext.Message.EventId);
                            }

                            return(cc.CorrelationId ?? Guid.Empty);
                        });

                        epc.StateMachineSaga(saga, repository);
                    });
                });
                return(busControl);
            }).SingleInstance().As <IBusControl>().As <IBus>();


            var container = builder.Build();

            var control = container.Resolve <IBusControl>();

            control.StartAsync().Wait();
        }
 public When_using_EntityFrameworkConcurrencyFail()
 {
     _sagaDbContextFactory =
         () => new SagaDbContext <ChoirState, EntityFrameworkChoirStateMap>(SagaDbContextFactoryProvider.GetLocalDbConnectionString());
     _repository = new Lazy <ISagaRepository <ChoirState> >(() => new EntityFrameworkSagaRepository <ChoirState>(_sagaDbContextFactory, optimistic: true));
 }
 public When_using_EntityFramework()
 {
     _sagaDbContextFactory =
         () => new SagaDbContext <ShoppingChore, EntityFrameworkShoppingChoreMap>(SagaDbContextFactoryProvider.GetLocalDbConnectionString());
     _repository = new Lazy <ISagaRepository <ShoppingChore> >(() => new EntityFrameworkSagaRepository <ShoppingChore>(_sagaDbContextFactory));
 }
예제 #20
0
 public Locating_an_existing_ef_saga()
 {
     sagaDbContextFactory = () => new SagaDbContext <SimpleSaga, SimpleSagaMap>(SagaDbContextFactoryProvider.GetLocalDbConnectionString());
     _sagaRepository      = new Lazy <ISagaRepository <SimpleSaga> >(() => new EntityFrameworkSagaRepository <SimpleSaga>(sagaDbContextFactory));
 }
예제 #21
0
 public RegistrationStateReader(string connectionString)
 {
     _sagaDbContextFactory = () => new SagaDbContext <RegistrationStateInstance, RegistrationStateInstanceMap>(connectionString);
 }
 public EntityFrameworkSagaRepository(SagaDbContextFactory sagaDbContextFactory, IsolationLevel isolationLevel = IsolationLevel.Serializable)
 {
     _sagaDbContextFactory = sagaDbContextFactory;
     _isolationLevel       = isolationLevel;
 }
 public EntityFrameworkSagaRepository(SagaDbContextFactory sagaDbContextFactory, IsolationLevel isolationLevel = IsolationLevel.ReadCommitted)
 {
     _sagaDbContextFactory = sagaDbContextFactory;
     _isolationLevel       = isolationLevel;
 }
 public EntityFrameworkSagaRepository(SagaDbContextFactory sagaDbContextFactory, IsolationLevel isolationLevel = IsolationLevel.ReadCommitted, bool optimistic = false)
 {
     _sagaDbContextFactory = sagaDbContextFactory;
     _isolationLevel       = isolationLevel;
     _optimistic           = optimistic;
 }