public async Task VerifySubscriberIsInitializedWhenRegistered()
        {
            // Setup the message bus.
            var cs = Any.String();
            var subscriber = new MockSubscriber();
            var mbf = new MockMessageBusFactory { Subscriber = subscriber };
            var mbd = new MessageBusDescription { ConnectionString = cs, Factory = mbf };
            var bus = new MessageBus(mbd);
            var entity = "MessageSendSuccess;MessageSendFailure";
            var name = "MessageSendSuccess";

            Assert.IsFalse(
                subscriber.IsInitialized, 
                "The subscriber should not be initialized before it is registered.");

            var called = false;

            // Register the subscriber.
            await bus.RegisterHandlerAsync(entity, name, message => Task.Run(() => { called = true; }));

            Assert.IsTrue(subscriber.IsInitialized, "The subscriber should be initialized after it is registered.");
            Assert.AreEqual(subscriber.Description.ConnectionString, cs);
            Assert.AreEqual(subscriber.Description.Entity, entity);
            Assert.AreEqual(subscriber.Description.Name, name);

            await subscriber.Handler.Invoke(null);
            Assert.IsTrue(called, "The handler must be callable.");

            // Close the bus.
            await bus.CloseAsync();

            Assert.IsTrue(subscriber.IsClosed, "The subscriber should be closed after the bus is closed.");
        }
예제 #2
0
    public void WhenSinkThrowsMessagesContinueToBeDelivered()
    {
        var sink = Substitute.For<IMessageSink>();
        var msg1 = Substitute.For<IMessageSinkMessage>();
        var msg2 = Substitute.For<IMessageSinkMessage>();
        var msg3 = Substitute.For<IMessageSinkMessage>();
        var messages = new List<IMessageSinkMessage>();
        sink.OnMessage(Arg.Any<IMessageSinkMessage>())
            .Returns(callInfo =>
            {
                var msg = (IMessageSinkMessage)callInfo[0];
                if (msg == msg2)
                    throw new Exception("whee!");
                else
                    messages.Add(msg);

                return false;
            });

        using (var bus = new MessageBus(sink))
        {
            bus.QueueMessage(msg1);
            bus.QueueMessage(msg2);
            bus.QueueMessage(msg3);
        }

        Assert.Collection(messages,
            message => Assert.Same(message, msg1),
            message => Assert.Same(message, msg3)
        );
    }
예제 #3
0
 static void Main(string[] args)
 {
     var bus = new MessageBus();
     var input = "";
     while ((input = Console.ReadLine()) != "Quit")
     {
         if (input == "1")
             MessageBus.Bus.Publish(new CreateIdeaMessage
             {
                 IdeaId = 1,
                 CaseId = 100
             });
         else if(input=="2")
             MessageBus.Bus.Publish(new CreateObjectiveMessage
             {
                 ObjectiveId = 12,
                 CaseId = 100
             });
         else
             MessageBus.Bus.Publish(new CreateTaskMessage
             {
                 TaskId = 12,
                 CaseId = 100
             });
     }
 }
예제 #4
0
        public void MultiplePublishers()
        {
            const string message1 = "Test Message #1";
            const string message2 = "Test Message #2";
            const string message3 = "Test Message #3";
            const string message4 = "Test Message #4";
            string receivedMessage = null;

            var messageBus = new MessageBus();
            var publisher1 = new Subject<string>();
            var publisher2 = new Subject<string>();
            var subscription1 = messageBus.RegisterPublisher(publisher1);
            messageBus.RegisterPublisher(publisher2);

            messageBus.Listen<string>().Subscribe(m => receivedMessage = m, e => Assert.Fail(), Assert.Fail);
            Assert.IsNull(receivedMessage);

            messageBus.Publish(message1);
            Assert.AreEqual(message1, receivedMessage);

            publisher1.OnNext(message2);
            Assert.AreEqual(message2, receivedMessage);

            publisher2.OnNext(message3);
            Assert.AreEqual(message3, receivedMessage);

            subscription1.Dispose();
            publisher1.OnNext(message4);
            Assert.AreEqual(message3, receivedMessage);

            publisher2.OnNext(message4);
            Assert.AreEqual(message4, receivedMessage);
        }
 public void FalseWithNoSubscribers()
 {
     var bus = new MessageBus();
     bus.HasSubscriberFor<Message>()
         .Should().BeFalse(
             "no subscribers have been added");
 }
예제 #6
0
        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            Trello = new Trello("1ed8d91b5af35305a60e169a321ac248");
            MessageBus = new MessageBus();

            var exportCardsControl = new ExportCardsControl();
            var importCardsControl = new ImportCardsControl();
            var authorizeForm = new AuthorizationDialog();

            ExportCardsTaskPane = CustomTaskPanes.Add(exportCardsControl, "Export cards to Trello");
            ExportCardsTaskPane.Width = 300;
            ExportCardsTaskPane.DockPositionRestrict = MsoCTPDockPositionRestrict.msoCTPDockPositionRestrictNoHorizontal;

            ImportCardsTaskPane = CustomTaskPanes.Add(importCardsControl, "Import cards from Trello");
            ImportCardsTaskPane.Width = 300;
            ImportCardsTaskPane.DockPositionRestrict = MsoCTPDockPositionRestrict.msoCTPDockPositionRestrictNoHorizontal;

            TaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();

            ExportCardsPresenter = new ExportCardsPresenter(exportCardsControl, Trello, new GridToNewCardTransformer(), TaskScheduler, MessageBus);
            ImportCardsPresenter = new ImportCardsPresenter(importCardsControl, MessageBus, Trello, TaskScheduler);
            AuthorizePresenter = new AuthorizePresenter(authorizeForm, Trello, MessageBus);

            Globals.Ribbons.TrelloRibbon.SetMessageBus(MessageBus);

            TryToAuthorizeTrello();
        }
예제 #7
0
        static void Main(string[] args)
        {
            Console.Title = "zmq Pub Sub Sample Client";
            const string publishAddress = "tcp://127.0.0.1:54321";
            const string listenAddress = "tcp://127.0.0.1:12345";
            IMessageCodec messageCodec = new JsonMessageCodec(Encoding.Unicode);

            IMessageBus messageBus = new MessageBus(listenAddress, publishAddress, messageCodec);
            messageBus.Subscribe<object>(Console.WriteLine);
            messageBus.GetMessages<StartedListeningMessage>()
                .Where(m => m.Id == messageBus.GetHashCode())
                .Subscribe(x => Console.WriteLine("Press ESC to cancel, or any other key to send a message."));
            var worker = new BackgroundWorker();
            worker.DoWork += (s, e) => messageBus.Listen();
            worker.RunWorkerAsync();

            bool loop = true;
            int i = 1;
            while (loop)
            {
                var key = Console.ReadKey(false);
                if (key.Key == ConsoleKey.Escape)
                {
                    loop = false;
                    continue;
                }
                string message = string.Format("Message {0:d2} from Client", i);
                messageBus.Publish(message);
                i++;
            }
        }
예제 #8
0
파일: Config.cs 프로젝트: attila3453/alsing
        private static MessageBus GetPersistedEventBus()
        {
            var persistedEventBus = new MessageBus();

            //application handlers

            persistedEventBus.RegisterHandler<RepliedToPostEvent>(MessageHandlerType.Synchronous, OnRepliedToPost, true);
            persistedEventBus.RegisterHandler<ApprovedCommentEvent>(MessageHandlerType.Synchronous, OnApprovedComment, true);
            persistedEventBus.RegisterHandler<FailedMessage>(MessageHandlerType.Synchronous, OnFailMessage, false);

            //sync handlers
            //persistedEventBus.RegisterHandler<RepliedToPostEvent>(MessageHandlerType.Synchronous, e => UpdateComment( e.Comment), true);
            //persistedEventBus.RegisterHandler<ApprovedCommentEvent>(MessageHandlerType.Synchronous, e => UpdateComment( e.Comment), true);

            //persistedEventBus.RegisterHandler<AssignedCategoryToPostEvent>(MessageHandlerType.Synchronous, e => CreateCategoryLink(e.Post,e.Category), true);

            //persistedEventBus.RegisterHandler<EditedPostEvent>(MessageHandlerType.Synchronous, e => UpdatePost(e.Post), true);
            //persistedEventBus.RegisterHandler<EnabledCommentsEvent>(MessageHandlerType.Synchronous, e => UpdatePost(e.Post), true);
            //persistedEventBus.RegisterHandler<DisabledCommentsEvent>(MessageHandlerType.Synchronous, e => UpdatePost(e.Post), true);
            //persistedEventBus.RegisterHandler<PostCreatedEvent>(MessageHandlerType.Synchronous, e => UpdatePost(e.Post), true);
            //persistedEventBus.RegisterHandler<PublishedPostEvent>(MessageHandlerType.Synchronous, e => DeletePost(e.Post), true);
            //persistedEventBus.RegisterHandler<UnpublishedPostEvent>(MessageHandlerType.Synchronous, e => DeletePost(e.Post), true);

            //persistedEventBus.RegisterHandler<PostDeletedEvent>(MessageHandlerType.Synchronous, e => DeletePost(e.Post), true);


            return persistedEventBus;
        }
예제 #9
0
파일: SkyBox.cs 프로젝트: veggielane/ORTS
 public SkyBox(int id, MessageBus bus)
 {
     Id = id;
     Bus = bus;
     Position = new Vect3(0, 0, 0);
     Rotation = new Quat(Math.Sqrt(0.5), 0, 0, Math.Sqrt(0.5));
 }
        /// <summary>
        /// Handles the specified subscription command line options.
        /// </summary>
        /// <param name="options">
        /// The options.
        /// </param>
        public static void Handle(SubscriptionOptions options)
        {
            if (options.IsVerbose)
            {
                Debug.Listeners.Add(new ColoredConsoleTraceListener());
            }

            OutputWriter = !string.IsNullOrWhiteSpace(options.OutputFileName)
                               ? new StreamWriter(options.OutputFileName)
                               : Console.Out;

            var description = new MessageBusDescription
                                  {
                                      ConnectionString = options.ConnectionString, 
                                      Factory =
                                          DependencyResolver.Resolve<IMessageBusFactory>(
                                              options.Factory), 
                                      StorageConnectionString = options.StorageConnectionString
                                  };
            var bus = new MessageBus(description);
            bus.RegisterHandlerAsync(options.Entity, options.Name, OnMessageArrived).Wait();

            Debug.Print("This is a debug print.");
            Console.WriteLine("Press any key to exit...");
            Console.ReadKey();

            Console.WriteLine("Closing message bus...");
            bus.CloseAsync().ContinueWith(t => Console.WriteLine("Message bus is closed.")).Wait();
        }
예제 #11
0
        private Configuration()
        {
            _bus = new MessageBus();
            var eventStore = new SqlEventStore(_bus);
            var repository = new DomainRepository(eventStore);

            var commandService = new AccountApplicationService(repository);
            _bus.RegisterHandler<RegisterAccountCommand>(commandService.Handle);
            _bus.RegisterHandler<DebitAccountCommand>(commandService.Handle);
            _bus.RegisterHandler<UnlockAccountCommand>(commandService.Handle);

            var infoProjection = new AccountInfoProjection();
            _bus.RegisterHandler<AccountRegisteredEvent>(infoProjection.Handle);
            _bus.RegisterHandler<AccountLockedEvent>(infoProjection.Handle);
            _bus.RegisterHandler<AccountUnlockedEvent>(infoProjection.Handle);

            var balanceProjection = new AccountBalanceProjection();
            _bus.RegisterHandler<AccountRegisteredEvent>(balanceProjection.Handle);
            _bus.RegisterHandler<AccountDebitedEvent>(balanceProjection.Handle);

            var notification = new NotificationProjection();
            _bus.RegisterHandler<AccountRegisteredEvent>(notification.Handle);
            _bus.RegisterHandler<AccountDebitedEvent>(notification.Handle);
            _bus.RegisterHandler<AccountLockedEvent>(notification.Handle);
            _bus.RegisterHandler<AccountUnlockedEvent>(notification.Handle);
            _bus.RegisterHandler<OverdrawAttemptedEvent>(notification.Handle);

            _readModel = new ReadModelFacade(balanceProjection, infoProjection, notification);

            var events = eventStore.GetAllEventsEver();
            _bus.Publish(events);
        }
예제 #12
0
 public void CreateBus()
 {
     m_Sender = Substitute.For<IMessageSender>();
     m_Receiver = Substitute.For<IMessageReceiver>();
     m_Bus = new MessageBus(m_Sender,
                            m_Receiver);
 }
예제 #13
0
 public void Initialise(MessageBus bus)
 {
     Bus = bus;
     SystemMessages = Bus.OfType<SystemMessage>().AsObservable();
     ObjectLifeTimeRequests = Bus.OfType<IObjectLifetimeRequest>().AsObservable();
     ObjectLifeTimeNotifications = Bus.OfType<IObjectLifetimeNotification>().AsObservable();
 }
예제 #14
0
        public GameObjectFactory(MessageBus bus)
        {
            GameObjects = new List<IGameObject>();
            Bus = bus;

            Initialise();
        }
예제 #15
0
 /// <summary>
 /// Construct a boot strapper for Light framework. 
 /// </summary>
 /// <param name="Args">Application init args</param>
 public Bootstrapper(string[] Args)
 {
     MessageBus = new MessageBus();
     Modules = new List<LightModule>();
     LoadAssemblies();
     MessageBus.Run();
 }
        public void HeavyLoadTest()
        {
            const int REPEATER_COUNT = 10;
              const int MESSAGE_COUNT = 200;

              // Arrange
              var bus = new MessageBus();

              var receivers = new MessageRepeater[REPEATER_COUNT];
              for (var i = 0; i < REPEATER_COUNT; i++)
              {
            receivers[i] = new MessageRepeater(bus, i);
            bus.SubscriberFor<RepeatingMessage>(receivers[i].Receive);
              }

              // Act
              var messages = new RepeatingMessage[MESSAGE_COUNT];
              for (var i = 0; i < MESSAGE_COUNT; i++)
              {
            messages[i] = new RepeatingMessage();
            bus.SendMessage(messages[i]);
              }

              // Assert
              var finished = false;
              while (!finished)
              {
            System.Threading.Thread.Sleep(500);
            var count = messages.Count(m => m.Counter == REPEATER_COUNT);
            Console.WriteLine(count);
            if (count == MESSAGE_COUNT)
              finished = true;
              }
        }
예제 #17
0
        private Configuration()
        {
            /* bus intialisation */
            _bus = new MessageBus();
            //var eventStore = new SqlServerEventStore(_bus);
            //var eventStore = new SqlLiteEventStore(_bus);
            var eventStore = new InMemoryEventStore(_bus, inMemDict );
            var repository = new DomainRepository(eventStore);

            /* Account Domain */
            var commandService = new AccountApplicationService(repository);
            _bus.RegisterHandler<RegisterAccountCommand>(commandService.Handle);
            _bus.RegisterHandler<DebitAccountCommand>(commandService.Handle);
            _bus.RegisterHandler<UnlockAccountCommand>(commandService.Handle);

            var infoProjection = new AccountInfoProjection();
            _bus.RegisterHandler<AccountRegisteredEvent>(infoProjection.Handle);
            _bus.RegisterHandler<AccountLockedEvent>(infoProjection.Handle);
            _bus.RegisterHandler<AccountUnlockedEvent>(infoProjection.Handle);

            var balanceProjection = new AccountBalanceProjection();
            _bus.RegisterHandler<AccountRegisteredEvent>(balanceProjection.Handle);
            _bus.RegisterHandler<AccountDebitedEvent>(balanceProjection.Handle);

            var notification = new NotificationProjection();
            _bus.RegisterHandler<AccountRegisteredEvent>(notification.Handle);
            _bus.RegisterHandler<AccountDebitedEvent>(notification.Handle);
            _bus.RegisterHandler<AccountLockedEvent>(notification.Handle);
            _bus.RegisterHandler<AccountUnlockedEvent>(notification.Handle);
            _bus.RegisterHandler<AccountOverdrawAttemptedEvent>(notification.Handle);

            _AccountReadModel = new AccountReadModelFacade(balanceProjection, infoProjection, notification);

            /*  News Domain*/
            //var newsEventStore = new SqlServerEventStore(_bus);
            //var newsEventStore = new SqlLiteEventStore(_bus);
            var newsEventStore = new InMemoryEventStore(_bus, inMemDict);
            var newsRepository = new DomainRepository(eventStore);

            /* Register command on the News bounded context */
            var newsCommandService = new AccountManager.Models.News.Domain.NewsApplicationService(newsRepository);
            _bus.RegisterHandler<AccountManager.Models.News.Commands.CreateNewsCommand>(newsCommandService.Handle);
            _bus.RegisterHandler<AccountManager.Models.News.Commands.PublishNewsCommand>(newsCommandService.Handle);
            _bus.RegisterHandler<AccountManager.Models.News.Commands.UnpublishNewsCommand>(newsCommandService.Handle);
            _bus.RegisterHandler<AccountManager.Models.News.Commands.UpdateNewsCommand>(newsCommandService.Handle);
            _bus.RegisterHandler<AccountManager.Models.News.Commands.DeleteNewsCommand>(newsCommandService.Handle);

            var _newsProjection = new AccountManager.Models.News.ReadModel.NewsProjection();
            _bus.RegisterHandler<AccountManager.Models.News.Events.NewsCreatedEvent>(_newsProjection.Handle);
            _bus.RegisterHandler<AccountManager.Models.News.Events.NewsPublishedEvent>(_newsProjection.Handle);
            _bus.RegisterHandler<AccountManager.Models.News.Events.NewsUnpublishedEvent>(_newsProjection.Handle);
            _bus.RegisterHandler<AccountManager.Models.News.Events.NewsUpdatedEvent>(_newsProjection.Handle);
            _bus.RegisterHandler<AccountManager.Models.News.Events.NewsDeletedEvent>(_newsProjection.Handle);

            _NewsReadModel = new NewsReadModelFacade(_newsProjection);

            /* rehydrate */
            var events = eventStore.GetAllEventsEver();
            _bus.Publish(events);
        }
예제 #18
0
        public void Can_send_and_receive_async_message()
        {
            var trigger = new AutoResetEvent(false);
            IMessageBus bus = new MessageBus();
            TestMessage receivedMessage = null;

            int currentThreadId = Thread.CurrentThread.ManagedThreadId;
            int handlerThreadId = 0;
            bus.RegisterHandler<TestMessage>(MessageHandlerType.Asynchronous, message =>
                                                                              {
                                                                                  handlerThreadId = Thread.CurrentThread.ManagedThreadId;
                                                                                  receivedMessage = message;
                                                                                  trigger.Set();
                                                                              }, false);

            var sentMessage = new TestMessage
                                  {
                                      Text = "Hello bus"
                                  };

            bus.Send(sentMessage);
            trigger.WaitOne(1000);
            //ensure we got the message
            Assert.AreSame(sentMessage, receivedMessage);

            //ensure we didn't handle it in the main thread
            Assert.AreNotEqual(currentThreadId, handlerThreadId);
        }
예제 #19
0
        public void PublishAndUnsubscribe()
        {
            // Arrange
            var bus = new MessageBus();
            Action<Object> handler = null;
            handler = (m) =>
            {
                Messages.Add(m);

                // Unsubscribe during the publish handler.
                bus.Unsubscribe<Object>(handler);
            };
            bus.Subscribe<Object>(handler);
            bus.Subscribe<Object>((m) =>
            {
                Messages.Add(m);
            });

            // Act
            var message = Guid.NewGuid().ToString();
            bus.Publish<Object>(message);
            bus.Publish<Object>(message);

            // Assert
            Assert.AreEqual(3, Messages.Count);
        }
        public void CanListenPositionChangeEvents()
        {
            // ARRANGE
            var waitEvent = new ManualResetEvent(false);
            var messageBus = new MessageBus();
            NmeaPositionMocker mocker;
            int count = 0;
            messageBus.AsObservable<GeoPosition>()
                .ObserveOn(Scheduler.ThreadPool)
                .Subscribe(position => count++);

            // ACT
            Action<TimeSpan> delayAction = _ => Thread.Sleep(0); // do not wait to make test faster
            using (Stream stream = new FileStream(TestHelper.NmeaFilePath, FileMode.Open))
            {
                mocker = new NmeaPositionMocker(stream, messageBus);
                mocker.OnDone += (s, e) => waitEvent.Set();
                mocker.Start(delayAction);
            }

            // ASSERT
            if(!waitEvent.WaitOne(TimeSpan.FromSeconds(60)))
                throw new TimeoutException();
            mocker.Stop();
            Assert.AreEqual(16, count);
        }
 public void TrueWithDerivedType()
 {
     var bus = new MessageBus();
     bus.SubscriberFor<TestMessageBase>(m => { });
     bus.HasSubscriberFor<TestMessageTypeA>()
         .Should().BeTrue(
             "subscriber for super type was added");
 }
 public void TrueWithExactMatch()
 {
     var bus = new MessageBus();
     bus.SubscriberFor<Message>(m => { });
     bus.HasSubscriberFor<Message>()
         .Should().BeTrue(
             "subscriber for type was added");
 }
 public ClientController(ActionInvoker actionInvoker, DataContext dataContext,
     JsonMapperManager jsonMapperManager, DeviceHiveConfiguration deviceHiveConfiguration,
     MessageBus messageBus, IMessageManager messageManager) :
     base(actionInvoker, dataContext, jsonMapperManager, deviceHiveConfiguration)
 {
     _messageBus = messageBus;
     _messageManager = messageManager;
 }
 public void FalseWithSuperType()
 {
     var bus = new MessageBus();
     bus.SubscriberFor<TestMessageTypeA>(m => { });
     bus.HasSubscriberFor<TestMessageBase>()
         .Should().BeFalse(
             "subscriber for derived type was added");
 }
 public void FalseWithNonMatch()
 {
     var bus = new MessageBus();
     bus.SubscriberFor<TestMessageTypeA>(m => { });
     bus.HasSubscriberFor<TestMessageTypeB>()
         .Should().BeFalse(
             "no subscriber for type was added");
 }
예제 #26
0
 public void Setup()
 {
     _bus = new MessageBus();
     _messOneTriggerCount = _messTwoTriggerCount = 0;
     _mockOneTriggerCount = _mockTwoTriggerCount = 0;
     _receivedMock = null;
     _receivedMessage = null;
 }
예제 #27
0
 public GameEngine(ObservableTimer timer, MessageBus bus, GameObjectFactory objectFactory)
 {
     Timer = timer;
     Bus = bus;
     ObjectFactory = objectFactory;
     IsRunning = false;
     Initialise();
 }
예제 #28
0
 private MessageBus _CreateBus(string id)
 {
     MessageBus bus;
     if (!Buses.TryGetValue (id, out bus)) {
         bus = new MessageBus (id);
         Buses.Add (id, bus);
     }
     return bus;
 }
 /// <summary>
 /// Default constructor
 /// </summary>
 /// <param name="messageBus">MessageBus object</param>
 /// <param name="configuration">DeviceHive configuration</param>
 /// <param name="deviceNotificationRepository">IDeviceNotificationRepository object</param>
 /// <param name="deviceCommandRepository">IDeviceCommandRepository object</param>
 public MessageManager(MessageBus messageBus, DeviceHiveConfiguration configuration,
     IDeviceNotificationRepository deviceNotificationRepository, IDeviceCommandRepository deviceCommandRepository)
 {
     _messageBus = messageBus;
     _configuration = configuration;
     _deviceNotificationRepository = deviceNotificationRepository;
     _deviceCommandRepository = deviceCommandRepository;
     _messageHandlerInfos = new List<MessageHandlerInfo>();
 }
예제 #30
0
		public MessageBus Bus { get; }//TODO CREATE BASE CLASS FOR MESSAGEBUS COMPONENTS

		public ReflectionPluginManager(MessageBus bus)
		{
			if (bus == null)
			{
				throw new ArgumentNullException("bus");
			}
			Bus = bus;
			Bus.Subscribe(this);
		}
예제 #31
0
 void DialogShowLoadingCallback(MessageBus bus, string message)
 {
     Device.BeginInvokeOnMainThread(() => UserDialogs.Instance.ShowLoading(message, MaskType.Black));
 }
예제 #32
0
 public static ICoroutineResult PostMessage(IMessage message)
 {
     MessageBus.Post(message);
     return(Wait);
 }
예제 #33
0
 public Floor(int index, Timeline timeline, MapInfo mapInfo, Spawner spawner, GoalMapStore goalMapStore, MessageBus messageBus)
 {
     Index        = index;
     Timeline     = timeline;
     MapInfo      = mapInfo;
     Spawner      = spawner;
     GoalMapStore = goalMapStore;
     MessageBus   = messageBus;
 }
예제 #34
0
        private void btnLoad_Click(object sender, System.EventArgs e)
        {
            var fileInfos = dtlvExplorer.CheckedObjects.OfType <AbstractDumpExplorerData>().Where(data => data.FileInfo != null).Select(data => data.FileInfo).ToList();

            MessageBus.SendMessage(new OpenDumpRequest(fileInfos));
        }
예제 #35
0
 public static IMessageBus CurrentMessageBusComesFrom(this IMessageBus messageBus)
 {
     MessageBus.SetProvider(() => messageBus);
     return(messageBus);
 }
예제 #36
0
 public SpaceGraphicsLoader(MessageBus bus)
 {
     Bus = bus;
 }
예제 #37
0
 public virtual bool FindTestsForClass(ITypeInfo type, bool includeSourceInformation = false)
 {
     using (var messageBus = new MessageBus(Visitor))
         return(base.FindTestsForType(type, includeSourceInformation, messageBus));
 }
예제 #38
0
        public static void DebugSend(
            MessageBus msgBus,
            Message message,
            StringBuilder textExplanation
            )
        {
            int count_PtToPt    = 0,
                count_Observer  = 0,
                count_RoleEvent = 0;

            Action <HandlerInfo, Message> Msg_PtToPt = (HandlerInfo handler, Message msg) => {
                textExplanation.AppendFormat(
                    "Point-to-Point Basis: Message match  # {0}\r\n"
                    + "Message processed by handler: {1}\r\n",
                    count_PtToPt,
                    handler
                    );
                count_PtToPt++;
            };
            Action <SubscriberInfo, HandlerInfo, string> Almost_PointToPoint = (SubscriberInfo sub, HandlerInfo h, string s) =>
            {
                textExplanation.AppendFormat("Point to Point near match: {0}\r\n", s);
            };

            Action <HandlerInfo, Message> Msg_Observer = (HandlerInfo handler, Message msg) => {
                textExplanation.AppendFormat(
                    "Role and Observer Basis: Message match  # {0}\r\n"
                    + "Message processed by handler: {1}\r\n",
                    count_Observer,
                    handler
                    );
                count_Observer++;
            };
            Action <SubscriberInfo, HandlerInfo, string> Almost_Observer = (SubscriberInfo sub, HandlerInfo h, string s) =>
            {
                textExplanation.AppendFormat("Observer near match: {0}\r\n", s);
            };

            Action <HandlerInfo, Message> Msg_RoleEvent = (HandlerInfo handler, Message msg) => {
                textExplanation.AppendFormat(
                    "Role and Event Code Basis: Message match  # {0}\r\n"
                    + "Message processed by handler: {1}\r\n",
                    count_RoleEvent,
                    handler
                    );
                count_RoleEvent++;
            };
            Action <SubscriberInfo, HandlerInfo, string> Almost_RoleEvent = (SubscriberInfo sub, HandlerInfo h, string s) =>
            {
                textExplanation.AppendFormat("Role and Event Code near match: {0}\r\n", s);
            };

            Action Msg_Unhandled = () =>
            {
                textExplanation.Append("No matches found.\r\n");
            };

            textExplanation.AppendFormat(
                "Performing match testing for message on the message bus:\r\n"
                + "Message : {0}\r\n", message
                );
            msgBus.MatchHandlers(message,
                                 Msg_PtToPt, Almost_PointToPoint,
                                 Msg_Observer, Almost_Observer,
                                 Msg_RoleEvent, Almost_RoleEvent,
                                 Msg_Unhandled
                                 );

            textExplanation.Append(
                "-----\r\nMatch Ended."
                );
        }
예제 #39
0
        public async Task SubscriptionWithMultipleExistingCursors()
        {
            var dr = new DefaultDependencyResolver();
            var passThroughMinfier = new PassThroughStringMinifier();

            dr.Register(typeof(IStringMinifier), () => passThroughMinfier);
            using (var bus = new MessageBus(dr))
            {
                Func <ISubscriber> subscriberFactory = () => new TestSubscriber(new[] { "key", "key2" });
                var         cdKey        = new CountDownRange <int>(Enumerable.Range(2, 4));
                var         cdKey2       = new CountDownRange <int>(new[] { 1, 2, 10 });
                IDisposable subscription = null;

                string prefix = DefaultSubscription._defaultCursorPrefix;

                // Pretend like we had an initial subscription
                bus.Subscribe(subscriberFactory(), null, (result, state) => TaskAsyncHelper.True, 10, null)
                .Dispose();

                // This simulates a reconnect
                await bus.Publish("test", "key", "1");

                await bus.Publish("test", "key", "2");

                await bus.Publish("test", "key", "3");

                await bus.Publish("test", "key", "4");

                await bus.Publish("test", "key2", "1");

                await bus.Publish("test", "key2", "2");

                try
                {
                    subscription = bus.Subscribe(subscriberFactory(), prefix + "key,00000001|key2,00000000", (result, state) =>
                    {
                        foreach (var m in result.GetMessages())
                        {
                            int n = Int32.Parse(m.GetString());
                            if (m.Key == "key")
                            {
                                Assert.True(cdKey.Mark(n));
                            }
                            else
                            {
                                Assert.True(cdKey2.Mark(n));
                            }
                        }

                        return(TaskAsyncHelper.True);
                    }, 10, null);

                    await bus.Publish("test", "key", "5");

                    await bus.Publish("test", "key2", "10");

                    await cdKey.WaitAsync().OrTimeout();

                    await cdKey2.WaitAsync().OrTimeout();
                }
                finally
                {
                    if (subscription != null)
                    {
                        subscription.Dispose();
                    }
                }
            }
        }
 public Task StartAsync(CancellationToken cancellationToken)
 {
     MessageBusSubscription = MessageBus.Bind(ManagedMqttClient);
     MqttEntityControlPanel.BindAll(MqttApplicationProvider, MessageBus, true);
     return(Task.CompletedTask);
 }
예제 #41
0
    public void Check()
    {
        doTickets.Clear();
        doAccidents.Clear();
        doNew.Clear();
        doWechat.Clear();

        if (DateTime.Compare(nextSlowTime, nowTime) < 0)
        {
            nextSlowTime = DateTime.MaxValue;
        }

        if (DateTime.Compare(nextTime, nowTime) < 0)
        {
            nextTime = nowTime.AddMinutes(30);
            EventHappenManager.Instance.EveryThirtyMinutes(nowTime);
        }

        //事故事件查找
        if (waitingAccidents.Count != 0)
        {
            var enumerator = waitingAccidents.GetEnumerator();
            enumerator.MoveNext();
            //Lucky.LuckyUtils.Log("next starttiem "+enumerator.Current.Key);
            if (DateTime.Compare(enumerator.Current.Key, NowTime) < 0)
            {
                List <TimeExecuteParam> teps = enumerator.Current.Value;
                doAccidents.AddRange(teps);
                waitingAccidents.Remove(enumerator.Current.Key);
            }
        }

        //事故事件执行
        foreach (TimeExecuteParam tep in doAccidents)
        {
            if (!tep.isDestroy)
            {
                Lucky.LuckyUtils.Log("new accident");
                StartCoroutine(tep.Callback(tep.accident));
                MapTrafficView.instance.ShowAccidentMessage(tep.accident);
            }
            else
            {
                MapTrafficView.instance.DisplayMessage(tep.accident);
            }
        }

        //旅游路线查找
        lock (golock)
        {
            if (waitingGo.Count != 0)
            {
                var etor = waitingGo.GetEnumerator();
                etor.MoveNext();
                if (DateTime.Compare(etor.Current.Key, NowTime) < 0)
                {
                    Dictionary <long, TicketParam> dics = etor.Current.Value;
                    foreach (KeyValuePair <long, TicketParam> kvp in dics)
                    {
                        GoId.Remove(kvp.Key);
                        doTickets.Add(kvp.Value);
                    }
                    waitingGo.Remove(etor.Current.Key);
                }
            }
        }

        //旅游路线执行
        foreach (TicketParam tp in doTickets)
        {
            //TimeSpeed = 1.0f;
            if (tp.rt.Type() == 0)
            {
                MapTrafficView.instance.TrainGo(tp);
            }
            else
            {
                MapTrafficView.instance.AirPlaneFly(tp);
            }
        }

        //微信事件查找
        if (waitingWeChat.Count != 0)
        {
            var etor = waitingWeChat.GetEnumerator();
            etor.MoveNext();
            if (DateTime.Compare(etor.Current.Key, NowTime) < 0)
            {
                List <MessageParam <WeChatMessage> > teps = etor.Current.Value;
                doWechat.AddRange(teps);
                waitingWeChat.Remove(etor.Current.Key);
            }
        }

        foreach (MessageParam <WeChatMessage> mp in doWechat)
        {
            //TimeSpeed = 1.0f;
            mp.Callback();
            MessageBus.Post(new MessageObject(mp.message));
        }

        //新闻事件查找
        if (waitingNew.Count != 0)
        {
            var etor = waitingNew.GetEnumerator();
            etor.MoveNext();
            if (DateTime.Compare(etor.Current.Key, NowTime) < 0)
            {
                List <MessageParam <NewMessage> > teps = etor.Current.Value;
                doNew.AddRange(teps);
                waitingNew.Remove(etor.Current.Key);
            }
        }

        foreach (MessageParam <NewMessage> mp in doNew)
        {
            //TimeSpeed = 1.0f;
            mp.Callback();
            MessageBus.Post(new MessageObject(mp.message));
        }

        if (DateTime.Compare(GameModel.Instance.tomorrow, nowTime) < 0)
        {
            InfoView.Show(new InfoMessage("失败", "垃圾"));
            timespeed = 0.0f;
        }
    }
예제 #42
0
 public void ConfigureMessageBus(IApplicationBuilder app)
 {
     // Set the MessageBus provider, so that IMessageBus are resolved from the current request scope
     MessageBus.SetProvider(MessageBusCurrentProviderBuilder.Create().From(app).Build());
 }
예제 #43
0
 void DialogHideLoadingCallback(MessageBus bus)
 {
     Device.BeginInvokeOnMainThread(() => UserDialogs.Instance.HideLoading());
 }
예제 #44
0
 public ProfileEventDispatcher(string journalName, string messageBusName, string topicName) : base(journalName, messageBusName, topicName)
 {
     _messageBus = MessageBus.Start(messageBusName);
     _topic      = _messageBus.OpenTopic(topicName);
 }
예제 #45
0
        static private void DoUpdateSystem(RequestUpdateSystem req)
        {
            Builder.Output(ClassName + ": Realizando actualizacion de la configuracion del sistema", TraceEventType.Information);

            bool RestartZyanServer = false;
            bool RestartHbReceiver = false;

            SystemConfigData newCfg = req.Data;

            // Config que afecta a HbReceiver.
            if (newCfg.UdpServerPort != _dbHandler.SystemData.UdpServerPort)
            {
                _dbHandler.SystemData.UdpServerPort = newCfg.UdpServerPort;
                RestartHbReceiver = true;
            }
            if (newCfg.ServerIpAdr != _dbHandler.SystemData.ServerIpAdr)
            {
                _dbHandler.SystemData.ServerIpAdr = newCfg.ServerIpAdr;
                RestartHbReceiver = true;
            }
            // Config que afecta a ZyanServer.
            if (newCfg.ZyanServerName != _dbHandler.SystemData.ZyanServerName)
            {
                _dbHandler.SystemData.ZyanServerName = newCfg.ZyanServerName;
                RestartZyanServer = true;
            }
            if (newCfg.ZyanServerPort != _dbHandler.SystemData.ZyanServerPort)
            {
                _dbHandler.SystemData.ZyanServerPort = newCfg.ZyanServerPort;
                RestartZyanServer = true;
            }
            // Config que afecta a Notifier.
            if (newCfg.Source != _dbHandler.SystemData.Source)
            {
                _dbHandler.SystemData.Source = newCfg.Source;
            }
            if (newCfg.Destination != _dbHandler.SystemData.Destination)
            {
                _dbHandler.SystemData.Destination = newCfg.Destination;
            }
            if (newCfg.Password != _dbHandler.SystemData.Password)
            {
                _dbHandler.SystemData.Password = newCfg.Password;
            }
            if (newCfg.SMtpServer != _dbHandler.SystemData.SMtpServer)
            {
                _dbHandler.SystemData.SMtpServer = newCfg.SMtpServer;
            }

            // Resto de la configuracion
            if (newCfg.TimeoutStartRestart != _dbHandler.SystemData.TimeoutStartRestart)
            {
                _dbHandler.SystemData.TimeoutStartRestart = newCfg.TimeoutStartRestart;
            }
            if (newCfg.RestartAttemps != _dbHandler.SystemData.RestartAttemps)
            {
                _dbHandler.SystemData.RestartAttemps = newCfg.RestartAttemps;
            }

            // guardar cambios
            MessageBus.Send(new RequestSaveConfig());

            // Registrando mensaje y controlador.
            MessageBus.Register <SendSystemConfig>(_clientManager.ReceiveSystemConfig);
            MessageBus.Register <SendSystemConfig>(_notifier.ReceiveSystemConfig);
            MessageBus.Register <SendSystemConfig>(_zyanServer.ReceiveSystemConfig);

            // Enviando msg.
            MessageBus.Send(new SendSystemConfig(_dbHandler.SystemData));

            // Quitando registro.
            MessageBus.Remove <SendSystemConfig>(_clientManager.ReceiveSystemConfig);
            MessageBus.Remove <SendSystemConfig>(_notifier.ReceiveSystemConfig);
            MessageBus.Remove <SendSystemConfig>(_zyanServer.ReceiveSystemConfig);

            // Actualizar componentes afectados:
            //  posibles implicados Notifier, ZyanServer, ClientManager (HB REceiver y timeouts)
            //  De ellos solo HB REceiver (pertenece a ClientManager) y ZyanServer se deben reiniciar si hay cambios
            //  los demas solo leen los valores de la configuracion.

            if (RestartHbReceiver)
            {
                MessageBus.Register <RequestStartHbServer>(_clientManager.DoRestartHbReceiver);
                MessageBus.Send(new RequestStartHbServer());
                MessageBus.Remove <RequestStartHbServer>(_clientManager.DoRestartHbReceiver);
            }

            if (RestartZyanServer)
            {
                MessageBus.Register <RequestStartZyanServer>(_zyanServer.DoRestart);
                MessageBus.Send(new RequestStartZyanServer());
                MessageBus.Remove <RequestStartZyanServer>(_zyanServer.DoRestart);
            }

            Builder.Output(ClassName + ": Terminada actualizacion de la configuracion del sistema", TraceEventType.Information);
        }
예제 #46
0
 public ContainerViewModel(IItemsSource itemsSource, ClientsClient clientsClient, MessageBus messageBus)
 {
     _itemsSource   = itemsSource;
     _clientsClient = clientsClient;
     _messageBus    = messageBus;
     Data           = new Data {
         SearchContext = new NullSearchContext()
     };
     GotoSearchPage();
 }
 private void StopSync()
 {
     MessageBus.Send(new SyncFinishedMessage(
                         ServiceContainer.Resolve <ISyncManager> (),
                         SyncMode.Full, false, null));
 }
예제 #48
0
 private void Awake() =>
 MessageBus.Subscribe(MessageBus.MessageType.AiSensoryMessage, this);
예제 #49
0
        public async Task FlushCommands_sends_all_commands_associated_with_specified_process_manager_sequentially()
        {
            // Arrange
            var serializer = new JsonMessageSerializer();

            var processManager      = new FakeProcessManager();
            var noiseProcessManager = new FakeProcessManager();

            var random  = new Random();
            var fixture = new Fixture();

            var envelopes = new List <Envelope>(
                from command in new[]
            {
                new FakeCommand {
                    Int32Value = random.Next(), StringValue = fixture.Create <string>()
                },
                new FakeCommand {
                    Int32Value = random.Next(), StringValue = fixture.Create <string>()
                },
                new FakeCommand {
                    Int32Value = random.Next(), StringValue = fixture.Create <string>()
                },
            }
                select new Envelope(
                    Guid.NewGuid(),
                    command,
                    operationId: Guid.NewGuid().ToString(),
                    correlationId: Guid.NewGuid(),
                    contributor: Guid.NewGuid().ToString()));

            using (var db = new ProcessManagerDbContext(_dbContextOptions))
            {
                db.PendingCommands.AddRange(from envelope in envelopes
                                            select PendingCommand.FromEnvelope(processManager, envelope, serializer));

                db.PendingCommands.AddRange(from envelope in new[]
                {
                    new Envelope(new object()),
                    new Envelope(new object()),
                    new Envelope(new object()),
                }
                                            select PendingCommand.FromEnvelope(noiseProcessManager, envelope, serializer));

                await db.SaveChangesAsync();
            }

            var messageBus = new MessageBus();

            var sut = new SqlCommandPublisher(
                () => new ProcessManagerDbContext(_dbContextOptions),
                serializer,
                messageBus,
                Mock.Of <IScheduledMessageBus>());

            // Act
            await sut.FlushCommands(processManager.Id, CancellationToken.None);

            // Assert
            messageBus.Sent.Should().BeEquivalentTo(envelopes, opts => opts.WithStrictOrdering().RespectingRuntimeTypes());
        }
예제 #50
0
 private void Ping(Message msg)
 {
     MessageBus.SendMessage(SubscribeType.Channel, Channel.ChannelIds[SubscribeType.Channel],
                            CommonMessage.Get(API.Messages.UPDATE,
                                              ObjectData.GetObjectData(_inventoryData)));
 }
예제 #51
0
        public void PrepareDocument()
        {
            var messageBus = new MessageBus();

            _document = CloneDocument(messageBus);
        }
예제 #52
0
 private void Zoom0Command_Executed(object sender, ExecutedRoutedEventArgs e)
 {
     MessageBus.Publish(new ZoomToFitCommand());
 }
예제 #53
0
 public void SetUp()
 {
     _messageBus = new MessageBus();
 }
예제 #54
0
 private void SaveCommand_Executed(object sender, ExecutedRoutedEventArgs e)
 {
     MessageBus.Publish(new SaveDocumentCommand());
 }
예제 #55
0
 public DeviceNotificationController(IMessageManager messageManager, MessageBus messageBus)
 {
     _messageManager = messageManager;
     _messageBus     = messageBus;
 }
예제 #56
0
        public async Task <IActionResult> AuthorizeOnly()
        {
            await MessageBus.PublishEvent(new UserAuthorizedEvt { Id = "user id", UserName = "******" });

            return(Ok());
        }
예제 #57
0
 public UserController(MessageBus messageBus, ILogger logger) : base(messageBus, logger)
 {
 }
예제 #58
0
 private void OnError(Exception ex)
 {
     MessageBus.Log(this, "Failed to initRuntime: " + DumpPath, ex);
 }
예제 #59
0
        public GlyphControlBar()
        {
            InitializeComponent();

            MessageBus.Subscribe <EditModeChangedEvent>(e => SwitchEditMode(e.EditMode));
        }
예제 #60
0
        /// <summary>
        /// Intenta reiniciar la aplicacion cliente. Si lo logra, el cliente se mueve
        /// de _timeOutList a _recoverList. Si no, el cliente se mueve a _deadList y no se monitorea mas.
        /// </summary>
        private void ClientTryToRestart()
        {
            bool flag;

            List <ClientData> buffer = new List <ClientData>(_timeOutList);

            foreach (var client in buffer)
            {
                // Log
                Builder.Output(string.Format(ClassName + ": Intentando reiniciar Cliente: {0} ejecutable: {1}.", client.Name, client.AppFilePath), TraceEventType.Information);

                // Comprobar si esta activo
                flag = GetProcessByName(client.AppName);

                // kill
                if (flag)
                {
                    KillProcessByName(client.AppName);
                }

                // "WerFault"
                const string pname = "WerFault";
                flag = GetProcessByName(pname);
                if (flag)
                {
                    KillProcessByName(pname);
                }
                // Realizar pausa mientras app termina
                System.Threading.Thread.Sleep(40);

                // Restart
                flag = StartProcessByName(client.AppFilePath);
                // Realizar pausa mientras sistema inicia
                System.Threading.Thread.Sleep(40);

                // Comprobar si se inicio, mover a donde corresponda y sacar de la cola
                if (flag)
                {
                    flag = GetProcessByName(client.AppName);
                }

                // Remover de la lista incondicionalmente.
                _timeOutList.Remove(client);

                // Mover en dependencia de si se reinicio o no.
                if (flag)
                {
                    client.Status = ClientStatus.Reiniciado;
                    client.RestartCount++;
                    client.RestartCountVolatil++;
                    client.EnterTime = DateTime.Now;

                    lock (_recoverList)
                    {
                        if (!_recoverList.Contains(client))
                        {
                            _recoverList.Add(client);
                        }
                    }
                    MessageBus.Send(new RequestSendEmail(EMessageAction.Restart, DateTime.Now, client));

                    Builder.Output(string.Format(ClassName + ": Reiniciado Cliente: {0} ejecutable: {1}.", client.Name, client.AppFilePath), TraceEventType.Information);
                }
                else
                {
                    client.Status = ClientStatus.Muerto;

                    lock (_deadList)
                    {
                        if (!_deadList.Contains(client))
                        {
                            _deadList.Add(client);
                        }
                    }

                    MessageBus.Send(new RequestSendEmail(EMessageAction.Dead, DateTime.Now, client));

                    Builder.Output(string.Format(ClassName + ": Imposible reiniciar Cliente: {0} ejecutable: {1}, movido a cola de Fuera de Control.", client.Name, client.AppFilePath), TraceEventType.Critical);
                }
            }
        }