async Task AsyncOnStart()
 {
     BusConfiguration busConfiguration = new BusConfiguration();
     //other bus configuration. endpoint name, logging, transport, persistence etc
     busConfiguration.EnableInstallers();
     endpointInstance = await Endpoint.Start(busConfiguration);
 }
Esempio n. 2
0
    static async Task Run(IEndpointInstance endpointInstance)
    {
        Console.WriteLine("Press 'F' to send a message with a file stream");
        Console.WriteLine("Press 'H' to send a message with a http stream");
        Console.WriteLine("Press any key to exit");

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

            if (key.Key == ConsoleKey.F)
            {
                await SendMessageWithFileStream(endpointInstance)
                    .ConfigureAwait(false);
                continue;
            }
            if (key.Key == ConsoleKey.H)
            {
                await SendMessageWithHttpStream(endpointInstance)
                    .ConfigureAwait(false);
                continue;
            }
            break;
        }
    }
 async Task AsyncOnStart()
 {
     var endpointConfiguration = new EndpointConfiguration("EndpointName");
     endpointConfiguration.EnableInstallers();
     endpointInstance = await Endpoint.Start(endpointConfiguration)
         .ConfigureAwait(false);
 }
Esempio n. 4
0
    protected void Application_Start()
    {
        #region ApplicationStart

        ContainerBuilder builder = new ContainerBuilder();

        // Register MVC controllers.
        builder.RegisterControllers(typeof(MvcApplication).Assembly);

        // Set the dependency resolver to be Autofac.
        IContainer container = builder.Build();

        EndpointConfiguration endpointConfiguration = new EndpointConfiguration("Samples.MvcInjection.WebApplication");
        // instruct NServiceBus to use a custom AutoFac configuration
        endpointConfiguration.UseContainer<AutofacBuilder>(c => c.ExistingLifetimeScope(container));
        endpointConfiguration.UseSerialization<JsonSerializer>();
        endpointConfiguration.UsePersistence<InMemoryPersistence>();
        endpointConfiguration.EnableInstallers();
        endpointConfiguration.SendFailedMessagesTo("error");

        endpoint = Endpoint.Start(endpointConfiguration).GetAwaiter().GetResult();

        ContainerBuilder updater = new ContainerBuilder();
        updater.RegisterInstance(endpoint);
        updater.Update(container);

        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

        AreaRegistration.RegisterAllAreas();
        RegisterRoutes(RouteTable.Routes);

        #endregion
    }
Esempio n. 5
0
    static async Task Run(IEndpointInstance endpointInstance)
    {
        Console.WriteLine("Press 'J' to send a JSON message");
        Console.WriteLine("Press 'X' to send a XML message");
        Console.WriteLine("Press any key to exit");

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

            if (key.Key == ConsoleKey.X)
            {
                await SendXmlMessage(endpointInstance)
                    .ConfigureAwait(false);
                continue;
            }
            if (key.Key == ConsoleKey.J)
            {
                await SendJsonMessage(endpointInstance)
                    .ConfigureAwait(false);
                continue;
            }
            break;
        }
    }
Esempio n. 6
0
    protected void Application_Start()
    {
        #region ApplicationStart

        ContainerBuilder builder = new ContainerBuilder();

        // Register your MVC controllers.
        builder.RegisterControllers(typeof(MvcApplication).Assembly);

        // Set the dependency resolver to be Autofac.
        IContainer container = builder.Build();

        BusConfiguration busConfiguration = new BusConfiguration();
        busConfiguration.EndpointName("Samples.MvcInjection.WebApplication");
        // ExistingLifetimeScope() ensures that IBus is added to the container as well,
        // allowing you to resolve IBus from your own components.
        busConfiguration.UseContainer<AutofacBuilder>(c => c.ExistingLifetimeScope(container));
        busConfiguration.UseSerialization<JsonSerializer>();
        busConfiguration.UsePersistence<InMemoryPersistence>();
        busConfiguration.EnableInstallers();
        busConfiguration.SendFailedMessagesTo("error");

        endpoint = Endpoint.Start(busConfiguration).GetAwaiter().GetResult();

        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

        AreaRegistration.RegisterAllAreas();
        RegisterRoutes(RouteTable.Routes);

        #endregion
    }
Esempio n. 7
0
    static async Task SendOrder(IEndpointInstance endpointInstance)
    {

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

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

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

            PlaceOrder placeOrder = new PlaceOrder
            {
                Product = "New shoes",
                Id = id
            };
            await endpointInstance.Send("Samples.StepByStep.Server", placeOrder);

            Console.WriteLine("Sent a new PlaceOrder message with id: {0}", id.ToString("N"));

        }

    }
Esempio n. 8
0
    public static async Task Run(IEndpointInstance endpointInstance)
    {
        Console.WriteLine("Press 's' to send a valid message");
        Console.WriteLine("Press 'e' to send a failed message");
        Console.WriteLine("Press any key to exit");

        while (true)
        {
            var key = Console.ReadKey();
            Console.WriteLine();
            Console.WriteLine();
            switch (key.Key)
            {
                case ConsoleKey.S:
                    #region SendingSmall

                    var createProductCommand = new CreateProductCommand
                    {
                        ProductId = "XJ128",
                        ProductName = "Milk",
                        ListPrice = 4,
                        // 7MB. MSMQ should throw an exception, but it will not since the buffer will be compressed
                        // before it reaches MSMQ.
                        Image = new byte[1024 * 1024 * 7]
                    };
                    await endpointInstance.SendLocal(createProductCommand)
                        .ConfigureAwait(false);
                    #endregion
                    break;
                case ConsoleKey.E:
                    try
                    {
                        #region SendingLarge

                        var productCommand = new CreateProductCommand
                        {
                            ProductId = "XJ128",
                            ProductName = "Really long product name",
                            ListPrice = 15,
                            // 7MB. MSMQ should throw an exception, but it will not since the buffer will be compressed
                            // before it reaches MSMQ.
                            Image = new byte[1024 * 1024 * 7]
                        };
                        await endpointInstance.SendLocal(productCommand)
                            .ConfigureAwait(false);
                        #endregion
                    }
                    catch
                    {
                        //so the console keeps on running
                    }
                    break;
                default:
                    {
                        return;
                    }
            }
        }
    }
Esempio n. 9
0
 // Shut down server before sending this message, after 30 seconds, the message will be moved to Transactional dead-letter messages queue.
 static async Task Expiration(IEndpointInstance endpointInstance)
 {
     await endpointInstance.Send(new MessageThatExpires
              {
                  RequestId = new Guid()
              });
     Console.WriteLine("message with expiration was sent");
 }
Esempio n. 10
0
 public static void SetInstance(IEndpointInstance endpoint)
 {
     if (Endpoint != null)
     {
         throw new Exception("Endpoint already set.");
     }
     Endpoint = endpoint;
 }
Esempio n. 11
0
 static IDisposable StartWcfHost(IEndpointInstance endpointInstance)
 {
     WcfMapper wcfMapper = new WcfMapper(endpointInstance, "http://localhost:8080");
     wcfMapper.StartListening<EnumMessage, Status>();
     wcfMapper.StartListening<ObjectMessage, ReplyMessage>();
     wcfMapper.StartListening<IntMessage, int>();
     return wcfMapper;
 }
        Task DefaultAction(IEndpointInstance endpoint)
        {
            #region DefaultCriticalErrorAction

            return endpoint.Stop();

            #endregion
        }
        async Task Subscribe(IEndpointInstance endpoint)
        {
            #region ExplicitSubscribe
            await endpoint.Subscribe<MyEvent>();

            await endpoint.Unsubscribe<MyEvent>();
            #endregion
        }
Esempio n. 14
0
    static async Task SendMessage(IEndpointInstance endpointInstance)
    {
        Message message = new Message();
        await endpointInstance.SendLocal(message);

        Console.WriteLine();
        Console.WriteLine("Message sent");
    }
Esempio n. 15
0
 async void Simple(IEndpointInstance endpoint, SendOptions sendOptions, ILog log)
 {
     #region EnumCallback
     Message message = new Message();
     Status response = await endpoint.Request<Status>(message, sendOptions);
     log.Info("Callback received with response:" + response);
     #endregion
 }
Esempio n. 16
0
 static async Task SendJsonMessage(IEndpointInstance endpointInstance)
 {
     MessageWithJson message = new MessageWithJson
     {
         SomeProperty = "Some content in a json message",
     };
     await endpointInstance.Send("Samples.MultiSerializer.Receiver", message);
     Console.WriteLine("Json Message sent");
 }
Esempio n. 17
0
 static async Task SendXmlMessage(IEndpointInstance endpointInstance)
 {
     var message = new MessageWithXml
     {
         SomeProperty = "Some content in a Xml message",
     };
     await endpointInstance.Send("Samples.MultiSerializer.Receiver", message)
         .ConfigureAwait(false);
     Console.WriteLine("XML message sent");
 }
 // Shut down server before sending this message, after 30 seconds, the message will be moved to Transactional dead-letter messages queue.
 static async Task Expiration(IEndpointInstance endpointInstance)
 {
     var messageThatExpires = new MessageThatExpires
     {
         RequestId = new Guid()
     };
     await endpointInstance.Send(messageThatExpires)
         .ConfigureAwait(false);
     Console.WriteLine("message with expiration was sent");
 }
Esempio n. 19
0
    async Task AsyncOnStart()
    {
        BusConfiguration busConfiguration = new BusConfiguration();

        busConfiguration.EndpointName("Samples.WindowsServiceAndConsole");
        busConfiguration.UseSerialization<JsonSerializer>();
        busConfiguration.SendFailedMessagesTo("error");
        busConfiguration.UsePersistence<InMemoryPersistence>();
        busConfiguration.EnableInstallers();
        endpoint = await Endpoint.Start(busConfiguration);
    }
Esempio n. 20
0
    static async Task PublishEvent(IEndpointInstance endpointInstance)
    {
        Guid eventId = Guid.NewGuid();

        await endpointInstance.Publish<IMyEvent>(m =>
        {
            m.EventId = eventId;
        });
        Console.WriteLine("Event published, id: " + eventId);

    }
        Scheduling(IEndpointInstance endpointInstance)
        {
            #region ScheduleTask
            // To send a message every 5 minutes
            endpointInstance.ScheduleEvery(TimeSpan.FromMinutes(5), b => b.Send(new CallLegacySystem()));

            // Name a schedule task and invoke it every 5 minutes
            endpointInstance.ScheduleEvery(TimeSpan.FromMinutes(5), "MyCustomTask", SomeCustomMethod);

            #endregion
        }
 async Task AsyncOnStart()
 {
     EndpointConfiguration endpointConfiguration = new EndpointConfiguration("Samples.WindowsServiceAndConsole");
     endpointConfiguration.UseSerialization<JsonSerializer>();
     endpointConfiguration.SendFailedMessagesTo("error");
     endpointConfiguration.UsePersistence<InMemoryPersistence>();
     endpointConfiguration.EnableInstallers();
     endpoint = await Endpoint.Start(endpointConfiguration);
     // run any startup actions on the bus
     await endpoint.SendLocal(new MyMessage());
 }
Esempio n. 23
0
    async Task StartBus()
    {
        EndpointConfiguration endpointConfiguration = new EndpointConfiguration();
        endpointConfiguration.EndpointName("Samples.Callbacks.WebSender");
        endpointConfiguration.UseSerialization<JsonSerializer>();
        endpointConfiguration.UsePersistence<InMemoryPersistence>();
        endpointConfiguration.EnableInstallers();
        endpointConfiguration.SendFailedMessagesTo("error");

        Endpoint = await NServiceBus.Endpoint.Start(endpointConfiguration);
    }
        async Task SendDelayedMessage(IEndpointInstance endpoint, IMessageHandlerContext handlerContext)
        {
            #region delayed-delivery-datetime
            SendOptions options = new SendOptions();
            options.DoNotDeliverBefore(new DateTime(2016, 12, 25));

            await handlerContext.Send(new MessageToBeSentLater(), options);
            // OR
            await endpoint.Send(new MessageToBeSentLater(), options);
            #endregion
        }
Esempio n. 25
0
    static async Task SendRequest(IEndpointInstance endpointInstance)
    {
        Guid requestId = Guid.NewGuid();

        await endpointInstance.Send(new Request
        {
            RequestId = requestId
        });

        Console.WriteLine("Request sent id: " + requestId);
    }
Esempio n. 26
0
 internal void SetEndpoint(IEndpointInstance endpointInstance)
 {
     lock (endpointCriticalLock)
     {
         endpoint = endpointInstance;
         foreach (var latentCritical in criticalErrors)
         {
             RaiseForEndpoint(latentCritical.Message, latentCritical.Exception);
         }
         criticalErrors.Clear();
     }
 }
Esempio n. 27
0
    static async Task SendMessageTooLargePayload(IEndpointInstance endpointInstance)
    {
        #region SendMessageTooLargePayload

        AnotherMessageWithLargePayload message = new AnotherMessageWithLargePayload
        {
            LargeBlob = new byte[1024*1024*5] //5MB
        };
        await endpointInstance.Send("Samples.DataBus.Receiver", message);

        #endregion
    }
Esempio n. 28
0
    static async Task SendEnumMessage(IEndpointInstance endpointInstance)
    {
        Console.WriteLine("Message sent");
        #region SendEnumMessage

        EnumMessage message = new EnumMessage();
        SendOptions sendOptions = new SendOptions();
        sendOptions.SetDestination("Samples.Callbacks.Receiver");
        Status status = await endpointInstance.Request<Status>(message, sendOptions);
        Console.WriteLine("Callback received with status:" + status);
        #endregion
    }
Esempio n. 29
0
    static async Task Start(IEndpointInstance endpointInstance)
    {
        Console.WriteLine("Press '1' to publish IEvent");
        Console.WriteLine("Press '2' to publish EventMessage");
        Console.WriteLine("Press '3' to publish AnotherEventMessage");
        Console.WriteLine("Press any other key to exit");
        #region PublishLoop
        while (true)
        {
            var key = Console.ReadKey();
            Console.WriteLine();

            var eventId = Guid.NewGuid();
            switch (key.Key)
            {
                case ConsoleKey.D1:
                    await endpointInstance.Publish<IMyEvent>(m =>
                    {
                        m.EventId = eventId;
                        m.Time = DateTime.Now.Second > 30 ? (DateTime?) DateTime.Now : null;
                        m.Duration = TimeSpan.FromSeconds(99999D);
                    })
                    .ConfigureAwait(false);
                    Console.WriteLine($"Published IMyEvent with Id {eventId}.");
                    continue;
                case ConsoleKey.D2:
                    var eventMessage = new EventMessage
                    {
                        EventId = eventId,
                        Time = DateTime.Now.Second > 30 ? (DateTime?) DateTime.Now : null,
                        Duration = TimeSpan.FromSeconds(99999D)
                    };
                    await endpointInstance.Publish(eventMessage)
                        .ConfigureAwait(false);
                    Console.WriteLine($"Published EventMessage with Id {eventId}.");
                    continue;
                case ConsoleKey.D3:
                    var anotherEventMessage = new AnotherEventMessage
                    {
                        EventId = eventId,
                        Time = DateTime.Now.Second > 30 ? (DateTime?) DateTime.Now : null,
                        Duration = TimeSpan.FromSeconds(99999D)
                    };
                    await endpointInstance.Publish(anotherEventMessage)
                        .ConfigureAwait(false);
                    Console.WriteLine($"Published AnotherEventMessage with Id {eventId}.");
                    continue;
                default:
                    return;
            }
        }
        #endregion
    }
Esempio n. 30
0
    static async Task Data(IEndpointInstance endpointInstance)
    {
        Guid requestId = Guid.NewGuid();

        await endpointInstance.Send(new LargeMessage
        {
            RequestId = requestId,
            LargeDataBus = new byte[1024*1024*5]
        });

        Console.WriteLine("Request sent id: " + requestId);
    }
        public async Task Write()
        {
            EndpointConfiguration endpointConfiguration = new EndpointConfiguration(endpointName);
            IEnumerable <Type>    typesToScan           = TypeScanner.NestedTypes <HeaderWriterAudit>();

            endpointConfiguration.SetTypesToScan(typesToScan);
            endpointConfiguration.EnableInstallers();
            endpointConfiguration.SendFailedMessagesTo("error");
            endpointConfiguration.AuditProcessedMessagesTo(endpointName);
            endpointConfiguration.UsePersistence <InMemoryPersistence>();
            endpointConfiguration.RegisterComponents(c => c.ConfigureComponent <Mutator>(DependencyLifecycle.InstancePerCall));

            IEndpointInstance endpoint = await Endpoint.Start(endpointConfiguration);

            await endpoint.SendLocal(new MessageToSend());

            ManualResetEvent.WaitOne();
            await endpoint.Stop();
        }
Esempio n. 32
0
    static Task SendStartMessages(IEndpointInstance endpoint)
    {
        var tasks = new List <Task>();

        for (var i = 0; i < iterations; i++)
        {
            var sendOptions = new SendOptions();
            sendOptions.RouteToThisEndpoint();
            var sendMessage = new SendMessage
            {
                Blob = new DataBusProperty <byte[]>(Helpers.Buffer)
            };
            var send = endpoint.Send(sendMessage, sendOptions);
            tasks.Add(send);
            Console.WriteLine("Sending " + i);
        }

        return(Task.WhenAll(tasks));
    }
        public async Task Write()
        {
            BusConfiguration config = new BusConfiguration();

            config.EndpointName(endpointName);
            IEnumerable <Type> typesToScan = TypeScanner.NestedTypes <HeaderWriterSaga>();

            config.SetTypesToScan(typesToScan);
            config.SendFailedMessagesTo("error");
            config.EnableInstallers();
            config.UsePersistence <InMemoryPersistence>();
            config.RegisterComponents(c => c.ConfigureComponent <Mutator>(DependencyLifecycle.InstancePerCall));

            IEndpointInstance endpoint = await Endpoint.Start(config);

            await endpoint.SendLocal(new StartSaga1Message());

            CountdownEvent.Wait();
        }
Esempio n. 34
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            var builder = new ContainerBuilder();

            builder.Populate(services);
            var endpointConfiguration = new EndpointConfiguration(endpointName: "OrderAPI");
            var transport             = endpointConfiguration.UseTransport <LearningTransport>();
            var routing = transport.Routing();

            routing.RouteToEndpoint(typeof(PlaceOrder), "Order");
            IEndpointInstance endpointInstance = Endpoint.Start(endpointConfiguration).Result;

            builder.RegisterInstance(endpointInstance).As <IEndpointInstance>().PropertiesAutowired();
            //TODO: Register
            this.ApplicationContainer = builder.Build();

            return(new AutofacServiceProvider(this.ApplicationContainer));
        }
Esempio n. 35
0
    static async Task SendMessageWithHttpStream(IEndpointInstance endpointInstance)
    {
        #region send-message-with-http-stream

        using (WebClient webClient = new WebClient())
        {
            MessageWithStream message = new MessageWithStream
            {
                SomeProperty   = "This message contains a stream",
                StreamProperty = webClient.OpenRead("http://www.particular.net")
            };
            await endpointInstance.Send("Samples.PipelineStream.Receiver", message);
        }

        #endregion

        Console.WriteLine();
        Console.WriteLine("Message with http stream sent");
    }
        private static void Main(string[] args)
        {
            var configurationBuilder = new ConfigurationBuilder();

            configurationBuilder.AddEnvironmentVariables("TODOMVC_");

            Configuration = configurationBuilder.Build();

            Console.Title = "Application";
            Log.Logger    = new LoggerConfiguration()
                            .MinimumLevel.Warning()
                            .WriteTo.Console(outputTemplate: "[{Level}] {Message}{NewLine}{Exception}")
                            .CreateLogger();

            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionTrapper;

            NServiceBus.Logging.LogManager.Use <SerilogFactory>();

            _container = new Container(x =>
            {
                x.For <IValidatorFactory>().Use <StructureMapValidatorFactory>();

                x.Scan(y =>
                {
                    y.TheCallingAssembly();

                    y.WithDefaultConventions();
                });
            });

            // Start the bus
            _bus = InitBus().Result;

            Console.WriteLine("Press CTRL+C to exit...");
            Console.CancelKeyPress += (sender, eArgs) =>
            {
                QuitEvent.Set();
                eArgs.Cancel = true;
            };
            QuitEvent.WaitOne();

            _bus.Stop().Wait();
        }
Esempio n. 37
0
        static async Task RunLoop(IEndpointInstance endpointInstance)
        {
            var lastOrder = string.Empty;

            while (true)
            {
                log.Info("Press 'P' to place an order, Press 'C' to cancel a placed order, or 'Q' to quit the program");
                var key = Console.ReadKey();
                Console.WriteLine();

                switch (key.Key)
                {
                case ConsoleKey.P:
                    var command = new PlaceOrder
                    {
                        OrderId = Guid.NewGuid().ToString()
                    };
                    log.Info($"Sending PlaceOrder command, OrderId {command.OrderId}");
                    //await endpointInstance.SendLocal(command);
                    lastOrder = command.OrderId;
                    await endpointInstance.Send(command);

                    break;

                case ConsoleKey.C:
                    var cancelCommand = new CancelOrder
                    {
                        OrderId = lastOrder
                    };
                    await endpointInstance.Send(cancelCommand);

                    log.Info($"Sent a correlated message to {cancelCommand.OrderId}");
                    break;

                case ConsoleKey.Q:
                    return;

                default:
                    log.Info("Unknown command. Please try again");
                    break;
                }
            }
        }
Esempio n. 38
0
        Usage(EndpointConfiguration endpointConfiguration, IEndpointInstance endpoint)
        {
            #region GatewayConfiguration

            endpointConfiguration.SendFailedMessagesTo("error");
            endpointConfiguration.EnableFeature <Gateway>();

            #endregion

            #region GatewayDefaultRetryPolicyConfiguration

            endpointConfiguration.Gateway().Retries(5, TimeSpan.FromMinutes(1));

            #endregion

            #region GatewayCustomRetryPolicyConfiguration

            endpointConfiguration.Gateway().CustomRetryPolicy((message, exception, currentRetry) => { return(currentRetry > 4 ? TimeSpan.MinValue : TimeSpan.FromSeconds(currentRetry * 60)); });

            #endregion

            #region GatewayDisableRetriesConfiguration

            endpointConfiguration.Gateway().DisableRetries();

            #endregion

            #region GatewayChannelFactoriesConfiguration

            endpointConfiguration.Gateway().ChannelFactories(channelType => { return(new CustomChannelSender()); }, channelType => { return(new CustomChannelReceiver()); });

            #endregion

            #region SendToSites

            endpoint.SendToSites(new[]
            {
                "SiteA",
                "SiteB"
            }, new MyMessage());

            #endregion
        }
    static async Task AsyncMain()
    {
        EndpointConfiguration endpointConfiguration = new EndpointConfiguration();

        endpointConfiguration.EndpointName("Store.CustomerRelations");
        endpointConfiguration.ApplyCommonConfiguration();
        endpointConfiguration.SendFailedMessagesTo("error");
        IEndpointInstance endpoint = await Endpoint.Start(endpointConfiguration);

        try
        {
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
        finally
        {
            await endpoint.Stop();
        }
    }
Esempio n. 40
0
        async Task Simple(IEndpointInstance endpoint)
        {
            #region CancelCallback

            var cancellationTokenSource = new CancellationTokenSource();
            cancellationTokenSource.CancelAfter(TimeSpan.FromSeconds(5));
            var message = new Message();
            try
            {
                var response = await endpoint.Request <int>(message, cancellationTokenSource.Token)
                               .ConfigureAwait(false);
            }
            catch (OperationCanceledException)
            {
                // Exception that is raised when the CancellationTokenSource is canceled
            }

            #endregion
        }
Esempio n. 41
0
    static async Task Start(IEndpointInstance endpointInstance)
    {
        Console.WriteLine("Press 'p' to publish event");
        Console.WriteLine("Press any other key to exit");

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

            var myEvent = new MyEvent
            {
                Consumer1Property = "Consumer1Info",
                Consumer2Property = "Consumer2Info"
            };
            await endpointInstance.Publish(myEvent)
            .ConfigureAwait(false);
        }
    }
Esempio n. 42
0
        public async Task Send()
        {
            var randomName     = Path.GetFileNameWithoutExtension(Path.GetRandomFileName());
            var endpointName   = $"send-{randomName}";
            var errorQueueName = $"send-{randomName}-error";

            var state = new State();
            IEndpointInstance endpoint = null;

            try
            {
                endpoint = await StartEndpoint(state, endpointName, errorQueueName).ConfigureAwait(false);

                var message = @"{ Property: 'Value' }";

                var headers = new Dictionary <string, string>
                {
                    { "NServiceBus.EnclosedMessageTypes", typeof(MessageToSend).FullName },
                    { "NServiceBus.MessageId", Guid.NewGuid().ToString() }
                };

                using (var client = ClientFactory.CreateSqsClient())
                {
                    await NativeSend.SendMessage(client, endpointName, message, headers)
                    .ConfigureAwait(false);
                }

                Assert.AreEqual("Value", await state.Signal.Task.ConfigureAwait(false));
            }
            finally
            {
                if (endpoint != null)
                {
                    await endpoint.Stop().ConfigureAwait(false);
                }

                await DeleteEndpointQueues.DeleteQueuesForEndpoint(endpointName, includeRetries : true)
                .ConfigureAwait(false);

                await QueueDeletionUtils.DeleteQueue(errorQueueName)
                .ConfigureAwait(false);
            }
        }
Esempio n. 43
0
    static async Task Run(IEndpointInstance endpointInstance)
    {
        Console.WriteLine("Press 'Enter' to send a Message");
        Console.WriteLine("Press any other key to exit");

        while (true)
        {
            ConsoleKeyInfo key = Console.ReadKey();
            if (key.Key != ConsoleKey.Enter)
            {
                return;
            }
            Message message = new Message();
            await endpointInstance.SendLocal(message);

            Console.WriteLine();
            Console.WriteLine("Message sent");
        }
    }
Esempio n. 44
0
        public override async Task Start(CancellationToken token)
        {
            ScenarioContext.CurrentEndpoint = configuration.EndpointName;
            try
            {
                endpointInstance = await startCallback(startable).ConfigureAwait(false);

                if (token.IsCancellationRequested)
                {
                    throw new OperationCanceledException("Endpoint start was aborted");
                }
            }
            catch (Exception ex)
            {
                Logger.Error("Failed to start endpoint " + configuration.EndpointName, ex);

                throw;
            }
        }
Esempio n. 45
0
    static async Task AsyncRun()
    {
        BusConfiguration busConfiguration = new BusConfiguration();

        busConfiguration.EndpointName("Samples.Headers");

        busConfiguration.UseSerialization <JsonSerializer>();
        busConfiguration.EnableInstallers();
        busConfiguration.UsePersistence <InMemoryPersistence>();
        busConfiguration.SendFailedMessagesTo("error");

        busConfiguration.RegisterComponents(components =>
        {
            components.ConfigureComponent <MutateIncomingMessages>(DependencyLifecycle.InstancePerCall);
            components.ConfigureComponent <MutateIncomingTransportMessages>(DependencyLifecycle.InstancePerCall);
            components.ConfigureComponent <MutateOutgoingMessages>(DependencyLifecycle.InstancePerCall);
            components.ConfigureComponent <MutateOutgoingTransportMessages>(DependencyLifecycle.InstancePerCall);
        });

        #region global-all-outgoing

        busConfiguration.AddHeaderToAllOutgoingMessages("AllOutgoing", "ValueAllOutgoing");

        #endregion
        IEndpointInstance endpoint = await Endpoint.Start(busConfiguration);

        try
        {
            #region sending

            MyMessage myMessage = new MyMessage();
            await endpoint.SendLocal(myMessage);

            #endregion

            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
        finally
        {
            await endpoint.Stop();
        }
    }
    public async Task Run()
    {
        if (endpointConfiguration == null)
        {
            var message = $"{nameof(EndpointCommunicationListener)} Run() method should be invoked after communication listener has been opened and not before.";

            Logger.Log(message);
            throw new Exception(message);
        }

        var zipcodeVotes = await stateManager.GetOrAddAsync <IReliableDictionary <Guid, SagaEntry> >("zipcode-votes")
                           .ConfigureAwait(false);

        await zipcodeVotes.ClearAsync()
        .ConfigureAwait(false);

        endpointInstance = await Endpoint.Start(endpointConfiguration)
                           .ConfigureAwait(false);
    }
Esempio n. 47
0
    public static async Task RunTests(IEndpointInstance bus)
    {
        await Task.Delay(TimeSpan.FromSeconds(10)).ConfigureAwait(false);

        await bus.Initiate().ConfigureAwait(false);

        for (var i = 0; i < 10; i++)
        {
            await Task.Delay(TimeSpan.FromSeconds(5)).ConfigureAwait(false);

            if (Verifier.IsFinished())
            {
                break;
            }
        }
        await bus.Stop().ConfigureAwait(false);

        Verifier.AssertExpectations();
    }
Esempio n. 48
0
    static async Task Main()
    {
        Console.Title = "Samples.Autofac";

        #region ContainerConfiguration

        var endpointConfiguration = new EndpointConfiguration("Samples.Autofac");

        var builder = new ContainerBuilder();

        IEndpointInstance endpoint = null;
        builder.Register(x => endpoint)
        .As <IEndpointInstance>()
        .SingleInstance();

        builder.RegisterInstance(new MyService());

        var container = builder.Build();

        endpointConfiguration.UseContainer <AutofacBuilder>(
            customizations: customizations =>
        {
            customizations.ExistingLifetimeScope(container);
        });

        #endregion

        endpointConfiguration.UsePersistence <LearningPersistence>();
        endpointConfiguration.UseTransport <LearningTransport>();

        endpoint = await Endpoint.Start(endpointConfiguration)
                   .ConfigureAwait(false);

        var endpointInstance = container.Resolve <IEndpointInstance>();
        var myMessage        = new MyMessage();
        await endpointInstance.SendLocal(myMessage)
        .ConfigureAwait(false);

        Console.WriteLine("Press any key to exit");
        Console.ReadKey();
        await endpointInstance.Stop()
        .ConfigureAwait(false);
    }
Esempio n. 49
0
        public async Task Write()
        {
            EndpointConfiguration endpointConfiguration = new EndpointConfiguration(endpointName);

            Type[]             callbackTypes = typeof(RequestResponseExtensions).Assembly.GetTypes();
            IEnumerable <Type> typesToScan   = TypeScanner.NestedTypes <HeaderWriterReturn>(callbackTypes);

            endpointConfiguration.SetTypesToScan(typesToScan);
            endpointConfiguration.ScaleOut().InstanceDiscriminator("A");
            endpointConfiguration.SendFailedMessagesTo("error");
            endpointConfiguration.EnableInstallers();
            endpointConfiguration.UsePersistence <InMemoryPersistence>();
            endpointConfiguration.RegisterComponents(c => c.ConfigureComponent <Mutator>(DependencyLifecycle.InstancePerCall));
            IEndpointInstance endpoint = await Endpoint.Start(endpointConfiguration);

            await endpoint.SendLocal(new MessageToSend());

            ManualResetEvent.WaitOne();
        }
        public async Task Write()
        {
            EndpointConfiguration endpointConfiguration = new EndpointConfiguration(EndpointName);
            IEnumerable <Type>    typesToScan           = TypeScanner.NestedTypes <HeaderWriterPublish>();

            endpointConfiguration.SetTypesToScan(typesToScan);
            endpointConfiguration.SendFailedMessagesTo("error");
            endpointConfiguration.EnableInstallers();
            endpointConfiguration.UsePersistence <InMemoryPersistence>();
            endpointConfiguration.RegisterComponents(c => c.ConfigureComponent <Mutator>(DependencyLifecycle.InstancePerCall));
            IEndpointInstance endpoint = await Endpoint.Start(endpointConfiguration);

            //give time for the subscription to happen
            Thread.Sleep(3000);
            await endpoint.Publish(new MessageToPublish());

            ManualResetEvent.WaitOne();
            await endpoint.Stop();
        }
        public static Task SendWithSignalRMetaData(this IEndpointInstance endpointInstance, ICommand command, HttpRequestMessage request, SendOptions incomingOptions = null)
        {
            var sendOptions = incomingOptions ?? new SendOptions();

            if (request.Headers.Contains(MetaDataConstants.SignalRConnectionId))
            {
                var connectionId = request.Headers.GetValues(MetaDataConstants.SignalRConnectionId).Single();
                sendOptions.SetHeader(MetaDataConstants.SignalRConnectionId, connectionId);
                if (request.Properties.ContainsKey(MetaDataConstants.SignalRCorrelationId))
                {
                    var correlationId = request.Properties[MetaDataConstants.SignalRCorrelationId] as string;
                    sendOptions.SetHeader(MetaDataConstants.SignalRCorrelationId, correlationId);
                }
            }
            sendOptions.SetHeader(MetaDataConstants.CommandSentUtc, ZaphodTime.UtcNow.SerializeViewModel());
            sendOptions.SetUserInfoOnHeader();

            return(endpointInstance.Send(command, sendOptions));
        }
        public async Task <IEndpointInstance> StartAsync()
        {
            var sbConnString      = ConfigurationManager.AppSettings["AzureServiceBusConnString"];
            var endpointName      = ConfigurationManager.AppSettings["QueueName"];
            var storageConnString = ConfigurationManager.ConnectionStrings["AzureWebJobsStorage"].ConnectionString;

            var endpointConfiguration = new EndpointConfiguration(endpointName);

            endpointConfiguration.UseSerialization <NewtonsoftSerializer>();
            endpointConfiguration.UsePersistence <InMemoryPersistence>();
            endpointConfiguration.EnableInstallers();

            var transport = endpointConfiguration.UseTransport <AzureServiceBusTransport>();

            transport.ConnectionString(sbConnString);

            endpointConfiguration.SendFailedMessagesTo($"{endpointName}_errors");

            /*endpointConfiguration.AuditProcessedMessagesTo("audit");
             * endpointConfiguration.SendHeartbeatTo("Particular.ServiceControl");
             * var metrics = endpointConfiguration.EnableMetrics();
             * metrics.SendMetricDataToServiceControl("Particular.Monitoring", TimeSpan.FromMilliseconds(500));*/

            transport.UseForwardingTopology();

            var builder = new ContainerBuilder();

            builder.Register(x => _endpointInstance).As <IEndpointInstance>().SingleInstance();
            builder.Register(x => new StorageRepository(storageConnString)).AsSelf();

            var container = builder.Build();

            endpointConfiguration.UseContainer <AutofacBuilder>(
                customizations =>
            {
                customizations.ExistingLifetimeScope(container);
            });

            _endpointInstance = await Endpoint.Start(endpointConfiguration)
                                .ConfigureAwait(false);

            return(_endpointInstance);
        }
Esempio n. 53
0
        async Task Simple(EndpointConfiguration endpointConfiguration, IEndpointInstance endpoint, SendOptions sendOptions, ILog log)
        {
            #region Callbacks-InstanceId

            endpointConfiguration.ScaleOut()
            .InstanceDiscriminator("uniqueId");

            #endregion

            #region ObjectCallback

            var message  = new Message();
            var response = await endpoint.Request <ResponseMessage>(message, sendOptions)
                           .ConfigureAwait(false);

            log.Info("Callback received with response:" + response.Property);

            #endregion
        }
Esempio n. 54
0
    static async Task AsyncMain()
    {
        LogManager.Use <DefaultFactory>()
        .Level(LogLevel.Warn);

        #region DisableSLR
        BusConfiguration busConfiguration = new BusConfiguration();
        busConfiguration.EndpointName("Samples.ErrorHandling.WithoutSLR");
        busConfiguration.DisableFeature <SecondLevelRetries>();
        #endregion
        busConfiguration.UseSerialization <JsonSerializer>();
        busConfiguration.UsePersistence <InMemoryPersistence>();
        busConfiguration.EnableInstallers();
        busConfiguration.SendFailedMessagesTo("error");

        IEndpointInstance endpoint = await Endpoint.Start(busConfiguration);

        try
        {
            IBusContext busContext = endpoint.CreateBusContext();
            Console.WriteLine("Press enter to send a message that will throw an exception.");
            Console.WriteLine("Press any key to exit");

            while (true)
            {
                ConsoleKeyInfo key = Console.ReadKey();
                if (key.Key != ConsoleKey.Enter)
                {
                    return;
                }
                MyMessage m = new MyMessage
                {
                    Id = Guid.NewGuid()
                };
                await busContext.SendLocal(m);
            }
        }
        finally
        {
            await endpoint.Stop();
        }
    }
Esempio n. 55
0
    public static async Task Start(IEndpointInstance endpointInstance)
    {
        Console.WriteLine("Press 'C' to send a command");
        Console.WriteLine("Press 'R' to send a request");
        Console.WriteLine("Press 'D' to send a large message that is marked to be sent using Data Bus");
        Console.WriteLine("Press 'X' to send a message that is marked with expiration time.");
        Console.WriteLine("Press any other key to exit");

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

            switch (key.Key)
            {
            case ConsoleKey.C:
                await SendCommand(endpointInstance)
                .ConfigureAwait(false);

                continue;

            case ConsoleKey.R:
                await SendRequest(endpointInstance)
                .ConfigureAwait(false);

                continue;

            case ConsoleKey.D:
                await Data(endpointInstance)
                .ConfigureAwait(false);

                continue;

            case ConsoleKey.X:
                await Expiration(endpointInstance)
                .ConfigureAwait(false);

                continue;
            }
            return;
        }
    }
Esempio n. 56
0
        static async Task Start()
        {
            var config = new EndpointConfiguration("Sender");

            config.UseSerialization <NewtonsoftSerializer>();
            config.SendFailedMessagesTo("error");
            config.EnableInstallers();
            config.UsePersistence <InMemoryPersistence>();

            var useRouter = SettingsReader <bool> .Read("UseRouter", true);

            var connectionString = SettingsReader <string> .Read("SqlConnectionString", "data source=(local); initial catalog=loadtest; integrated security=true");

            var bodySize = SettingsReader <int> .Read("BodySize");

            var maxConcurrency = SettingsReader <int> .Read("MaxConcurrency", 32);

            config.RegisterComponents(c => c.RegisterSingleton(new LoadGenerator((info, token) => GenerateMessages(bodySize, info, token, maxConcurrency), 10000, 20000)));

            var senderTransport = config.UseTransport <SqlServerTransport>();

            senderTransport.UseNativeDelayedDelivery().DisableTimeoutManagerCompatibility();
            senderTransport.ConnectionString(connectionString);
            senderTransport.Transactions(TransportTransactionMode.SendsAtomicWithReceive);

            if (useRouter)
            {
                var senderRouterConnector = senderTransport.Routing().ConnectToRouter("Sender.Router");
                senderRouterConnector.RouteToEndpoint(typeof(MyMessage), "Receiver");
            }
            else
            {
                senderTransport.Routing().RouteToEndpoint(typeof(MyMessage), "Receiver");
            }

            endpointInstance = await Endpoint.Start(config);

            Console.WriteLine("Press <enter> to exit.");
            Console.ReadLine();

            await endpointInstance.Stop();
        }
Esempio n. 57
0
        static async Task RunLoop(IEndpointInstance endpointInstance)
        {
            int currentFloor = 0;

            log.Info("Press 'U' to go to Up, 'D' to go Down, or 'Q' to quit.");
            while (true)
            {
                log.Info($"You are on floor {currentFloor}. {hallwayButtonPanel.StatusText()}");

                var key = Console.ReadKey();
                Console.WriteLine();

                switch (key.Key)
                {
                case ConsoleKey.U:
                case ConsoleKey.D:
                    // Instantiate the command
                    var command = new SummonElevator
                    {
                        CurrentFloor = new Floor()
                        {
                            Id = currentFloor
                        },
                        RequestedDirection = key.Key == ConsoleKey.U? Direction.Up : Direction.Down
                    };

                    // Send the command to the local endpoint
                    //log.Info($"Sending GoToFloor command, Floor = {command.Floor}");
                    await endpointInstance.Send(command)
                    .ConfigureAwait(false);

                    break;

                case ConsoleKey.Q:
                    return;

                default:
                    log.Info("Unknown input. Please try again.");
                    break;
                }
            }
        }
Esempio n. 58
0
    static async Task AsyncMain()
    {
        BusConfiguration busConfiguration = new BusConfiguration();

        busConfiguration.EndpointName("Samples.PerfCounters");
        busConfiguration.UseSerialization <JsonSerializer>();
        busConfiguration.EnableInstallers();
        busConfiguration.UsePersistence <InMemoryPersistence>();
        busConfiguration.SendFailedMessagesTo("error");

        #region enable-counters
        busConfiguration.EnableCriticalTimePerformanceCounter();
        busConfiguration.EnableSLAPerformanceCounter(TimeSpan.FromSeconds(100));
        #endregion

        IEndpointInstance endpoint = await Endpoint.Start(busConfiguration);

        try
        {
            Console.WriteLine("Press enter to send 10 messages with random sleep");
            Console.WriteLine("Press any key to exit");

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

                if (key.Key != ConsoleKey.Enter)
                {
                    break;
                }
                for (int i = 0; i < 10; i++)
                {
                    await endpoint.SendLocal(new MyMessage());
                }
            }
        }
        finally
        {
            await endpoint.Stop();
        }
    }
        static async Task Main(string[] args)
        {
            var configuration = new EndpointConfiguration(Shared.Configuration.SenderEndpointName);

            configuration.UseTransport <SqlServerTransport>()
            .ConnectionString(() => Shared.Configuration.ConnectionString)
            .Routing().RouteToEndpoint(typeof(TestCommand).Assembly, Shared.Configuration.ReceiverEndpointName);

            configuration.UsePersistence <InMemoryPersistence>();

            configuration.Conventions().DefiningCommandsAs(t => t == typeof(TestCommand));

            configuration.EnableInstallers();

            endpoint = await Endpoint.Start(configuration);

            var rootCommand = new RootCommand();

            rootCommand.AddCommand(CreateChildCommand(nameof(Send), "send"));
            rootCommand.AddCommand(CreateChildCommand(nameof(ThrottledSend), "throttled-send"));
            rootCommand.AddCommand(CreateChildCommand(nameof(FillQueue), "fill"));
            rootCommand.AddCommand(CreateChildCommand(nameof(ResetStatistics), "reset"));

            var ctSource = new CancellationTokenSource();

            ct = ctSource.Token;

            var task = rootCommand.InvokeAsync(args);

            while (ctSource.IsCancellationRequested == false && task.IsCompleted == false)
            {
                if (Console.KeyAvailable && Console.ReadKey().Key == ConsoleKey.Enter)
                {
                    ctSource.Cancel();
                    break;
                }

                await Task.Delay(TimeSpan.FromMilliseconds(500));
            }

            await task;
        }
Esempio n. 60
0
    static async Task MainAsync()
    {
        Console.Title = "Samples.ASB.Polymorphic.Subscriber";
        EndpointConfiguration endpointConfiguration = new EndpointConfiguration("Samples.ASB.Polymorphic.Subscriber");
        var transport = endpointConfiguration.UseTransport <AzureServiceBusTransport>();

        transport.UseTopology <EndpointOrientedTopology>();
        transport.ConnectionString(Environment.GetEnvironmentVariable("AzureServiceBus.ConnectionString"));
        endpointConfiguration.SendFailedMessagesTo("error");

        #region DisableAutoSubscripton

        endpointConfiguration.DisableFeature <AutoSubscribe>();

        #endregion


        endpointConfiguration.UseSerialization <JsonSerializer>();
        endpointConfiguration.EnableInstallers();
        endpointConfiguration.UsePersistence <InMemoryPersistence>();
        endpointConfiguration.DisableFeature <SecondLevelRetries>();


        IEndpointInstance endpoint = await Endpoint.Start(endpointConfiguration);

        try
        {
            #region ControledSubscriptions

            await endpoint.Subscribe <BaseEvent>();

            #endregion

            Console.WriteLine("Subscriber is ready to receive events");
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
        finally
        {
            await endpoint.Stop();
        }
    }