Beispiel #1
0
        static void Main(string[] args)
        {
            var random = new Random();

            var busConfig = new BusConfiguration();

            busConfig.UsePersistence <InMemoryPersistence>();
            busConfig.UseTransport <SqlServerTransport>().ConnectionString(ConnectionString);

            using (var bus = Bus.Create(busConfig).Start())
            {
                while (true)
                {
                    Console.WriteLine("Press <enter> to submit an order");
                    Console.ReadLine();

                    var orderMessage = new OrderSubmitted
                    {
                        OrderId    = Guid.NewGuid(),
                        OrderValue = random.Next(200)
                    };
                    bus.Publish(orderMessage);

                    Console.WriteLine("Order {0} worth {1} submitted.", orderMessage.OrderId, orderMessage.OrderValue);
                }
            }
        }
Beispiel #2
0
    static void Main()
    {
        Console.Title = "Samples.SQLNHibernateOutboxEF.Sender";
        const string letters = "ABCDEFGHIJKLMNOPQRSTUVXYZ";
        var          random  = new Random();

        var hibernateConfig = new Configuration();

        hibernateConfig.DataBaseIntegration(
            dataBaseIntegration: configurationProperties =>
        {
            configurationProperties.ConnectionStringName = "NServiceBus/Persistence";
            configurationProperties.Dialect <MsSql2012Dialect>();
        });

        hibernateConfig.SetProperty("default_schema", "sender");

        var busConfiguration = new BusConfiguration();

        busConfiguration.UseSerialization <JsonSerializer>();
        busConfiguration.EndpointName("Samples.SQLNHibernateOutboxEF.Sender");

        #region SenderConfiguration

        var transport      = busConfiguration.UseTransport <SqlServerTransport>();
        var connectionInfo = EndpointConnectionInfo.For("Samples.SQLNHibernateOutboxEF.Receiver")
                             .UseSchema("receiver");
        transport.UseSpecificConnectionInformation(connectionInfo);
        transport.DefaultSchema("sender");

        busConfiguration.UsePersistence <NHibernatePersistence>();

        busConfiguration.EnableOutbox();

        #endregion

        using (var bus = Bus.Create(busConfiguration).Start())
        {
            Console.WriteLine("Press enter to send a message");
            Console.WriteLine("Press any key to exit");

            while (true)
            {
                var key = Console.ReadKey();
                Console.WriteLine();

                if (key.Key != ConsoleKey.Enter)
                {
                    return;
                }
                var orderId        = new string(Enumerable.Range(0, 4).Select(x => letters[random.Next(letters.Length)]).ToArray());
                var orderSubmitted = new OrderSubmitted
                {
                    OrderId = orderId,
                    Value   = random.Next(100)
                };
                bus.Publish(orderSubmitted);
            }
        }
    }
Beispiel #3
0
    static async Task AsyncMain()
    {
        Console.Title = "Samples.SqlNHibernate.Sender";
        var endpointConfiguration = new EndpointConfiguration("Samples.SqlNHibernate.Sender");

        endpointConfiguration.SendFailedMessagesTo("error");
        endpointConfiguration.EnableInstallers();

        var hibernateConfig = new Configuration();

        hibernateConfig.DataBaseIntegration(x =>
        {
            x.ConnectionStringName = "NServiceBus/Persistence";
            x.Dialect <MsSql2012Dialect>();
        });
        hibernateConfig.SetProperty("default_schema", "sender");

        #region SenderConfiguration

        var transport = endpointConfiguration.UseTransport <SqlServerTransport>();
        transport.DefaultSchema("sender");
        transport.UseSchemaForQueue("error", "dbo");
        transport.UseSchemaForQueue("audit", "dbo");

        var persistence = endpointConfiguration.UsePersistence <NHibernatePersistence>();
        persistence.UseConfiguration(hibernateConfig);

        #endregion

        var routing = transport.Routing();
        routing.RouteToEndpoint(typeof(OrderAccepted), "Samples.SqlNHibernate.Sender");

        var endpointInstance = await Endpoint.Start(endpointConfiguration)
                               .ConfigureAwait(false);

        Console.WriteLine("Press enter to send a message");
        Console.WriteLine("Press any key to exit");

        while (true)
        {
            var key = Console.ReadKey();
            Console.WriteLine();

            if (key.Key != ConsoleKey.Enter)
            {
                break;
            }

            var orderId        = new string(Enumerable.Range(0, 4).Select(x => letters[random.Next(letters.Length)]).ToArray());
            var orderSubmitted = new OrderSubmitted
            {
                OrderId = orderId,
                Value   = random.Next(100)
            };
            await endpointInstance.Publish(orderSubmitted)
            .ConfigureAwait(false);
        }
        await endpointInstance.Stop()
        .ConfigureAwait(false);
    }
Beispiel #4
0
    static void Main()
    {
        Console.Title = "Samples.MultiTenant.Sender";
        const string     letters          = "ABCDEFGHIJKLMNOPQRSTUVXYZ";
        Random           random           = new Random();
        BusConfiguration busConfiguration = new BusConfiguration();

        busConfiguration.EndpointName("Samples.MultiTenant.Sender");
        busConfiguration.UseSerialization <JsonSerializer>();

        busConfiguration.UsePersistence <NHibernatePersistence>();
        busConfiguration.EnableOutbox();

        using (IBus bus = Bus.Create(busConfiguration).Start())
        {
            Console.WriteLine("Press A or B to publish a message (A and B are tenant IDs)");
            while (true)
            {
                ConsoleKeyInfo key = Console.ReadKey();
                Console.WriteLine();
                char uppercaseKey = char.ToUpperInvariant(key.KeyChar);

                string         orderId = new string(Enumerable.Range(0, 4).Select(x => letters[random.Next(letters.Length)]).ToArray());
                OrderSubmitted message = new OrderSubmitted
                {
                    OrderId = orderId,
                    Value   = random.Next(100)
                };
                bus.SetMessageHeader(message, "TenantId", uppercaseKey.ToString());
                bus.Publish(message);
            }
        }
    }
Beispiel #5
0
    public static async Task Main()
    {
        random = new Random();

        Console.Title = "Samples.Sql.Sender";
        var endpointConfiguration = new EndpointConfiguration("Samples.Sql.Sender");

        endpointConfiguration.SendFailedMessagesTo("error");
        endpointConfiguration.EnableInstallers();

        #region SenderConfiguration

        var connection = @"Data Source=.\SqlExpress;Database=NsbSamplesSql;Integrated Security=True;Max Pool Size=100";
        var transport  = endpointConfiguration.UseTransport <SqlServerTransport>();
        transport.ConnectionString(connection);
        transport.DefaultSchema("sender");
        transport.UseSchemaForQueue("error", "dbo");
        transport.UseSchemaForQueue("audit", "dbo");
        transport.NativeDelayedDelivery().DisableTimeoutManagerCompatibility();

        endpointConfiguration.UsePersistence <InMemoryPersistence>();

        var subscriptions = transport.SubscriptionSettings();
        subscriptions.SubscriptionTableName(
            tableName: "Subscriptions",
            schemaName: "dbo");

        #endregion

        SqlHelper.CreateSchema(connection, "sender");

        var endpointInstance = await Endpoint.Start(endpointConfiguration)
                               .ConfigureAwait(false);

        Console.WriteLine("Press enter to send a message");
        Console.WriteLine("Press any key to exit");

        while (true)
        {
            var key = Console.ReadKey();
            Console.WriteLine();

            if (key.Key != ConsoleKey.Enter)
            {
                break;
            }

            var orderSubmitted = new OrderSubmitted
            {
                OrderId = Guid.NewGuid(),
                Value   = random.Next(100)
            };
            await endpointInstance.Publish(orderSubmitted)
            .ConfigureAwait(false);

            Console.WriteLine("Published OrderSubmitted message");
        }
        await endpointInstance.Stop()
        .ConfigureAwait(false);
    }
Beispiel #6
0
        //-- COMMANDS ------------------------------------------------------------------------------------------------//
        private void OnMessage(SubmitOrder command)
        {
            this.CommandCount++;
            this.Logger.LogInformation(LogId.Trading, $"{Received}{Command} {command}.");

            var result = this.database.AddOrder(
                command.Order,
                command.TraderId,
                command.AccountId,
                command.StrategyId,
                command.PositionId);

            if (result.IsSuccess)
            {
                var positionIdBroker = this.database.GetPositionIdBroker(command.PositionId);
                this.gateway.SubmitOrder(command.Order, positionIdBroker);

                var submitted = new OrderSubmitted(
                    command.AccountId,
                    command.Order.Id,
                    this.TimeNow(),
                    this.NewGuid(),
                    this.TimeNow());

                command.Order.Apply(submitted);
                this.database.UpdateOrder(command.Order);

                this.SendToEventPublisher(submitted);
            }
            else
            {
                this.Logger.LogError(LogId.Database, $"Cannot execute command {command} ({result.Message}).");
            }
        }
Beispiel #7
0
    static async Task Main()
    {
        Console.Title = "Samples.MultiTenant.Sender";
        const string letters = "ABCDEFGHIJKLMNOPQRSTUVXYZ";
        var          random  = new Random();
        var          endpointConfiguration = new EndpointConfiguration("Samples.MultiTenant.Sender");

        endpointConfiguration.SendFailedMessagesTo("error");

        var connection  = @"Data Source=.\SqlExpress;Database=NsbSamplesMultiTenantSender;Integrated Security=True";
        var persistence = endpointConfiguration.UsePersistence <NHibernatePersistence>();

        persistence.ConnectionString(connection);
        endpointConfiguration.UseTransport <MsmqTransport>();
        endpointConfiguration.EnableInstallers();
        endpointConfiguration.EnableOutbox();

        var endpointInstance = await Endpoint.Start(endpointConfiguration)
                               .ConfigureAwait(false);

        Console.WriteLine("Press A or B to publish a message (A and B are tenant IDs)");
        Console.WriteLine("Press Escape to exit");
        var acceptableInput = new List <char> {
            'A', 'B'
        };

        while (true)
        {
            var key = Console.ReadKey();
            Console.WriteLine();

            if (key.Key == ConsoleKey.Escape)
            {
                break;
            }
            var uppercaseKey = char.ToUpperInvariant(key.KeyChar);

            if (acceptableInput.Contains(uppercaseKey))
            {
                var orderId = new string(Enumerable.Range(0, 4).Select(x => letters[random.Next(letters.Length)]).ToArray());
                var message = new OrderSubmitted
                {
                    OrderId = orderId,
                    Value   = random.Next(100)
                };

                var options = new PublishOptions();
                options.SetHeader("TenantId", uppercaseKey.ToString());

                await endpointInstance.Publish(message, options)
                .ConfigureAwait(false);
            }
            else
            {
                Console.WriteLine($"[{uppercaseKey}] is not a valid tenant identifier.");
            }
        }
        await endpointInstance.Stop()
        .ConfigureAwait(false);
    }
Beispiel #8
0
        static void Main()
        {
            var serviceProvider = new ServiceCollection()
                                  .AddRawRabbit(new RawRabbitOptions
            {
                ClientConfiguration = new RawRabbitConfiguration
                {
                    Username    = "******",
                    Password    = "******",
                    Port        = 5672,
                    VirtualHost = "/",
                    Hostnames   = { "localhost" }
                }
            })
                                  .BuildServiceProvider();

            var client = serviceProvider.GetService <IBusClient>();

            Console.WriteLine("Publishing order event...");

            var orderSubmitted = new OrderSubmitted(Guid.NewGuid(), $"Order - {DateTime.Now}", 1230);

            client.PublishAsync(orderSubmitted).Wait();

            Console.WriteLine($"Event {orderSubmitted.Id} published.");
        }
    static async Task AsyncMain()
    {
        Console.Title = "Samples.SqlTransportSqlPersistence.Sender";
        var endpointConfiguration = new EndpointConfiguration("Samples.SqlTransportSqlPersistence.Sender");

        endpointConfiguration.SendFailedMessagesTo("error");
        endpointConfiguration.EnableInstallers();

        #region SenderConfiguration

        var connectionString = @"Data Source=.\SqlExpress;Database=shared;Integrated Security=True;Min Pool Size=2;Max Pool Size=100";
        var transport        = endpointConfiguration.UseTransport <SqlServerTransport>();
        transport.ConnectionString(connectionString);
        transport.DefaultSchema("sender");
        transport.UseSchemaForQueue("error", "dbo");
        transport.UseSchemaForQueue("audit", "dbo");

        var persistence = endpointConfiguration.UsePersistence <SqlPersistence>();
        persistence.SqlVariant(SqlVariant.MsSqlServer);
        persistence.ConnectionBuilder(
            connectionBuilder: () =>
        {
            return(new SqlConnection(connectionString));
        });
        persistence.Schema("sender");
        persistence.TablePrefix("");
        var subscriptions = persistence.SubscriptionSettings();
        subscriptions.CacheFor(TimeSpan.FromMinutes(1));

        #endregion

        var endpointInstance = await Endpoint.Start(endpointConfiguration)
                               .ConfigureAwait(false);

        Console.WriteLine("Press enter to send a message");
        Console.WriteLine("Press any key to exit");

        while (true)
        {
            var key = Console.ReadKey();
            Console.WriteLine();

            if (key.Key != ConsoleKey.Enter)
            {
                break;
            }

            var orderId        = new string(Enumerable.Range(0, 4).Select(x => letters[random.Next(letters.Length)]).ToArray());
            var orderSubmitted = new OrderSubmitted
            {
                OrderId = orderId,
                Value   = random.Next(100)
            };
            await endpointInstance.Publish(orderSubmitted)
            .ConfigureAwait(false);
        }
        await endpointInstance.Stop()
        .ConfigureAwait(false);
    }
Beispiel #10
0
    static async Task AsyncMain()
    {
        Console.Title = "Samples.SQLNHibernateOutbox.Sender";
        const string letters = "ABCDEFGHIJKLMNOPQRSTUVXYZ";
        var          random  = new Random();
        var          endpointConfiguration = new EndpointConfiguration("Samples.SQLNHibernateOutbox.Sender");

        endpointConfiguration.UseSerialization <JsonSerializer>();

        #region SenderConfiguration

        var transport = endpointConfiguration.UseTransport <SqlServerTransport>();
        transport.ConnectionString(@"Data Source=.\SqlExpress;Database=nservicebus;Integrated Security=True");

        var persistence = endpointConfiguration.UsePersistence <NHibernatePersistence>();
        persistence.ConnectionString(@"Data Source=.\SqlExpress;Database=nservicebus;Integrated Security=True");

        endpointConfiguration.EnableOutbox();

        #endregion

        endpointConfiguration.Recoverability()
        .Immediate(immediate => immediate.NumberOfRetries(0))
        .Delayed(delayed => delayed.NumberOfRetries(0));
        endpointConfiguration.SendFailedMessagesTo("error");
        endpointConfiguration.AuditProcessedMessagesTo("audit");
        endpointConfiguration.EnableInstallers();

        var endpointInstance = await Endpoint.Start(endpointConfiguration)
                               .ConfigureAwait(false);

        try
        {
            Console.WriteLine("Press enter to publish a message");
            Console.WriteLine("Press any key to exit");
            while (true)
            {
                var key = Console.ReadKey();
                Console.WriteLine();
                if (key.Key != ConsoleKey.Enter)
                {
                    return;
                }
                var orderId        = new string(Enumerable.Range(0, 4).Select(x => letters[random.Next(letters.Length)]).ToArray());
                var orderSubmitted = new OrderSubmitted
                {
                    OrderId = orderId,
                    Value   = random.Next(100)
                };
                await endpointInstance.Publish(orderSubmitted)
                .ConfigureAwait(false);
            }
        }
        finally
        {
            await endpointInstance.Stop()
            .ConfigureAwait(false);
        }
    }
    public Task Handle(OrderSubmitted message, IMessageHandlerContext context)
    {
        Data.OrderId = message.OrderId;
        #region Timeout
        return(RequestTimeout <OrderTimeout>(context, TimeSpan.FromSeconds(5)));

        #endregion
    }
        public void Handle(OrderSubmitted message)
        {
            Data.OrderId = message.OrderId;

            #region Timeout
            RequestTimeout <OrderTimeout>(TimeSpan.FromSeconds(5));
            #endregion
        }
    public Task Handle(OrderSubmitted message, IMessageHandlerContext context)
    {
        Data.OrderId = message.OrderId;

        RequestTimeout <OrderTimeout>(context, TimeSpan.FromSeconds(5));

        return(Task.CompletedTask);
    }
Beispiel #14
0
        //-- EVENTS --------------------------------------------------------------------------------------------------//
        private void OnMessage(OrderSubmitted @event)
        {
            this.EventCount++;
            this.Logger.LogInformation(LogId.Trading, $"{Received}{Event} {@event}.");

            this.ProcessOrderEvent(@event);
            this.SendToEventPublisher(@event);
        }
Beispiel #15
0
    public static async Task Main()
    {
        //required to prevent possible occurrence of .NET Core issue https://github.com/dotnet/coreclr/issues/12668
        Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US");
        Thread.CurrentThread.CurrentCulture   = new CultureInfo("en-US");

        random = new Random();

        Console.Title = "Samples.Sql.Sender";
        var endpointConfiguration = new EndpointConfiguration("Samples.Sql.Sender");

        endpointConfiguration.SendFailedMessagesTo("error");
        endpointConfiguration.EnableInstallers();

        #region SenderConfiguration

        var connection = @"Data Source=.\SqlExpress;Database=NsbSamplesSql;Integrated Security=True;Max Pool Size=100";
        var transport  = endpointConfiguration.UseTransport <SqlServerTransport>();
        transport.ConnectionString(connection);
        transport.DefaultSchema("sender");
        transport.UseSchemaForQueue("error", "dbo");
        transport.UseSchemaForQueue("audit", "dbo");

        endpointConfiguration.UsePersistence <InMemoryPersistence>();

        #endregion

        SqlHelper.CreateSchema(connection, "sender");

        var endpointInstance = await Endpoint.Start(endpointConfiguration)
                               .ConfigureAwait(false);

        Console.WriteLine("Press enter to send a message");
        Console.WriteLine("Press any key to exit");

        while (true)
        {
            var key = Console.ReadKey();
            Console.WriteLine();

            if (key.Key != ConsoleKey.Enter)
            {
                break;
            }

            var orderSubmitted = new OrderSubmitted
            {
                OrderId = Guid.NewGuid(),
                Value   = random.Next(100)
            };
            await endpointInstance.Publish(orderSubmitted)
            .ConfigureAwait(false);

            Console.WriteLine("Published OrderSubmitted message");
        }
        await endpointInstance.Stop()
        .ConfigureAwait(false);
    }
Beispiel #16
0
        private void OnMessage(SubmitBracketOrder command)
        {
            this.CommandCount++;
            this.Logger.LogInformation(LogId.Trading, $"{Received}{Command} {command}.");

            var result = this.database.AddBracketOrder(
                command.BracketOrder,
                command.TraderId,
                command.AccountId,
                command.StrategyId,
                command.PositionId);

            if (result.IsSuccess)
            {
                this.gateway.SubmitOrder(command.BracketOrder);

                var submitted1 = new OrderSubmitted(
                    command.AccountId,
                    command.BracketOrder.Entry.Id,
                    this.TimeNow(),
                    this.NewGuid(),
                    this.TimeNow());

                var submitted2 = new OrderSubmitted(
                    command.AccountId,
                    command.BracketOrder.StopLoss.Id,
                    this.TimeNow(),
                    this.NewGuid(),
                    this.TimeNow());

                command.BracketOrder.Entry.Apply(submitted1);
                command.BracketOrder.StopLoss.Apply(submitted2);
                this.database.UpdateOrder(command.BracketOrder.Entry);
                this.database.UpdateOrder(command.BracketOrder.StopLoss);

                this.SendToEventPublisher(submitted1);
                this.SendToEventPublisher(submitted2);

                if (command.BracketOrder.TakeProfit != null)
                {
                    var submitted3 = new OrderSubmitted(
                        command.AccountId,
                        command.BracketOrder.TakeProfit.Id,
                        this.TimeNow(),
                        this.NewGuid(),
                        this.TimeNow());

                    command.BracketOrder.TakeProfit.Apply(submitted3);
                    this.database.UpdateOrder(command.BracketOrder.TakeProfit);

                    this.SendToEventPublisher(submitted3);
                }
            }
            else
            {
                this.Logger.LogError(LogId.Database, $"Cannot execute command {command} {result.Message}");
            }
        }
    public async Task Handle(OrderSubmitted message, IMessageHandlerContext context)
    {
        Data.OrderId = message.OrderId;

        #region Timeout
        await RequestTimeout(context, TimeSpan.FromSeconds(5), new OrderTimeout());

        #endregion
    }
    public async Task Handle(OrderSubmitted message, IMessageHandlerContext context)
    {
        #region Timeout

        var orderTimeout = new OrderTimeout();
        await RequestTimeout(context, TimeSpan.FromSeconds(5), orderTimeout)
            .ConfigureAwait(false);
        #endregion
    }
 public void When(OrderSubmitted e)
 {
     writer.Update <OrdersView>(e.Id, v =>
     {
         v.Version   = e.Version;
         v.UpdatedOn = e.CreatedOn;
         v.Status    = OrderStatus.Submitted;
     });
 }
Beispiel #20
0
        private async Task SendMessage()
        {
            var notification = new OrderSubmitted
            {
                CustomerIdentifier = customers[random.Next(customers.Length)]
            };

            await mediator.Publish(notification);
        }
Beispiel #21
0
        private static async Task SendMessage()
        {
            var message = new OrderSubmitted
            {
                CustomerId = customers[random.Next(customers.Length)]
            };

            await endpointInstance.Publish(message).ConfigureAwait(false);
        }
    static async Task AsyncMain()
    {
        Console.Title = "Samples.Sql.Sender";
        var endpointConfiguration = new EndpointConfiguration("Samples.Sql.Sender");

        endpointConfiguration.UseSerialization <JsonSerializer>();
        endpointConfiguration.SendFailedMessagesTo("error");
        endpointConfiguration.EnableInstallers();

        #region SenderConfiguration

        var connection = @"Data Source=.\SqlExpress;Database=shared;Integrated Security=True";
        var transport  = endpointConfiguration.UseTransport <SqlServerTransport>();
        transport.ConnectionString(connection);
        transport.DefaultSchema("sender");
        transport.UseSchemaForQueue("error", "dbo");
        transport.UseSchemaForQueue("audit", "dbo");

        endpointConfiguration.UsePersistence <InMemoryPersistence>();

        #endregion


        var allText = File.ReadAllText("Startup.sql");
        await SqlHelper.ExecuteSql(connection, allText)
        .ConfigureAwait(false);

        var endpointInstance = await Endpoint.Start(endpointConfiguration)
                               .ConfigureAwait(false);

        Console.WriteLine("Press enter to send a message");
        Console.WriteLine("Press any key to exit");

        while (true)
        {
            var key = Console.ReadKey();
            Console.WriteLine();

            if (key.Key != ConsoleKey.Enter)
            {
                break;
            }

            var orderSubmitted = new OrderSubmitted
            {
                OrderId = Guid.NewGuid(),
                Value   = random.Next(100)
            };
            await endpointInstance.Publish(orderSubmitted)
            .ConfigureAwait(false);

            Console.WriteLine("Published OrderSubmitted message");
        }
        await endpointInstance.Stop()
        .ConfigureAwait(false);
    }
Beispiel #23
0
    static async Task AsyncMain()
    {
        Console.Title = "Samples.SqlServer.StoreAndForwardSender";
        const string letters = "ABCDEFGHIJKLMNOPQRSTUVXYZ";
        var          random  = new Random();
        var          endpointConfiguration = new EndpointConfiguration("Samples.SqlServer.StoreAndForwardSender");

        endpointConfiguration.SendFailedMessagesTo("error");
        endpointConfiguration.UsePersistence <InMemoryPersistence>();

        #region SenderConfiguration

        var transport = endpointConfiguration.UseTransport <SqlServerTransport>();
        transport.EnableLegacyMultiInstanceMode(ConnectionProvider.GetConnecton);

        var pipeline = endpointConfiguration.Pipeline;
        pipeline.Register("Forward", new ForwardBehavior(), "Forwards messages to destinations.");
        pipeline.Register("Store",
                          b => new SendThroughLocalQueueRoutingToDispatchConnector(b.Build <ReadOnlySettings>().LocalAddress()),
                          "Send messages through local endpoint.");

        #endregion

        var endpointInstance = await Endpoint.Start(endpointConfiguration)
                               .ConfigureAwait(false);

        try
        {
            Console.WriteLine("Press enter to publish a message");
            Console.WriteLine("Press any key to exit");
            while (true)
            {
                var key = Console.ReadKey();
                Console.WriteLine();
                if (key.Key != ConsoleKey.Enter)
                {
                    break;
                }
                var orderId        = new string(Enumerable.Range(0, 4).Select(x => letters[random.Next(letters.Length)]).ToArray());
                var orderSubmitted = new OrderSubmitted
                {
                    OrderId = orderId,
                    Value   = random.Next(100)
                };
                await endpointInstance.Publish(orderSubmitted)
                .ConfigureAwait(false);

                Console.WriteLine($"Order {orderId} placed");
            }
        }
        finally
        {
            await endpointInstance.Stop()
            .ConfigureAwait(false);
        }
    }
Beispiel #24
0
        static void Main(string[] args)
        {
            var exchange           = "Model.Event:IOrderSubmitted";
            var priorityRoutingKey = RoutingKey.Priority;
            var regularRoutingKey  = RoutingKey.Regular;
            var factory            = new ConnectionFactory
            {
                HostName = "localhost",
                UserName = "******",
                Password = "******"
            };

            using (var connection = factory.CreateConnection())
                using (var channel = connection.CreateModel())
                {
                    var priorityOrderSubmitted = new OrderSubmitted
                    {
                        CorrelationId = InVar.CorrelationId,
                        EventId       = Guid.NewGuid(),
                        OrderType     = priorityRoutingKey
                    };

                    var regularOrderSubmitted = new OrderSubmitted
                    {
                        CorrelationId = InVar.CorrelationId,
                        EventId       = Guid.NewGuid(),
                        OrderType     = regularRoutingKey
                    };


                    // Msg should be wrapped in an envelop before sending to RabbitMQ
                    var priorityEnvelope = new Envelope
                    {
                        MessageId          = Guid.NewGuid().ToString(),
                        DestinationAddress = "localhost",
                        Message            = priorityOrderSubmitted,
                        Headers            = { },
                        MessageType        = new[] { $"urn:message:{exchange}" }
                    };

                    var regularEnvelope = new Envelope
                    {
                        MessageId          = Guid.NewGuid().ToString(),
                        DestinationAddress = "localhost",
                        Message            = priorityOrderSubmitted,
                        Headers            = { },
                        MessageType        = new[] { $"urn:message:{exchange}" }
                    };

                    var priorityMsg = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(priorityEnvelope));
                    var regularMsg  = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(regularEnvelope));

                    channel.BasicPublish(exchange, priorityRoutingKey, null, priorityMsg);
                    channel.BasicPublish(exchange, regularRoutingKey, null, regularMsg);
                }
        }
Beispiel #25
0
    static async Task AsyncMain()
    {
        Console.Title = "Samples.MultiTenant.Sender";
        const string letters = "ABCDEFGHIJKLMNOPQRSTUVXYZ";
        var          random  = new Random();
        var          endpointConfiguration = new EndpointConfiguration("Samples.MultiTenant.Sender");

        endpointConfiguration.UseSerialization <JsonSerializer>();
        endpointConfiguration.SendFailedMessagesTo("error");

        endpointConfiguration.UsePersistence <NHibernatePersistence>();
        endpointConfiguration.EnableOutbox();

        var endpointInstance = await Endpoint.Start(endpointConfiguration)
                               .ConfigureAwait(false);

        try
        {
            Console.WriteLine("Press A or B to publish a message (A and B are tenant IDs)");
            var acceptableInput = new List <char> {
                'A', 'B'
            };

            while (true)
            {
                var key = Console.ReadKey();
                Console.WriteLine();
                var uppercaseKey = char.ToUpperInvariant(key.KeyChar);

                if (acceptableInput.Contains(uppercaseKey))
                {
                    var orderId = new string(Enumerable.Range(0, 4).Select(x => letters[random.Next(letters.Length)]).ToArray());
                    var message = new OrderSubmitted
                    {
                        OrderId = orderId,
                        Value   = random.Next(100)
                    };

                    var options = new PublishOptions();
                    options.SetHeader("TenantId", uppercaseKey.ToString());

                    await endpointInstance.Publish(message, options)
                    .ConfigureAwait(false);
                }
                else
                {
                    Console.WriteLine($"[{uppercaseKey}] is not a valid tenant identifier.");
                }
            }
        }
        finally
        {
            await endpointInstance.Stop()
            .ConfigureAwait(false);
        }
    }
    static void Main()
    {
        Console.Title = "Samples.SQLNHibernateOutboxEF.Sender";
        const string letters = "ABCDEFGHIJKLMNOPQRSTUVXYZ";
        var random = new Random();

        var hibernateConfig = new Configuration();
        hibernateConfig.DataBaseIntegration(x =>
        {
            x.ConnectionStringName = "NServiceBus/Persistence";
            x.Dialect<MsSql2012Dialect>();
        });

        hibernateConfig.SetProperty("default_schema", "sender");

        var busConfiguration = new BusConfiguration();
        busConfiguration.UseSerialization<JsonSerializer>();
        busConfiguration.EndpointName("Samples.SQLNHibernateOutboxEF.Sender");

        #region SenderConfiguration

        var transport = busConfiguration.UseTransport<SqlServerTransport>();
        transport.UseSpecificConnectionInformation(
            EndpointConnectionInfo.For("Samples.SQLNHibernateOutboxEF.Receiver").UseSchema("receiver"));
        transport.DefaultSchema("sender");

        busConfiguration.UsePersistence<NHibernatePersistence>();

        busConfiguration.EnableOutbox();

        #endregion

        using (var bus = Bus.Create(busConfiguration).Start())
        {
            Console.WriteLine("Press enter to send a message");
            Console.WriteLine("Press any key to exit");

            while (true)
            {
                var key = Console.ReadKey();
                Console.WriteLine();

                if (key.Key != ConsoleKey.Enter)
                {
                    return;
                }
                var orderId = new string(Enumerable.Range(0, 4).Select(x => letters[random.Next(letters.Length)]).ToArray());
                var orderSubmitted = new OrderSubmitted
                {
                    OrderId = orderId,
                    Value = random.Next(100)
                };
                bus.Publish(orderSubmitted);
            }
        }
    }
    static async Task AsyncMain()
    {
        Console.Title = "Samples.SqlServer.StoreAndForwardSender";
        const string letters = "ABCDEFGHIJKLMNOPQRSTUVXYZ";
        var random = new Random();
        var endpointConfiguration = new EndpointConfiguration("Samples.SqlServer.StoreAndForwardSender");
        endpointConfiguration.SendFailedMessagesTo("error");
        endpointConfiguration.UsePersistence<InMemoryPersistence>();

        #region SenderConfiguration

        var transport = endpointConfiguration.UseTransport<SqlServerTransport>();
        transport.EnableLegacyMultiInstanceMode(ConnectionProvider.GetConnecton);

        var pipeline = endpointConfiguration.Pipeline;
        pipeline.Register("Forward", new ForwardBehavior(), "Forwards messages to destinations.");
        pipeline.Register("Store",
            b => new SendThroughLocalQueueRoutingToDispatchConnector(b.Build<ReadOnlySettings>().LocalAddress()),
            "Send messages through local endpoint.");

        #endregion

        var endpointInstance = await Endpoint.Start(endpointConfiguration)
            .ConfigureAwait(false);
        try
        {
            Console.WriteLine("Press enter to publish a message");
            Console.WriteLine("Press any key to exit");
            while (true)
            {
                var key = Console.ReadKey();
                Console.WriteLine();
                if (key.Key != ConsoleKey.Enter)
                {
                    break;
                }
                var orderId = new string(Enumerable.Range(0, 4).Select(x => letters[random.Next(letters.Length)]).ToArray());
                var orderSubmitted = new OrderSubmitted
                {
                    OrderId = orderId,
                    Value = random.Next(100)
                };
                await endpointInstance.Publish(orderSubmitted)
                    .ConfigureAwait(false);
                Console.WriteLine($"Order {orderId} placed");
            }
        }
        finally
        {
            await endpointInstance.Stop()
                .ConfigureAwait(false);
        }
    }
    static async Task AsyncMain()
    {
        Console.Title = "Samples.MultiTenant.Sender";
        const string letters = "ABCDEFGHIJKLMNOPQRSTUVXYZ";
        var random = new Random();
        var endpointConfiguration = new EndpointConfiguration("Samples.MultiTenant.Sender");
        endpointConfiguration.UseSerialization<JsonSerializer>();
        endpointConfiguration.SendFailedMessagesTo("error");

        endpointConfiguration.UsePersistence<NHibernatePersistence>();
        endpointConfiguration.EnableOutbox();

        var endpointInstance = await Endpoint.Start(endpointConfiguration)
            .ConfigureAwait(false);

        try
        {
            Console.WriteLine("Press A or B to publish a message (A and B are tenant IDs)");
            var acceptableInput = new List<char> { 'A', 'B' };

            while (true)
            {
                var key = Console.ReadKey();
                Console.WriteLine();
                var uppercaseKey = char.ToUpperInvariant(key.KeyChar);

                if (acceptableInput.Contains(uppercaseKey))
                {
                    var orderId = new string(Enumerable.Range(0, 4).Select(x => letters[random.Next(letters.Length)]).ToArray());
                    var message = new OrderSubmitted
                    {
                        OrderId = orderId,
                        Value = random.Next(100)
                    };

                    var options = new PublishOptions();
                    options.SetHeader("TenantId", uppercaseKey.ToString());

                    await endpointInstance.Publish(message, options)
                        .ConfigureAwait(false);
                }
                else
                {
                    Console.WriteLine($"[{uppercaseKey}] is not a valid tenant identifier.");
                }
            }
        }
        finally
        {
            await endpointInstance.Stop()
                .ConfigureAwait(false);
        }
    }
Beispiel #29
0
        public Task Handle(OrderSubmitted message, IMessageHandlerContext context)
        {
            log.Info($"saga for Order {context.MessageId} with orderid {message.OrderId} is started");

            Data.OrderId = message.OrderId;
            context.SendLocal(new SaveOrder()
            {
                OrderId = message.OrderId,
                Value   = message.Value
            });

            return(Task.FromResult(0));
        }
Beispiel #30
0
    public async Task Handle(OrderSubmitted message, IMessageHandlerContext context)
    {
        var orderTimeout = new OrderTimeout();

        await RequestTimeout(context, TimeSpan.FromSeconds(5), orderTimeout)
        .ConfigureAwait(false);

        var orderAccepted = new OrderAccepted
        {
            OrderId = message.OrderId,
        };
        await context.Reply(orderAccepted)
        .ConfigureAwait(false);
    }
Beispiel #31
0
    static void Main()
    {
        Console.Title = "Samples.SqlServer.StoreAndForwardSender";
        var random           = new Random();
        var busConfiguration = new BusConfiguration();

        busConfiguration.EndpointName("Samples.SqlServer.StoreAndForwardSender");

        #region SenderConfiguration

        var transport = busConfiguration.UseTransport <SqlServerTransport>();
        var sender    = @"Data Source=.\SqlExpress;Database=NsbSamplesStoreAndForwardSender;Integrated Security=True";
        transport.ConnectionString(sender);
        var receiver = @"Data Source=.\SqlExpress;Database=NsbSamplesStoreAndForwardReceiver;Integrated Security=True";
        transport.UseSpecificConnectionInformation(
            EndpointConnectionInfo.For("Samples.SqlServer.StoreAndForwardReceiver")
            .UseConnectionString(receiver)
            );
        busConfiguration.UsePersistence <InMemoryPersistence>();
        var pipeline = busConfiguration.Pipeline;
        pipeline.Register <ForwardBehavior.Registration>();
        pipeline.Register <SendThroughLocalQueueBehavior.Registration>();

        #endregion

        SqlHelper.EnsureDatabaseExists(sender);
        using (var bus = Bus.Create(busConfiguration).Start())
        {
            Console.WriteLine("Press enter to publish a message");
            Console.WriteLine("Press any key to exit");
            while (true)
            {
                var key = Console.ReadKey();
                Console.WriteLine();
                if (key.Key != ConsoleKey.Enter)
                {
                    return;
                }
                var orderId        = Guid.NewGuid();
                var orderSubmitted = new OrderSubmitted
                {
                    OrderId = orderId,
                    Value   = random.Next(100)
                };
                bus.Publish(orderSubmitted);
                Console.WriteLine($"Order {orderId} placed");
            }
        }
    }
Beispiel #32
0
    static void Main()
    {
        Console.Title = "Samples.MultiTenant.Sender";
        const string letters          = "ABCDEFGHIJKLMNOPQRSTUVXYZ";
        var          random           = new Random();
        var          busConfiguration = new BusConfiguration();

        busConfiguration.EndpointName("Samples.MultiTenant.Sender");

        var connection  = @"Data Source=.\SqlExpress;Database=NsbSamplesMultiTenantSender;Integrated Security=True";
        var persistence = busConfiguration.UsePersistence <NHibernatePersistence>();

        persistence.ConnectionString(connection);
        busConfiguration.EnableOutbox();

        SqlHelper.EnsureDatabaseExists(connection);
        using (var bus = Bus.Create(busConfiguration).Start())
        {
            Console.WriteLine("Press A or B to publish a message (A and B are tenant IDs)");
            var acceptableInput = new List <char> {
                'A', 'B'
            };

            while (true)
            {
                var key = Console.ReadKey();
                Console.WriteLine();
                var uppercaseKey = char.ToUpperInvariant(key.KeyChar);

                if (acceptableInput.Contains(uppercaseKey))
                {
                    var orderId = new string(Enumerable.Range(0, 4).Select(x => letters[random.Next(letters.Length)]).ToArray());
                    var message = new OrderSubmitted
                    {
                        OrderId = orderId,
                        Value   = random.Next(100)
                    };
                    bus.SetMessageHeader(message, "TenantId", uppercaseKey.ToString());
                    bus.Publish(message);
                }
                else
                {
                    Console.WriteLine($"[{uppercaseKey}] is not a valid tenant identifier.");
                }
            }
        }
    }
Beispiel #33
0
        public void Handle(OrderSubmitted message)
        {
            Data.OrderId = message.OrderId;
            Data.ThrowSagaTimeoutException = message.ThrowSagaTimeoutException;

            #region Timeout

            RequestTimeout <OrderTimeout>(TimeSpan.FromSeconds(5));

            #endregion

            if (message.ThrowSagaTransportException)
            {
                throw new Exception("Blow up!");
            }
            Console.WriteLine("Saga Handler Finished");
        }
		public void Setup()
		{
			_order = new OrderSubmitted();

			_overLimit = MockRepository.GenerateMock<Action<OrderSubmitted>>();
			_overLimit.Expect(x => x(_order));

			_underLimit = MockRepository.GenerateMock<Action<OrderSubmitted>>();
			_underLimit.Expect(x => x(_order)).Repeat.Never();

			_engine = new MagnumRulesEngine();

			AddOverLimitRule();
			AddUnderLimitRule();

			StringNodeVisitor visitor = new StringNodeVisitor();
			_engine.Visit(visitor);

			Trace.WriteLine(visitor.Result);
		}
Beispiel #35
0
    static void Main()
    {
        Console.Title = "Samples.MultiTenant.Sender";
        const string letters = "ABCDEFGHIJKLMNOPQRSTUVXYZ";
        Random random = new Random();
        BusConfiguration busConfiguration = new BusConfiguration();
        busConfiguration.EndpointName("Samples.MultiTenant.Sender");
        busConfiguration.UseSerialization<JsonSerializer>();

        busConfiguration.UsePersistence<NHibernatePersistence>();
        busConfiguration.EnableOutbox();

        using (IBus bus = Bus.Create(busConfiguration).Start())
        {
            Console.WriteLine("Press A or B to publish a message (A and B are tenant IDs)");
            List<char> acceptableInput = new List<char> { 'A', 'B' };

            while (true)
            {
                ConsoleKeyInfo key = Console.ReadKey();
                Console.WriteLine();
                char uppercaseKey = char.ToUpperInvariant(key.KeyChar);

                if (acceptableInput.Contains(uppercaseKey))
                {
                    string orderId = new string(Enumerable.Range(0, 4).Select(x => letters[random.Next(letters.Length)]).ToArray());
                    OrderSubmitted message = new OrderSubmitted
                    {
                        OrderId = orderId,
                        Value = random.Next(100)
                    };
                    bus.SetMessageHeader(message, "TenantId", uppercaseKey.ToString());
                    bus.Publish(message);
                }
                else
                {
                    Console.WriteLine("[{0}] is not a valid tenant identifier.", uppercaseKey);
                }
            }
        }
    }
    static async Task AsyncMain()
    {
        Console.Title = "Samples.SQLNHibernateOutboxEF.Sender";
        const string letters = "ABCDEFGHIJKLMNOPQRSTUVXYZ";
        var random = new Random();

        var hibernateConfig = new Configuration();
        hibernateConfig.DataBaseIntegration(x =>
        {
            x.ConnectionStringName = "NServiceBus/Persistence";
            x.Dialect<MsSql2012Dialect>();
        });

        hibernateConfig.SetProperty("default_schema", "sender");

        var endpointConfiguration = new EndpointConfiguration("Samples.SQLNHibernateOutboxEF.Sender");
        endpointConfiguration.UseSerialization<JsonSerializer>();

        #region SenderConfiguration

        var transport = endpointConfiguration.UseTransport<SqlServerTransport>();
        transport.DefaultSchema("sender");
        transport.UseSpecificSchema(queueName =>
        {
            if (queueName.Equals("error", StringComparison.OrdinalIgnoreCase) || queueName.Equals("audit", StringComparison.OrdinalIgnoreCase))
            {
                return "dbo";
            }
            return null;
        });

        endpointConfiguration.UsePersistence<NHibernatePersistence>();

        endpointConfiguration.EnableOutbox();

        #endregion

        var endpointInstance = await Endpoint.Start(endpointConfiguration)
            .ConfigureAwait(false);

        try
        {
            Console.WriteLine("Press enter to send a message");
            Console.WriteLine("Press any key to exit");

            while (true)
            {
                var key = Console.ReadKey();
                Console.WriteLine();

                if (key.Key != ConsoleKey.Enter)
                {
                    return;
                }
                var orderId = new string(Enumerable.Range(0, 4).Select(x => letters[random.Next(letters.Length)]).ToArray());
                var orderSubmitted = new OrderSubmitted
                {
                    OrderId = orderId,
                    Value = random.Next(100)
                };
                await endpointInstance.Publish(orderSubmitted)
                    .ConfigureAwait(false);
            }
        }
        finally
        {
            await endpointInstance.Stop()
                .ConfigureAwait(false);
        }
    }
    static async Task AsyncMain()
    {
        Console.Title = "Samples.SqlNHibernate.Sender";
        var endpointConfiguration = new EndpointConfiguration("Samples.SqlNHibernate.Sender");
        endpointConfiguration.SendFailedMessagesTo("error");
        endpointConfiguration.EnableInstallers();

        var hibernateConfig = new Configuration();
        hibernateConfig.DataBaseIntegration(x =>
        {
            x.ConnectionStringName = "NServiceBus/Persistence";
            x.Dialect<MsSql2012Dialect>();
        });
        hibernateConfig.SetProperty("default_schema", "sender");

        #region SenderConfiguration

        var transport = endpointConfiguration.UseTransport<SqlServerTransport>();
        transport.DefaultSchema("sender");
        transport.UseSpecificSchema(e =>
            {
                if (e == "error" || e == "audit")
                {
                    return "dbo";
                }
                return null;
            });

        var persistence = endpointConfiguration.UsePersistence<NHibernatePersistence>();
        persistence.UseConfiguration(hibernateConfig);

        #endregion

        var endpointInstance = await Endpoint.Start(endpointConfiguration)
            .ConfigureAwait(false);
        try
        {
            Console.WriteLine("Press enter to send a message");
            Console.WriteLine("Press any key to exit");

            while (true)
            {
                var key = Console.ReadKey();
                Console.WriteLine();

                if (key.Key != ConsoleKey.Enter)
                {
                    return;
                }

                var orderId = new string(Enumerable.Range(0, 4).Select(x => letters[random.Next(letters.Length)]).ToArray());
                var orderSubmitted = new OrderSubmitted
                {
                    OrderId = orderId,
                    Value = random.Next(100)
                };
                await endpointInstance.Publish(orderSubmitted)
                .ConfigureAwait(false);
            }
        }
        finally
        {
            await endpointInstance.Stop()
                .ConfigureAwait(false);
        }
    }