Exemple #1
0
 public void Unsubscribe <T>(IMessageSubscriber <T> subscriber) where T : IMessage
 {
     if (_subscribers.Contains(subscriber))
     {
         _subscribers.Remove(subscriber);
     }
 }
 public CommandConsumer(IMessageSubscriber subscriber, IEnumerable <ICommandHandler> commandHandlers)
 {
     this.subscriber             = subscriber;
     this.commandHandlers        = commandHandlers;
     subscriber.MessageReceived += async(sender, e) =>
     {
         if (this.commandHandlers != null)
         {
             foreach (var handler in this.commandHandlers)
             {
                 var handlerType     = handler.GetType();
                 var messageType     = e.Message.GetType();
                 var methodInfoQuery = from method in handlerType.GetMethods(BindingFlags.Public | BindingFlags.Instance)
                                       let parameters = method.GetParameters()
                                                        where method.Name == "HandleAsync" &&
                                                        method.ReturnType == typeof(Task) &&
                                                        parameters.Length == 1 &&
                                                        parameters[0].ParameterType == messageType
                                                        select method;
                 var methodInfo = methodInfoQuery.FirstOrDefault();
                 if (methodInfo != null)
                 {
                     await(Task) methodInfo.Invoke(handler, new[] { e.Message });
                 }
             }
         }
     };
 }
 internal SubscriberInfo(IMessageSubscriber Subscriber)
 {
     SubscriberType = Subscriber.GetType();
     Instance       = Subscriber;
     Roles          = new RoleSet(SubscriberType);
     _ObservedSet   = new UniqueSet <IMessageSubscriber>();
 }
 /// <summary>
 /// Removes the observed-object from the observer if and only if
 /// the given object was the observed object.
 /// </summary>
 /// <param name="ClearIfObserved">The object to cease observing</param>
 /// <returns>True if the given object was being observed by THIS object.</returns>
 public bool ClearObservedObject(IMessageSubscriber ClearIfObserved)
 {
     return(_ObservedSet.Has(ClearIfObserved, () =>
     {
         _ObservedSet.Remove(ClearIfObserved);
     }));
 }
Exemple #5
0
        /// <summary>
        /// Submits a message to its channel's subscribers.
        /// </summary>
        /// <param name="sender">The submitter node.</param>
        /// <param name="message">The message to submit.</param>
        /// <returns>True if the operation succeeded.</returns>
        public bool SubmitMessage(IMessageSubscriber sender, IrisMessage message)
        {
            if (message.PublisherId == null || !_nodes.ContainsKey(sender))
            {
                return(false);
            }

            IrisConcurrentHashSet <Guid> _deliveryNodes            = new IrisConcurrentHashSet <Guid>();
            Action <IMessageSubscriber>  sendMessageToOthersAction = (n) =>
            {
                if (n != sender && !_deliveryNodes.Contains(n.Id))
                {
                    _deliveryNodes.Add(n.Id);
                    n.ReceiveMessage(message);
                }
            };

            if (message.TargetChannel == null)
            {
                // Broadcast
                _nodes.Keys.ForEach(sendMessageToOthersAction);
                return(true);
            }
            else
            {
                var irisNodes = _subsDictionary.GetSubscriptions(message.TargetChannel, message.PropagateThroughHierarchy);
                if (irisNodes != null)
                {
                    irisNodes.ForEach(sendMessageToOthersAction);
                }

                return(irisNodes != null);
            }
        }
        private static void LoadHalJson <T>(
            out IMessagePublisher publisher,
            out IMessageSubscriber <T> subscriber) where T : new()
        {
            var connectionString = "server=.;database=scratchpad;trusted_connection=true;";
            var pubStoreSproc    = "usp_StoreMessage";
            var pubReceiveSproc  = "usp_GetPageOfMessages";
            var subGetSproc      = "usp_GetLastMessageId";
            var subUpdateSproc   = "usp_UpdateLastMessageId";

            //WriteColoredText("Connection string: ");
            //var connectionString = Console.ReadLine();

            //WriteColoredText("Publish store sproc: ");
            //var pubStoreSproc = Console.ReadLine();

            //WriteColoredText("Publish receive sproc: ");
            //var pubReceiveSproc = Console.ReadLine();

            //WriteColoredText("Receive get sproc: ");
            //var subGetSproc = Console.ReadLine();

            //WriteColoredText("Receive update sproc: ");
            //var subUpdateSproc = Console.ReadLine();

            publisher = new SyndicationMessagePublisher(new SqlServerMessageRepository(connectionString, pubStoreSproc, pubReceiveSproc, 10));

            var feedPositionRepo = new SqlServerFeedPositionRepository(connectionString, subGetSproc, subUpdateSproc);

            subscriber = new SyndicationPollingMessageReceiver <T>(
                new HalJsonMessageClient(feedPositionRepo, new HttpClientWrapper("http://localhost:16972/"), new MessageIdentifierFactory()),
                feedPositionRepo);
        }
Exemple #7
0
        /// <summary>
        /// Unregisters a node. This also deletes every subscription of that node.
        /// </summary>
        /// <param name="node">The node to unregister.</param>
        /// <returns>True if the operation succeeded.</returns>
        public bool Unregister(IMessageSubscriber node)
        {
            if (!_nodes.ContainsKey(node))
            {
                return(false);
            }

            List <string> channels;
            bool          success = _nodes.TryGetValue(node, out channels);

            // Unregister the node and remove the subscriptions
            // with removeChannelFromRegisteredNode: false
            // to avoid concurrent modifications over the channels list
            foreach (var channel in channels)
            {
                if (!(success = Unsubscribe(node, channel, removeChannelFromRegisteredNode: false)))
                {
                    break;
                }
            }

            if (success)
            {
                success = _nodes.TryRemove(node, out channels);
            }

            return(success);
        }
Exemple #8
0
        /// <summary>
        /// Method used to avoid having concurrent modifications over the subscriptions when the Unregister is invoked.
        /// </summary>
        /// <param name="node">The node to unsubscribe.</param>
        /// <param name="channel">The channel from which unsubscribe.</param>
        /// <param name="removeChannelFromRegisteredNode">If true, removes the channel from the main nodes list.</param>
        /// <returns>True if the operation succeeded.</returns>
        private bool Unsubscribe(IMessageSubscriber node, string channel, bool removeChannelFromRegisteredNode)
        {
            if (!_nodes.ContainsKey(node))
            {
                return(false);
            }

            bool success = false;

            if (channel != null)
            {
                success = _subsDictionary.Remove(node, channel);
            }

            if (removeChannelFromRegisteredNode && success)
            {
                try
                {
                    _nodes[node].Remove(channel);
                }
                catch (Exception ex) when(!(ex is KeyNotFoundException))
                {
                    success = false;
                }
            }

            return(success);
        }
Exemple #9
0
        /// <summary>
        /// Subscribes a node to a channel in order to receive target messages.
        /// </summary>
        /// <param name="node">The node to subscribe.</param>
        /// <param name="channel">The channel to which subscribe.</param>
        /// <returns>True if the operation succeeded.</returns>
        public bool Subscribe(IMessageSubscriber node, string channel)
        {
            if (!_nodes.ContainsKey(node))
            {
                return(false);
            }

            bool success = false;

            if (channel != null)
            {
                success = _subsDictionary.Add(node, channel);
            }

            try
            {
                if (success)
                {
                    _nodes[node].Add(channel);
                }
            }
            catch (Exception ex) when(!(ex is KeyNotFoundException))
            {
                _subsDictionary.Remove(node, channel);
                success = false;
            }

            return(success);
        }
Exemple #10
0
 public CreateOrganizationAdminProfileRollbackSubscriber(
     ILogger logger,
     IMessageSubscriber messageSubscriber,
     IServiceProvider serviceProvider,
     IMessagePublisher publisher) : base(logger, messageSubscriber, serviceProvider, publisher)
 {
 }
Exemple #11
0
 public void Subscribe <T>(IMessageSubscriber <T> subscriber) where T : IMessage
 {
     if (!_subscribers.Contains(subscriber))
     {
         _subscribers.Add(subscriber);
     }
 }
Exemple #12
0
 public UpdatePhysicianProfileRollbackSubscriber(
     ILogger logger,
     IMessageSubscriber messageSubscriber,
     IServiceProvider serviceProvider,
     IMessagePublisher publisher) : base(logger, messageSubscriber, serviceProvider, publisher)
 {
 }
 public CreateSuperAdminRollbackSubscriber(
     ILogger logger,
     IMessageSubscriber messageSubscriber,
     IServiceProvider serviceProvider,
     IMessagePublisher publisher) : base(logger, messageSubscriber, serviceProvider, publisher)
 {
 }
Exemple #14
0
        public WalletController(
            IBlockchainController blockchainController,
            ICertificateService certificateService,
            IMessagePublisher messagePublisher,
            IMessageSubscriber messageSubscriber,
            INetworkController networkController,
            INotificationService notificationService,
            ISettingsManager settingsManager)
        {
            this.blockchainController = blockchainController;
            this.certificateService   = certificateService;
            this.messagePublisher     = messagePublisher;
            this.messageSubscriber    = messageSubscriber;
            this.networkController    = networkController;
            this.notificationService  = notificationService;

            this.blockchainDataDirectoryPath = settingsManager.BlockchainDataDirectoryPath;

            this.localNodePort = settingsManager.LocalNodePort;
            this.localWSPort   = settingsManager.LocalWSPort;

            this.certificateCachePath = settingsManager.CertificateCachePath;

            this.certificateQueryResultCache = new Dictionary <ECPoint, CertificateQueryResult>();
        }
 public MessageBusHub(IMessageSubscriber subscriber) {
     subscriber.Subscribe<EntityChanged>(OnEntityChanged);
     subscriber.Subscribe<EventOccurrence>(OnEventOccurrence);
     subscriber.Subscribe<PlanChanged>(OnPlanChanged);
     subscriber.Subscribe<PlanOverage>(OnPlanOverage);
     subscriber.Subscribe<StackUpdated>(OnStackUpdated);
 }
Exemple #16
0
 /// <inheritdoc/>
 public void Subscribe(IMessageSubscriber <TMessageType> receiver, TMessageType type)
 {
     lock (subscribers)
     {
         subscribers[type].Add(receiver);
     }
 }
Exemple #17
0
 public static void SubscribeEvent <TEvent>(this IMessageSubscriber subscriber)
     where TEvent : class, IEvent
 => subscriber.Subscribe <TEvent>(async(sp, @event) =>
 {
     var dispatcher = sp.GetService <IEventDispatcher>();
     await dispatcher.DispatchAsync(@event);
 });
        public void Register(IMessageSubscriber Subscriber)
        {
            SubscriberInfo subInfo = GetInfoFor(Subscriber);

            if (subInfo == null)
            {
                subInfo = new SubscriberInfo(Subscriber);
            }
            else
            {
                _Logger.LogAt(LogLevel.LL_DebugFramework,
                              "Already had a subscriber for same instance: " + subInfo.ToString()
                              );
                return;
            }

            _Logger.LogAt(LogLevel.LL_Info, "Creating Group: " + subInfo.SubscriberType.Name);
            _MessageHandlers.CreateGroup(subInfo);

            _Logger.LogAt(LogLevel.LL_DebugFramework, "START --Adding Handlers--");
            foreach (HandlerInfo info in FindHandlers(subInfo))
            {
                _Logger.LogAt(LogLevel.LL_DebugFramework, "Handler: " + info.ToString()
                              );
                _MessageHandlers.ToGroup(
                    subInfo,
                    (Groups <SubscriberInfo, HandlerInfo> .Members handlers) => { handlers.Add(info); }
                    );
            }
            _Logger.LogAt(LogLevel.LL_DebugFramework, "END --Adding Handlers--");
        }
    /// <summary>
    /// Initializes a new instance of L1L2RedisCache.
    /// </summary>
    public L1L2RedisCache(
        IMemoryCache l1Cache,
        IOptions <L1L2RedisCacheOptions> l1l2RedisCacheOptionsAccessor,
        Func <IDistributedCache> l2CacheAccessor,
        IMessagePublisher messagePublisher,
        IMessageSubscriber messageSubscriber)
    {
        L1Cache = l1Cache;
        L1L2RedisCacheOptions = l1l2RedisCacheOptionsAccessor.Value;
        L2Cache           = l2CacheAccessor();
        MessagePublisher  = messagePublisher;
        MessageSubscriber = messageSubscriber;

        Database = new Lazy <IDatabase>(() =>
                                        L1L2RedisCacheOptions
                                        .ConnectionMultiplexerFactory()
                                        .GetAwaiter()
                                        .GetResult()
                                        .GetDatabase(
                                            L1L2RedisCacheOptions
                                            .ConfigurationOptions?
                                            .DefaultDatabase ?? -1));

        MessageSubscriber.Subscribe();
    }
Exemple #20
0
 public static Task SubscribeAsync <TMessage>(
     this IMessageSubscriber subscriber,
     Func <TMessage, CancellationToken, Task> handlerFunc,
     CancellationToken token = default)
 {
     return(subscriber.SubscribeAsync(new AnnonymousMessageHandler <TMessage>(handlerFunc), token));
 }
Exemple #21
0
 public static Task SubscribeAsync(this IMessageSubscriber subscriber, Action <IMessage> handler, CancellationToken cancellationToken = default)
 {
     return(subscriber.SubscribeAsync((msg, token) => {
         handler(msg);
         return Task.CompletedTask;
     }, cancellationToken));
 }
Exemple #22
0
 public MessageBusHub(IMessageSubscriber subscriber)
 {
     subscriber.Subscribe <EntityChanged>(OnEntityChanged);
     subscriber.Subscribe <PlanChanged>(OnPlanChanged);
     subscriber.Subscribe <PlanOverage>(OnPlanOverage);
     subscriber.Subscribe <UserMembershipChanged>(OnUserMembershipChanged);
 }
 public CommandsObserver(
     IMessageSubscriber commandsQueue,
     DocumentsJoinerStatusObserverWorker statusObserver)
 {
     this.commandsQueue  = commandsQueue ?? throw new ArgumentNullException(nameof(commandsQueue));
     this.statusObserver = statusObserver ?? throw new ArgumentNullException(nameof(statusObserver));
 }
 public BuildsController(IDocumentStore store, IBuildRepository buildRepository, ProcedureExecutor procedureExecutor, IMessageSubscriber messageSubscriber)
 {
     this.store = store;
     this.buildRepository = buildRepository;
     this.procedureExecutor = procedureExecutor;
     this.messageSubscriber = messageSubscriber;
 }
Exemple #25
0
 private void AssertValid(IMessageSubscriber _Instance, Type _Origin)
 {
     if (_Instance != null && (_Instance.GetType() != _Origin && !_Instance.GetType().IsSubclassOf(_Origin)))
     {
         throw new ArgumentException("Sending instance expected to be of type " + _Origin.Name);
     }
 }
 public MessageBusBroker(IConnectionManager connectionManager, IConnectionMapping connectionMapping, IMessageSubscriber subscriber, ILogger <MessageBusBroker> logger)
 {
     _connectionManager = connectionManager;
     _connectionMapping = connectionMapping;
     _subscriber        = subscriber;
     _logger            = logger;
 }
 internal SubscriberInfo(IMessageSubscriber Subscriber)
 {
     SubscriberType = Subscriber.GetType();
     Instance = Subscriber;
     Roles = new RoleSet(SubscriberType);
     _ObservedSet = new UniqueSet<IMessageSubscriber>();
 }
Exemple #28
0
 public CommandConsumer(
     IMessageSubscriber subscriber,
     IEnumerable <ICommandHandler> commandHandlers)
 {
     Subscriber                  = subscriber;
     CommandHandlers             = commandHandlers;
     subscriber.MessageReceived += (sender, e) =>
     {
         if (CommandHandlers == null)
         {
             return;
         }
         foreach (var handler in CommandHandlers)
         {
             var handlerType     = handler.GetType();
             var messageType     = e.Message.GetType();
             var methodInfoQuery =
                 from method in handlerType.GetMethods(BindingFlags.Public | BindingFlags.Instance)
                 let parameters = method.GetParameters()
                                  where method.Name == "Handle" &&
                                  method.ReturnType == typeof(IObservable <Unit>) &&
                                  parameters.Length == 1 &&
                                  parameters[0].ParameterType == messageType
                                  select method;
             var methodInfo = methodInfoQuery.FirstOrDefault();
             methodInfo?.Invoke(handler, new[] { e.Message });
         }
     };
 }
Exemple #29
0
 /// <inheritdoc/>
 public void Unsubscribe(IMessageSubscriber <TMessageType> receiver, TMessageType type)
 {
     lock (subscribers)
     {
         subscribers[type].Remove(receiver);
     }
 }
 public PollChannel(IMessageSubscriber messageSubscriber, string channel, string @group)
 {
     this.messageSubscriber = messageSubscriber;
     messageSubscriber.AddListener(this);
     this.channel = channel;
     this.group = group;
 }
Exemple #31
0
 /// <inheritdoc/>
 public void Unsubscribe(IMessageSubscriber <TMessageType> receiver)
 {
     lock (subscribers)
     {
         subscribers.RemoveFromAll(receiver);
     }
 }
Exemple #32
0
 public UpdateOrganizationUserRollbackSubscriber(
     ILogger logger,
     IMessageSubscriber messageSubscriber,
     IServiceProvider serviceProvider,
     IMessagePublisher publisher) : base(logger, messageSubscriber, serviceProvider, publisher)
 {
 }
 public virtual void UnSubscribe <T>(IMessageSubscriber <T> subscriber) where T : IMessage
 {
     if (_messageSubscribers.TryGetValue(typeof(T), out IList <IMessageSubscriber <IMessage> > list))
     {
         list.Remove((IMessageSubscriber <IMessage>)subscriber);
     }
 }
Exemple #34
0
 public static void Subscribe <T>(this IMessageSubscriber subscriber, Action <T> handler, CancellationToken cancellationToken = default(CancellationToken)) where T : class
 {
     subscriber.Subscribe <T>((msg, token) => {
         handler(msg);
         return(Task.CompletedTask);
     }, cancellationToken);
 }
 public void Verify(string revision, IMessageSubscriber subscriber)
 {
     this.revision = revision;
     var revisionHashLength = "280bb4850c149a0a33412093cba5d22b4d10bff4".Length;
     if (revision.Length == revisionHashLength && Regex.Match(revision, "[0-9a-fA-F]*").Success)
     {
         subscriber.Published(string.Format("Revision number is a valid Git hash."));
         subscriber.Ask("Pull this revision? (Y/N)", this);
     }
 }
Exemple #36
0
        private Message(Type _Origin, Type _TargetRole, object _EventType, IMessageSubscriber _Instance, object _Payload)
        {
            Origin = _Origin;
            SenderInstance = _Instance;
            EventType = _EventType;
            TargetRole = _TargetRole;
            Payload = _Payload;
            TargetInstance = null;

            AssertValid(_TargetRole);
            AssertValid(_Instance, _Origin);
        }
Exemple #37
0
 public Message(IMessageSubscriber _OriginInstance, Type _TargetRole, object _EventType, object _Payload)
     : this(_OriginInstance.GetType(), _TargetRole, _EventType, _OriginInstance, _Payload)
 {
 }
 /// <summary>
 /// Removes the observed-object from the observer if and only if
 /// the given object was the observed object.
 /// </summary>
 /// <param name="ClearIfObserved">The object to cease observing</param>
 /// <returns>True if the given object was being observed by THIS object.</returns>
 public bool ClearObservedObject(IMessageSubscriber ClearIfObserved)
 {
     return _ObservedSet.Has( ClearIfObserved, () =>
     {
         _ObservedSet.Remove( ClearIfObserved );
     });
 }
 public MessageBusBroker(IConnectionManager connectionManager, IConnectionMapping connectionMapping, IMessageSubscriber subscriber) {
     _connectionManager = connectionManager;
     _connectionMapping = connectionMapping;
     _subscriber = subscriber;
 }
 public SampleService(ILogger logger, IMessageSubscriber sampleMessageSubscriber)
 {
     _logger = logger;
     _sampleMessageSubscriber = sampleMessageSubscriber;
 }
Exemple #41
0
 public DllDebugger(IMessageSubscriber subscriber, ISourceRepository sourceRepository)
 {
     this.subscriber = subscriber;
     this.sourceRepository = sourceRepository;
     NumberOfModulesLoaded = 0;
 }
Exemple #42
0
 private void AssertValid(IMessageSubscriber _Instance, Type _Origin)
 {
     if ( _Instance != null && (_Instance.GetType() != _Origin && ! _Instance.GetType().IsSubclassOf(_Origin) )) {
         throw new ArgumentException("Sending instance expected to be of type " + _Origin.Name);
     }
 }
 public MessagePublisher(IMessageSubscriber messageSubscriber)
 {
     _messageSubscriber = messageSubscriber;
 }
Exemple #44
0
 /// <summary>
 /// Identifies sender both as type and as a specific instance.  Useful for an observed type
 /// like a model.
 /// </summary>
 /// <param name="_Origin">Sender type, for grouping.</param>
 /// <param name="_TargetRole">Role that member instances must implement to receive message.</param>
 /// <param name="_EventType">The event type or function number.</param>
 /// <param name="_Instance">The source instance (of type _Origin)</param>
 public Message(Type _Origin, Type _TargetRole, object _EventType, IMessageSubscriber _Instance)
     : this(_Origin, _TargetRole, _EventType, _Instance, null)
 {
 }
 public void SetObservedObject(IMessageSubscriber ObservedObject)
 {
     _ObservedSet.Add(ObservedObject);
 }
 public MessageBusBroker(IConnectionManager connectionManager, ConnectionMapping userIdConnections, IMessageSubscriber subscriber) {
     _connectionManager = connectionManager;
     _userIdConnections = userIdConnections;
     _subscriber = subscriber;
 }
Exemple #47
0
 /// <summary>
 /// Where the destination's instance is known, this can be used to short circuit the
 /// message send addressing scheme.
 /// It allows a call to go down a hierarchy: e.g. Controller -> Renderer -> Palette
 /// It allows a response to a received message.
 /// </summary>
 /// <param name="Target">The instance to exclusively receive this message.</param>
 public void SetTargetInstance(IMessageSubscriber Target)
 {
     TargetInstance = Target;
 }
 public void AnsweredWith(string response, IMessageSubscriber subscriber)
 {
     if (responseParser.Yes(response))
         subscriber.Published(string.Format("Pulling source corresponding to {0}", revision));
     else subscriber.Published(string.Format("Skipping revision {0}", revision));
 }
 public static void SendVia(Message msg, MessageBus MsgBus, IMessageSubscriber Caller)
 {
     msg.ActualSender = Caller;
     MsgBus.Send(msg);
 }