Example #1
0
        public static async Task StartAsync(
            ISendOnlyBus bus,
            string track,
            string consumerKey,
            string consumerSecret,
            string accessToken,
            string accessTokenSecret)
        {
            var credentials = new TwitterCredentials(consumerKey, consumerSecret, accessToken, accessTokenSecret);
            while (true)
            {
                try
                {
                    var stream = Stream.CreateFilteredStream(credentials);
                    stream.AddTrack(track);

                    var sessionId = Guid.NewGuid();
                    stream.StreamStarted += (sender, args) =>
                    {
                        sessionId = Guid.NewGuid();
                        ColorConsole.WriteLine(
                            $"{DateTime.UtcNow.ToLocalTime()}".DarkGray(),
                            " ",
                            $" {track} ".DarkCyan().OnWhite(),
                            " ",
                            "stream started with session ID".Gray(),
                            " ",
                            $"{sessionId}".White());
                    };

                    stream.StreamStopped += (sender, args) => ColorConsole.WriteLine(
                        $"{DateTime.UtcNow.ToLocalTime()} ".DarkGray(),
                        $" {track} ".DarkCyan().OnWhite(),
                        " stream stopped.".Red(),
                        args.Exception == null ? string.Empty : $" {args.Exception.Message}".DarkRed());

                    stream.MatchingTweetReceived += (sender, e) =>
                    {
                        var analyzeTweet = TweetMapper.Map(e.Tweet, track);
                        Writer.Write(analyzeTweet.Tweet);
                        bus.Send(analyzeTweet);

                        var tweetReceived = new TweetReceived()
                        {
                            SessionId = sessionId,
                            Track = track,
                            TweetId = e.Tweet.Id
                        };
                        bus.Publish(tweetReceived);
                    };

                    await stream.StartStreamMatchingAnyConditionAsync();
                }
                catch (Exception ex)
                {
                    ColorConsole.WriteLine($"{DateTime.UtcNow.ToLocalTime()} ".DarkGray(), "Error listening to Twitter stream.".Red(), $" {ex.Message}".DarkRed());
                    Thread.Sleep(1000);
                }
            }
        }
Example #2
0
        public static void Init()
        {
            if (Bus != null)
            {
                return;
            }

            lock (padlock)
            {
                if (Bus != null)
                {
                    return;
                }

                var cfg = new BusConfiguration();

                cfg.UseTransport <MsmqTransport>();
                cfg.UsePersistence <InMemoryPersistence>();
                cfg.EndpointName("FileImportProcessingSagaNSB5.ConsoleClient");
                cfg.PurgeOnStartup(true);
                cfg.EnableInstallers();

                Bus = NServiceBus.Bus.CreateSendOnly(cfg);
            }
        }
Example #3
0
        private static void RunOnce()
        {
            var cts = new CancellationTokenSource();

            EventWaitHandle sequentialStarter = new AutoResetEvent(true);

            Task[] tasks =
            {
                StartEndpoint(new FirstHandlerInSagaEndpoint(),  cts.Token, sequentialStarter),
                StartEndpoint(new SecondHandlerInSagaEndpoint(), cts.Token, sequentialStarter),
                StartEndpoint(new DoingSomethingElseEndpoint(),  cts.Token, sequentialStarter)
            };

            // let everything settle down
            Task.Delay(20000).Wait();

            // send a message that does something
            BusConfiguration config = new BusConfiguration();

            config.UseTransport <AzureServiceBusTransport>();
            using (ISendOnlyBus bus = Bus.CreateSendOnly(config))
            {
                bus.Send <RunBusinessActivity>(m => m.ProcessId = Guid.NewGuid().ToString());
            }

            // and then close the system down after another ten seconds
            cts.CancelAfter(10000);
            Task.WaitAll(tasks);
        }
Example #4
0
        static void StartBus()
        {
            try
            {
                var myDocumentStore = new DocumentStore { ConnectionStringName = "EpiFlowDB" };

                var busConfiguration = new BusConfiguration();
                busConfiguration.EndpointName("EpiFlow.Messages");
                busConfiguration.UseSerialization<JsonSerializer>();
                busConfiguration.UsePersistence<RavenDBPersistence>()
                    .UseDocumentStoreForSubscriptions(myDocumentStore)
                    .UseDocumentStoreForSagas(myDocumentStore)
                    .UseDocumentStoreForTimeouts(myDocumentStore);
                busConfiguration.UseTransport<RabbitMQTransport>();
                busConfiguration.DefineCriticalErrorAction(OnCriticalError);
                busConfiguration.Transactions().DisableDistributedTransactions();

                if (Environment.UserInteractive && Debugger.IsAttached)
                {
                    busConfiguration.EnableInstallers();
                }
                _bus = Bus.CreateSendOnly(busConfiguration);
            }
            catch (Exception exception)
            {
                OnCriticalError("Failed to start the bus.", exception);
            }
        }
        private static void PublishAgreementPlacedForOnlineBrokerEvent(ISendOnlyBus bus)
        {
            const int OnlineBrokerId       = 456;
            var       agreementPlacedEvent = CreateAgreementPlacedEvent(OnlineBrokerId);

            bus.Publish(agreementPlacedEvent);
        }
        private static void PublishAgreementPlacedForRemoteBrokerEvent(ISendOnlyBus bus)
        {
            const int RemoteBrokerId       = 123;
            var       agreementPlacedEvent = CreateAgreementPlacedEvent(RemoteBrokerId);

            bus.Publish(agreementPlacedEvent);
        }
Example #7
0
        protected void Application_Start()
        {
            #region ApplicationStart
            var builder = new ContainerBuilder();

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

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

            var configuration = new BusConfiguration();
            configuration.EndpointName("Samples.MvcInjection.WebApplication");
            configuration.UseContainer <AutofacBuilder>(c => c.ExistingLifetimeScope(container));
            configuration.UseSerialization <JsonSerializer>();
            configuration.UsePersistence <InMemoryPersistence>();
            configuration.EnableInstallers();

            bus = Bus.CreateSendOnly(configuration);

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            #endregion
        }
    protected void Application_Start()
    {
        #region ApplicationStart

        ContainerBuilder builder = new ContainerBuilder();

        // Register the 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 resolve IBus from the components.
        busConfiguration.UseContainer <AutofacBuilder>(c => c.ExistingLifetimeScope(container));
        busConfiguration.UseSerialization <JsonSerializer>();
        busConfiguration.UsePersistence <InMemoryPersistence>();
        busConfiguration.EnableInstallers();

        bus = Bus.CreateSendOnly(busConfiguration);

        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

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

        #endregion
    }
        public ExampleModule(IRepositoryOfId<int> repository, IMappingEngine engine, ISendOnlyBus bus)
        {
            Get["/examples"] = _ => repository.Query<ExampleEntity>()
                .Project().To<ExampleModel>()
                .ToList();

            Get["/example/{id:int}"] = _ => {
                var entity = repository.Load<ExampleEntity>(_.id);
                return engine.Map<ExampleEntity, ExampleModel>(entity);
            };

            Post["/examples"] = _ => {
                var model = this.BindAndValidateModel<NewExampleModel>();

                var entity = new ExampleEntity(model.Name);
                repository.Save(entity);

                return new NewExampleCreatedModel { Id = entity.ID };
            };

            Post["/examples/close"] = _ => {
                var model = this.BindAndValidateModel<CloseExampleModel>();
                bus.Send(new CloseExampleCommand {Id = model.Id});
                return HttpStatusCode.OK;
            };

            Delete["/example/{id:int}"] = _ => {
                repository.Delete<ExampleEntity>(_.id);
                return HttpStatusCode.OK;
            };
        }
Example #10
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();

        bus = Bus.CreateSendOnly(busConfiguration);

        DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

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

        #endregion
    }
Example #11
0
        void SendOnly(BusConfiguration busConfiguration)
        {
            #region 4to5SendOnly

            ISendOnlyBus bus = Bus.CreateSendOnly(busConfiguration);

            #endregion
        }
Example #12
0
        protected void Application_Start()
        {
            #region SetAutofacContainer
            //Create Autofac builder
            var builder = new ContainerBuilder();
            //Now register all depedencies to your custom IoC container


            //register mvc controller
            builder.RegisterControllers(typeof(MvcApplication).Assembly);

            builder.RegisterAssemblyTypes(typeof(MvcApplication).Assembly)
            .AsImplementedInterfaces();

            builder.RegisterModelBinderProvider();

            // Register the Web API controllers.
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            // builder.RegisterType(typeof(IHandleMessages<CreateMedicalProcedureApprovalRequest>));
            // builder.RegisterType(typeof(IHandleMessages<ApprovalCreated>));
            builder.RegisterType(typeof(ICommand));
            builder.RegisterType(typeof(IMessage));
            builder.RegisterGeneric(typeof(Repository <>))
            .As(typeof(IRepository <>));
            builder.RegisterType <EventStore>().As <IEventStore>();


            var containerBuilder = builder.Build();

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

            //MVC resolver
            DependencyResolver.SetResolver(new AutofacDependencyResolver(containerBuilder));

            // Create the depenedency resolver for Web Api
            // Configure Web API with the dependency resolver.
            GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(containerBuilder);
            var config = new HttpConfiguration();
            config.DependencyResolver = new AutofacWebApiDependencyResolver(containerBuilder);

            #endregion SetAutofacContainer

            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
Example #13
0
        public void SendOnly()
        {
            #region 4to5SendOnly

            BusConfiguration busConfiguration = new BusConfiguration();
            ISendOnlyBus     bus = Bus.CreateSendOnly(busConfiguration);

            #endregion
        }
Example #14
0
        void SendOnly()
        {
            #region Hosting-SendOnly

            BusConfiguration busConfiguration = new BusConfiguration();
            ISendOnlyBus     bus = Bus.CreateSendOnly(busConfiguration);

            #endregion
        }
Example #15
0
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            DatabaseConfig.CreateDatabase();

            bus = BusConfig.Start();
        }
Example #16
0
    public void Simple()
    {
        #region SendOnly

        BusConfiguration configuration = new BusConfiguration();

        ISendOnlyBus bus = Bus.CreateSendOnly(configuration);

        #endregion
    }
        protected void Application_Start()
        {
            #region SetAutofacContainer
            //Create Autofac builder
            var builder = new ContainerBuilder();
            //Now register all depedencies to your custom IoC container

            //register mvc controller
            builder.RegisterControllers(typeof(MvcApplication).Assembly);

            builder.RegisterAssemblyTypes(typeof(MvcApplication).Assembly)
               .AsImplementedInterfaces();

            builder.RegisterModelBinderProvider();

            // Register the Web API controllers.
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            // builder.RegisterType(typeof(IHandleMessages<CreateMedicalProcedureApprovalRequest>));
            // builder.RegisterType(typeof(IHandleMessages<ApprovalCreated>));
            builder.RegisterType(typeof(ICommand));
            builder.RegisterType(typeof(IMessage));
            builder.RegisterGeneric(typeof(Repository<>))
                  .As(typeof(IRepository<>));
            builder.RegisterType<EventStore>().As<IEventStore>();

            var containerBuilder = builder.Build();

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

            //MVC resolver
            DependencyResolver.SetResolver(new AutofacDependencyResolver(containerBuilder));

            // Create the depenedency resolver for Web Api
            // Configure Web API with the dependency resolver.
            GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(containerBuilder);
            var config = new HttpConfiguration();
            config.DependencyResolver = new AutofacWebApiDependencyResolver(containerBuilder);

            #endregion SetAutofacContainer

            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    public SendMessageModule(ISendOnlyBus bus) : base("/sendmessage")
    {
        this.bus = bus;

        this.Get["/"] = r =>
        {
            var message = new MyMessage();
            bus.Send("Samples.Nancy.Endpoint", message);
            return("Message sent to endpoint");
        };
    }
Example #19
0
        private void RegisterBus()
        {
            var busConfiguration = new BusConfiguration();
            busConfiguration.UseSerialization<JsonSerializer>();
            busConfiguration.UseTransport<MsmqTransport>();
            busConfiguration.Transactions().Disable();
            busConfiguration.PurgeOnStartup(false);

            LogManager.Use<NServiceBus.Log4Net.Log4NetFactory>();

            Bus = NServiceBus.Bus.CreateSendOnly(busConfiguration);
        }
Example #20
0
        /// <summary>
        /// Sets the value of the header for the given key.
        /// </summary>
        /// <param name="bus">The <see cref="IBus"/>.</param>
        /// <param name="msg">The message to add a header to.</param>
        /// <param name="key">The header key.</param>
        /// <param name="value">The value to assign to the header.</param>
        public static void SetMessageHeader(this ISendOnlyBus bus, object msg, string key, string value)
        {
            var manageMessageHeaders = bus as IManageMessageHeaders;

            if (manageMessageHeaders != null)
            {
                manageMessageHeaders.SetHeaderAction(msg, key, value);
                return;
            }

            throw new InvalidOperationException("bus does not implement IManageMessageHeaders");
        }
Example #21
0
        private void RegisterBus()
        {
            var busConfiguration = new BusConfiguration();

            busConfiguration.UseSerialization <JsonSerializer>();
            busConfiguration.UseTransport <MsmqTransport>();
            busConfiguration.Transactions().Disable();
            busConfiguration.PurgeOnStartup(false);

            LogManager.Use <NServiceBus.Log4Net.Log4NetFactory>();

            Bus = NServiceBus.Bus.CreateSendOnly(busConfiguration);
        }
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            var builder = new ContainerBuilder();
            builder.RegisterControllers(typeof(MvcApplication).Assembly);
            var container = builder.Build();
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            var busConfiguration = new BusConfiguration();
            busConfiguration.Configure(container);
            bus = Bus.CreateSendOnly(busConfiguration);
        }
        static void Main(string[] args)
        {
            var config = new BusConfiguration();
            config.UsePersistence<InMemoryPersistence>();
            config.UseTransport<AzureStorageQueueTransport>();
            ServiceBus = Bus.CreateSendOnly(config);

            ReportStoreMessage message = new ReportStoreMessage();

            message.CompanyID = 50000;
            message.CompanyStoreID = 1;
            message.Identifier = "999243463345888";
            message.Timestamp = DateTime.Now;

            ServiceBus.Send("50000", message);

            Console.WriteLine("Message sent");
            Console.ReadLine();
        }
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            var builder = new ContainerBuilder();

            builder.RegisterControllers(typeof(MvcApplication).Assembly);
            var container = builder.Build();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            var busConfiguration = new BusConfiguration();

            busConfiguration.Configure(container);
            bus = Bus.CreateSendOnly(busConfiguration);
        }
Example #25
0
        public Result Initialize(RunDescriptor run, EndpointBehavior endpointBehavior,
                                 IDictionary <Type, string> routingTable, string endpointName)
        {
            try
            {
                behavior        = endpointBehavior;
                scenarioContext = run.ScenarioContext;
                configuration   =
                    ((IEndpointConfigurationFactory)Activator.CreateInstance(endpointBehavior.EndpointBuilderType))
                    .Get();
                configuration.EndpointName = endpointName;

                if (!string.IsNullOrEmpty(configuration.CustomMachineName))
                {
                    RuntimeEnvironment.MachineNameAction = () => configuration.CustomMachineName;
                }

                //apply custom config settings
                busConfiguration = configuration.GetConfiguration(run, routingTable);

                endpointBehavior.CustomConfig.ForEach(customAction => customAction(busConfiguration));

                if (configuration.SendOnly)
                {
                    sendOnlyBus = Bus.CreateSendOnly(busConfiguration);
                }
                else
                {
                    bus = configuration.GetBus() ?? Bus.Create(busConfiguration);
                    var transportDefinition = ((UnicastBus)bus).Settings.Get <TransportDefinition>();

                    scenarioContext.HasNativePubSubSupport = transportDefinition.HasNativePubSubSupport;
                }

                return(Result.Success());
            }
            catch (Exception ex)
            {
                Logger.Error($"Failed to initialize endpoint {endpointName}", ex);
                return(Result.Failure(ex));
            }
        }
        public static void Init()
        {
            if (Bus != null)
                return;

            lock (padlock)
            {
                if (Bus != null)
                    return;

                var cfg = new BusConfiguration();

                cfg.UseTransport<MsmqTransport>();
                cfg.UsePersistence<InMemoryPersistence>();
                cfg.PurgeOnStartup(true);
                cfg.EnableInstallers();

                Bus = NServiceBus.Bus.CreateSendOnly(cfg);
            }
        }
Example #27
0
 public NsbProgressReporter(ISendOnlyBus bus, ICompletionState completionState,
                            IRequestKey defaultRequestKey, Action <IProgress> setTotalCallback = null,
                            Action <IProgress> reportProgressCallback = null)
     : base(completionState, defaultRequestKey, x =>
 {
     setTotalCallback?.Invoke(x);
     using (new TransactionScope(TransactionScopeOption.Suppress))
     {
         bus.Publish(x);
     }
 }, x =>
 {
     reportProgressCallback?.Invoke(x);
     using (new TransactionScope(TransactionScopeOption.Suppress))
     {
         bus.Publish(x);
     }
 })
 {
 }
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            var configuration = new BusConfiguration();

            configuration.EndpointName("web");
            configuration.UseTransport <MsmqTransport>();
            configuration.UseSerialization <JsonSerializer>();
            configuration.UsePersistence <InMemoryPersistence>();
            configuration.AssembliesToScan(AllAssemblies.Except("Razor"));
            configuration
            .Conventions()
            .DefiningCommandsAs(type => FilterByName(type, "Command"))
            .DefiningEventsAs(type => FilterByName(type, "Event"));

            Bus = NServiceBus.Bus.CreateSendOnly(configuration);
        }
        protected void Application_Start()
        {
            var config = new BusConfiguration();

            config.Conventions()
                    .DefiningCommandsAs(t => t.Namespace != null && (t.Namespace.StartsWith("Commands") || t.Namespace.Contains("Commands")))
                    .DefiningEventsAs(t => t.Namespace != null && (t.Namespace.EndsWith("Events") || t.Namespace.EndsWith("Notifications")));

            LogManager.Use<DefaultFactory>().Directory("c:/temp");

            config.UseTransport<AzureServiceBusTransport>();
            //config.UsePersistence<AzureStoragePersistence>();

            config.PurgeOnStartup(true);
            config.EnableInstallers();

            _bus = NServiceBus.Bus.CreateSendOnly(config);

            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
        }
Example #30
0
        public static void Init()
        {
            if (Bus != null)
                return;

            lock (padlock)
            {
                if (Bus != null)
                    return;

                var cfg = new BusConfiguration();

                cfg.UseTransport<MsmqTransport>();
                cfg.UsePersistence<InMemoryPersistence>();
                cfg.EndpointName("CQRSButDifferent.ResupplyVendorConsoleClient");
                cfg.PurgeOnStartup(true);
                cfg.EnableInstallers();

                Bus = NServiceBus.Bus.CreateSendOnly(cfg);
            }
        }
Example #31
0
        public static void Init(ILifetimeScope container)
        {
            if (Bus != null) return;

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

              lock (padlock)
              {
            if (Bus != null) return;

            var configuration = new BusConfiguration();
            configuration.UseSerialization<JsonSerializer>();
            configuration.UseContainer<AutofacBuilder>(x => x.ExistingLifetimeScope(container));
            configuration.UseTransport<MsmqTransport>();

            ConventionsBuilder conventions = configuration.Conventions();
            conventions.DefiningCommandsAs(t => t.Namespace != null && t.Namespace.StartsWith("Orders.Messages") && t.Namespace.EndsWith("Commands"));

            Bus = NServiceBus.Bus.CreateSendOnly(configuration);
              }
        }
Example #32
0
        static void Main(string[] args)
        {
            BusConfiguration configuration = new BusConfiguration();

            configuration.UseTransport <MsmqTransport>();
            configuration.UseSerialization <JsonSerializer>();

            ConventionsBuilder conventions = configuration.Conventions();

            conventions.DefiningCommandsAs(c => c.Namespace != null && c.Namespace == "Messages" && c.Name.EndsWith("Command"));

            using (ISendOnlyBus bus = Bus.CreateSendOnly(configuration))
            {
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("When you're ready, press 1 to send the command!");
                Console.WriteLine("Press any other key to exit");

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

                    if (keyPressed.Key == ConsoleKey.D1)
                    {
                        SendMessageCommand cmd = new SendMessageCommand()
                        {
                            EventId = Guid.NewGuid().ToString()
                        };
                        Console.WriteLine($"Sending SendMessageCommand with id {cmd.EventId}");
                        bus.Send(cmd);
                    }
                    else
                    {
                        return;
                    }
                }
            }
        }
Example #33
0
        static void Main(string[] args)
        {
            BusConfiguration configuration = new BusConfiguration();

            configuration.UseTransport <MsmqTransport>();
            configuration.UseSerialization <JsonSerializer>();

            ConventionsBuilder conventions = configuration.Conventions();

            conventions.DefiningCommandsAs(t => t.Namespace != null && t.Namespace == "Messages" && t.Name.EndsWith("Command"));

            CancelOrderCommand cmd = new CancelOrderCommand();

            cmd.OrderId = Guid.NewGuid();

            Console.WriteLine("When you're ready, press a key to send the command!");
            Console.ReadKey();

            using (ISendOnlyBus bus = Bus.CreateSendOnly(configuration))
            {
                Console.WriteLine("Sending CancelOrderCommand");
                bus.Send(cmd);
            }
        }
Example #34
0
 public AccountController(IFormsAuthenticationService formsAuthenticationService, ISendOnlyBus bus)
 {
     _formsAuthenticationService = formsAuthenticationService;
     _bus = bus;
 }
 private static void PublishAgreementPlacedForRemoteBrokerEvent(ISendOnlyBus bus)
 {
     const int RemoteBrokerId = 123;
     var agreementPlacedEvent = CreateAgreementPlacedEvent(RemoteBrokerId);
     bus.Publish(agreementPlacedEvent);
 }
 private static void PublishAgreementPlacedForOnlineBrokerEvent(ISendOnlyBus bus)
 {
     const int OnlineBrokerId = 456;
     var agreementPlacedEvent = CreateAgreementPlacedEvent(OnlineBrokerId);
     bus.Publish(agreementPlacedEvent);
 }
 public DiagnosticsSender(ISendOnlyBus bus)
 {
     _bus = bus;
 }
 public HomeController(ISendOnlyBus sendOnlyBus)
 {
     this.sendOnlyBus = sendOnlyBus;
 }
Example #39
0
 public NSBCommandBus(ISendOnlyBus bus)
 {
     this.Bus = bus;
 }
Example #40
0
        public Result Initialize(RunDescriptor run, EndpointBehavior endpointBehavior,
            IDictionary<Type, string> routingTable, string endpointName)
        {
            try
            {
                runDescriptor = run;
                behavior = endpointBehavior;
                scenarioContext = run.ScenarioContext;
                configuration =
                    ((IEndpointConfigurationFactory)Activator.CreateInstance(endpointBehavior.EndpointBuilderType))
                        .Get();
                configuration.EndpointName = endpointName;

                if (!string.IsNullOrEmpty(configuration.CustomMachineName))
                {
                    RuntimeEnvironment.MachineNameAction = () => configuration.CustomMachineName;
                }

                //apply custom config settings
                var busConfiguration = configuration.GetConfiguration(run, routingTable);

                scenarioContext.ContextPropertyChanged += scenarioContext_ContextPropertyChanged;

                endpointBehavior.CustomConfig.ForEach(customAction => customAction(busConfiguration));

                if (configuration.SendOnly)
                {
                    sendOnlyBus = Bus.CreateSendOnly(busConfiguration);
                }
                else
                {
                    bus = Bus.Create(busConfiguration);
                    var transportDefinition = ((UnicastBus)bus).Settings.Get<TransportDefinition>();

                    scenarioContext.HasNativePubSubSupport = transportDefinition.HasNativePubSubSupport;
                }


                executeWhens = Task.Factory.StartNew(() =>
                {
                    while (!stopped)
                    {
                        //we spin around each 5s since the callback mechanism seems to be shaky
                        contextChanged.Wait(TimeSpan.FromSeconds(5));

                        lock (behavior)
                        {
                            foreach (var when in behavior.Whens)
                            {
                                if (executedWhens.Contains(when.Id))
                                {
                                    continue;
                                }

                                if (when.ExecuteAction(scenarioContext, bus))
                                {
                                    executedWhens.Add(when.Id);
                                }
                            }
                        }
                    }
                });

                return Result.Success();
            }
            catch (Exception ex)
            {
                Logger.Error("Failed to initialize endpoint " + endpointName, ex);
                return Result.Failure(ex);
            }
        }
Example #41
0
        public static void Start(ISendOnlyBus bus)
        {
            var random = new Random();
            var countOfUsers = 15;
            while (true)
            {
                Thread.Sleep((int)Math.Pow(random.Next(6), 5));
                var now = DateTime.UtcNow;
                var hashtag = "Simulated";
                var track = $"#{hashtag}";
                var hashtagText = track;
                var secondaryHashtag = new string(char.ConvertFromUtf32(random.Next(65, 80)).ElementAt(0), 6);
                if (now.Millisecond % 3 == 0)
                {
                    hashtag = hashtag.ToLowerInvariant();
                    hashtagText = hashtagText.ToLowerInvariant();
                    secondaryHashtag = secondaryHashtag.ToLowerInvariant();
                }

                var userId = random.Next(countOfUsers);
                var userMentionId = random.Next(countOfUsers);
                var userMentionIndex = random.Next(31) + 1;
                var retweetedUserId = random.Next(countOfUsers);
                var text = string.Join(
                        string.Empty,
                        Enumerable.Range(0, userMentionIndex - 1).Select(i => char.ConvertFromUtf32(random.Next(65, 128)))) +
                    $" @johnsmith{userMentionId} " +
                    string.Join(
                        string.Empty,
                        Enumerable.Range(0, random.Next(32)).Select(i => char.ConvertFromUtf32(random.Next(65, 128)))) +
                    $" {hashtagText}" +
                    $" #{secondaryHashtag}";

                var message = new AnalyzeTweet
                {
                    Tweet = new Tweet
                    {
                        Track = track,
                        Id = now.Ticks,
                        CreatedAt = now,
                        CreatedById = userId,
                        CreatedByIdStr = $"{userId}",
                        CreatedByName = $"John Smith{userId}",
                        CreatedByScreenName = $"johnsmith{userId}",
                        Text = text,
                        UserMentions = new List<UserMention>
                        {
                            new UserMention
                            {
                                Id=userMentionId,
                                IdStr= $"{userMentionId}",
                                Indices = new List<int> { userMentionIndex, userMentionIndex + $"@johnsmith{userMentionId}".Length, },
                                Name = $"John Smith{userMentionId}",
                                ScreenName = $"johnsmith{userMentionId}",
                            },
                        },
                        Hashtags = new List<Hashtag>
                        {
                            new Hashtag
                            {
                                Text = hashtag,
                                Indices = new[] { text.Length - $"{hashtagText} #{secondaryHashtag}".Length, text.Length - $" #{secondaryHashtag}".Length, },
                            },
                            new Hashtag
                            {
                                Text = secondaryHashtag,
                                Indices = new[] { text.Length - $"#{secondaryHashtag}".Length, text.Length, },
                            },
                        },
                        RetweetedTweet = now.Millisecond % 3 == 0
                            ? new Tweet
                            {
                                Track = track,
                                Id = now.AddDays(-1000).Ticks,
                                CreatedAt = now.AddDays(-1000),
                                CreatedById = retweetedUserId,
                                CreatedByIdStr = $"{retweetedUserId}",
                                CreatedByName = $"John Smith{retweetedUserId}",
                                CreatedByScreenName = $"johnsmith{retweetedUserId}",
                                Text = text,
                                UserMentions = new List<UserMention>(),
                                Hashtags = new List<Hashtag>(),
                                RetweetedTweet = null,
                            }
                            : null,
                    }
                };

                Writer.Write(message.Tweet);
                bus.Send(message);
            }
        }
Example #42
0
 public SignupController(ISendOnlyBus bus)
 {
     this.bus = bus;
 }
Example #43
0
 public MyMessageTopicMessageHandler(ISendOnlyBus bus)
 {
     this.bus = bus;
 }
 public SignupController(ISendOnlyBus bus)
 {
     this.bus = bus;
 }
Example #45
0
        public static bool Menu(ISendOnlyBus bus)
        {
            int[] customers = Db.AllCustomers();

            using (Colr.Green())
            {
                Console.WriteLine(Environment.NewLine + "Menu:");
                Console.WriteLine("(n)ew customer");
                foreach (var customer in customers)
                {
                    Console.WriteLine("({0}) Customer {1}", customer, customer);
                }
                Console.WriteLine("(q) to quit");
                Console.Write(" > ");
            }

            char input = Console.ReadKey().KeyChar;
            switch (input)
            {
                case 'n':
                    int customerId = Db.NewCustomer();
                    while (CustomerMenu(bus, customerId))
                    {
                    }
                    return true;
                case 'q':
                    return false;
                default:
                    int i;
                    if (int.TryParse(input.ToString(), out i))
                        if (customers.Contains(i))
                        {
                            while (CustomerMenu(bus, i))
                            {
                            }
                            return true;
                        }

                    using (Colr.Red())
                        Console.WriteLine("Unknown input '{0}', please try again" + Environment.NewLine, input);

                    return true;
            }
        }
 public HomeController(IBus sendOnlyBus)
 {
     this.sendOnlyBus = sendOnlyBus;
 }
Example #47
0
        public static bool RequestMenu(ISendOnlyBus bus, int customerId, Guid requestId)
        {
            if (!RequestIsValid(customerId, requestId)) return false;

            Console.WriteLine(Environment.NewLine);
            using (Colr.Magenta())
            {
                Console.WriteLine(Environment.NewLine + "Request {0} Menu:", requestId);
                Console.WriteLine("(a)pprove");
                Console.WriteLine("(e)xtend acceptance timeout");
                Console.WriteLine("(r)educe acceptance timeout");
                Console.WriteLine("(b)ack to previous menu");
                Console.Write(" > ");
            }

            char input = Console.ReadKey().KeyChar;
            if (!RequestIsValid(customerId, requestId)) return false;

            switch (input)
            {
                case 'a':
                    bus.Send(new ApproveRmaRequest{CustomerId = customerId, RequestId = requestId});
                    return false;
                case 'e':
                    Console.WriteLine(Environment.NewLine);
                    int extendBy = GetNumericValue("Number of seconds to extend by or (0) to cancel: ");

                    if (extendBy > 0)
                    {
                        bus.Send(new ExtendAcceptanceTimeout
                        {
                            CustomerId = customerId,
                            RequestId = requestId,
                            ExtendBySeconds = extendBy
                        });
                    }
                    else
                    {
                        using (Colr.Red())
                            Console.WriteLine("Canceled");
                    }
                    return true;
                case 'r':
                    Console.WriteLine(Environment.NewLine);
                    int reduceBy = GetNumericValue("Number of seconds to reduce by or (0) to cancel: ");

                    if (reduceBy > 0)
                    {
                        bus.Send(new ReduceAcceptanceTimeout
                        {
                            CustomerId = customerId,
                            RequestId = requestId,
                            ReduceBySeconds = reduceBy
                        });
                    }
                    else
                    {
                        using (Colr.Red())
                            Console.WriteLine("Canceled");
                    }
                    return true;
                case 'b':
                    return false;
                default:
                    using (Colr.Red())
                        Console.WriteLine("I don't understand, try again...");
                    return true;
            }
        }
 public ExampleSender(ISendOnlyBus bus)
 {
     _bus = bus;
 }
Example #49
0
        public static bool CustomerMenu(ISendOnlyBus bus, int customerId)
        {
            Guid[] requests = Db.AllRequests(customerId);

            Console.WriteLine(Environment.NewLine);
            using (Colr.Yellow())
            {
                Console.WriteLine(Environment.NewLine + "Customer {0} Menu:", customerId);
                Console.WriteLine("(n)ew request");
                Console.WriteLine("(e)xtend all acceptance timeouts");
                Console.WriteLine("(r)educe all acceptance timeouts");
                for (var i = 0; i < requests.Length; i++)
                {
                    Console.WriteLine("({0}) Request {1}", i, requests[i]);
                }
                Console.WriteLine("(b)ack to previous menu");
                Console.Write(" > ");
            }

            char input = Console.ReadKey().KeyChar;
            switch (input)
            {
                case 'n':

                    Console.WriteLine(Environment.NewLine);
                    int acceptIn = GetNumericValue("Number of seconds before auto accept or (0) to cancel: ");

                    if (acceptIn > 0)
                    {
                        Guid requestId = CreateNewRequest(bus, customerId, acceptIn);
                        while (RequestMenu(bus, customerId, requestId))
                        {
                        }
                    }
                    else
                    {
                        using (Colr.Red())
                            Console.WriteLine("Canceled");
                    }
                    return true;
                case 'e':
                    Console.WriteLine(Environment.NewLine);
                    int extendBy = GetNumericValue("Number of seconds to extend by or (0) to cancel: ");

                    if (extendBy > 0)
                    {
                        bus.Send(new ExtendAllAcceptanceTimeouts {CustomerId = customerId, ExtendBySeconds = extendBy});
                    }
                    else
                    {
                        using (Colr.Red())
                            Console.WriteLine("Canceled");
                    }
                    return true;
                case 'r':
                    Console.WriteLine(Environment.NewLine);
                    int reduceBy = GetNumericValue("Number of seconds to reduce by or (0) to cancel: ");

                    if (reduceBy > 0)
                    {
                        bus.Send(new ReduceAllAcceptanceTimeouts {CustomerId = customerId, ReduceBySeconds = reduceBy});
                    }
                    else
                    {
                        using (Colr.Red())
                            Console.WriteLine("Canceled");
                    }
                    return true;
                case 'b':
                    return false;
                default:
                    int i;
                    if (int.TryParse(input.ToString(), out i))
                        if (i < requests.Length)
                        {
                            while (RequestMenu(bus, customerId, requests[i]))
                            {
                            }
                            return true;
                        }

                    using (Colr.Red())
                        Console.WriteLine("Unknown input '{0}', please try again" + Environment.NewLine, input);
                    return true;
            }
        }
 public DiagnosticsSender(ISendOnlyBus bus)
 {
     _bus = bus;
 }
Example #51
0
 private static Guid CreateNewRequest(ISendOnlyBus bus, int customerId, int acceptIn)
 {
     Guid requestId = Db.NewRequest(customerId);
     bus.Send(new CreateRmaRequest
     {
         CustomerId = customerId,
         RequestId = requestId,
         AcceptTimeoutSeconds = acceptIn
     });
     return requestId;
 }
Example #52
0
 private static void Publish(ISendOnlyBus bus)
 {
     while (Menu(_bus))
     {
     }
 }
 public CollectBillingController(ISendOnlyBus bus)
 {
     this.bus = bus;
 }
 public ExampleSender(ISendOnlyBus bus)
 {
     _bus = bus;
 }
 public TestController(ISendOnlyBus bus)
 {
     _bus = bus;
 }
 public OrdersController(ISayHello say, ISendOnlyBus bus)
 {
     _say = say;
     _bus = bus;
 }
 public SimpleTypeResolver(IDependencyResolver defaultResolver, ISendOnlyBus bus)
 {
     dependencyResolver = defaultResolver;
     this.bus = bus;
 }
Example #58
0
 public SimpleTypeResolver(IDependencyResolver defaultResolver, ISendOnlyBus bus)
 {
     dependencyResolver = defaultResolver;
     this.bus           = bus;
 }
Example #59
0
 public HomeController(ISendOnlyBus bus)
 {
     this.bus = bus;
 }