Exemplo n.º 1
0
        /// <summary>
        ///     Creates a subscription to the specified Item.
        /// </summary>
        /// <remarks>
        ///     <para>
        ///         Upon the addition of the initial subscriber, an entry is added to the <see cref="Subscriptions"/> Dictionary
        ///         keyed with the specified Item with a new <see cref="List{T}"/> of type <see cref="Action{T}"/> containing one
        ///         entry corresponding to the specified callback delegate.
        ///     </para>
        ///     <para>
        ///         Successive additions add each of the specified callback delegates to the <see cref="Subscriptions"/> dictionary.
        ///     </para>
        /// </remarks>
        /// <param name="item">The <see cref="Item"/> to which the subscription should be added.</param>
        /// <param name="callback">The callback delegate to be invoked upon change of the subscribed Item.</param>
        /// <returns>A value indicating whether the operation succeeded.</returns>
        public bool Subscribe(Item item, Action <object> callback)
        {
            logger.EnterMethod(xLogger.Params(item, callback));
            logger.Debug("Subscribing to Item '" + item.FQN + "' on Provider '" + ItemProviderName + "'...");

            bool retVal = false;

            if (!Subscriptions.ContainsKey(item))
            {
                logger.Debug("The Item '" + item.FQN + "' has been added to the Subscriptions list.");
                Subscriptions.Add(item, new List <Action <object> >());
            }

            if (Subscriptions[item].Where(c => ReferenceEquals(c, callback)).Count() <= 0)
            {
                int count = Subscriptions[item].Count;

                Subscriptions[item].Add(callback);

                logger.Debug("Subscriptions to Item '" + item.FQN + "' on Provider '" + ItemProviderName + "' changed from " + count + " to " + Subscriptions[item].Count + ".");

                retVal = true;
            }
            else
            {
                logger.Debug("The specified item '" + item.FQN + "' and callback '" + callback?.Target?.ToString() + "' has already been subscribed.");
            }

            logger.ExitMethod(retVal);
            return(retVal);
        }
Exemplo n.º 2
0
        /// <summary>
        ///     Removes a subscription from the specified ConnectorItem.
        /// </summary>
        /// <remarks>
        ///     <para>
        ///         Upon the removal of a subscriber the specified callback delegate is removed from the corresponding Dictionary
        ///         entry for the specified <see cref="Item"/>.
        ///     </para>
        ///     Upon removal of the final subscriber, the Dictionary key corresponding to the specified <see cref="Item"/> is
        ///     completely removed.
        /// </remarks>
        /// <param name="item">The <see cref="Item"/> for which the subscription should be removed.</param>
        /// <param name="callback">The callback delegate to be invoked upon change of the subscribed Item.</param>
        /// <returns>A value indicating whether the operation succeeded.</returns>
        public bool UnSubscribe(Item item, Action <object> callback)
        {
            bool retVal = false;

            try
            {
                if (Subscriptions.ContainsKey(item))
                {
                    Subscriptions[item].Remove(callback);

                    if (Subscriptions[item].Count == 0)
                    {
                        Subscriptions.Remove(item);
                    }

                    retVal = true;
                }
            }
            catch (Exception ex)
            {
                logger.Exception(ex);
            }

            return(retVal);
        }
Exemplo n.º 3
0
 public void AddSubscription(Subscription subscription)
 {
     if (!Subscriptions.ContainsKey(subscription.UserId))
     {
         Subscriptions.Add(subscription.UserId, subscription);
     }
 }
Exemplo n.º 4
0
 public bool Add(dynamic handler, string subscriberID, int povDirection = 0)
 {
     if (povDirection == 0)
     {
         // Regular mapping
         if (Subscriptions.ContainsKey(subscriberID))
         {
             Subscriptions[subscriberID].Callback = handler;
         }
         else
         {
             Subscriptions.Add(subscriberID, new Subscription(handler));
         }
         return(true);
     }
     else
     {
         //Pov Direction Mapping
         if (povDirection < 1 || povDirection > 4)
         {
             return(false);
         }
         if (!PovDirectionSubscriptions.ContainsKey(povDirection))
         {
             PovDirectionSubscriptions.Add(povDirection, new SubscribedPovDirection(povDirection));
         }
         return(PovDirectionSubscriptions[povDirection].Add(subscriberID, handler));
     }
 }
Exemplo n.º 5
0
        /// <summary>
        /// Subscribe to channel
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="channelName"></param>
        /// <param name="action"></param>
        /// <returns></returns>
        public Task Subscribe <T>(string channelName, Action <T> action) where T : class
        {
            // Add the process type to the list of subscribed processes
            if (!Subscriptions.ContainsKey(channelName))
            {
                Subscriptions.Add(channelName, (messageBody) =>
                {
                    if (messageBody is T)
                    {
                        action(messageBody as T);
                    }
                    else
                    {
                        var obj = JsonConvert.DeserializeObject <T>(messageBody);
                        action(obj);
                    }
                });
            }

            // Execute all unexecuted processes from the queue (database in this case)
            Task.Run(() =>
            {
                ProcessUnprocessedTasks(channelName, action);
            });

            return(Task.CompletedTask);
        }
Exemplo n.º 6
0
 public bool Remove(string subscriberID, int povDirection = 0)
 {
     if (povDirection == 0)
     {
         // Regular mapping
         if (!Subscriptions.ContainsKey(subscriberID))
         {
             return(false);
         }
         Subscriptions.Remove(subscriberID);
         return(true);
     }
     else
     {
         // POV Direction Mapping
         if (PovDirectionSubscriptions.ContainsKey(povDirection))
         {
             var ret = PovDirectionSubscriptions[povDirection].Remove(subscriberID);
             if (ret && PovDirectionSubscriptions[povDirection].IsEmpty())
             {
                 PovDirectionSubscriptions.Remove(povDirection);
             }
             return(ret);
         }
         return(false);
     }
 }
Exemplo n.º 7
0
        protected void ProcessQueuedMessages(XmlStream xml, CancellationToken canceltoken)
        {
            Message msg;

            while (!canceltoken.IsCancellationRequested && QueuedMessages.TryDequeue(out msg))
            {
                foreach (XElement el in msg.Content)
                {
                    if (el.Name.ToString() == "{google:push}push")
                    {
                        string channel = el.Attribute("channel").Value;
                        if (Subscriptions.ContainsKey(channel))
                        {
                            Logger.Log(LogLevel.Debug, "Handling message for channel {0}", channel);
                            Subscriptions[channel](el, this);
                        }
                        else
                        {
                            Logger.Log(LogLevel.Debug, "Message for unknown channel {0}", channel);
                        }
                    }
                }
            }

            canceltoken.ThrowIfCancellationRequested();
        }
Exemplo n.º 8
0
        /// <summary>
        ///     Removes a subscription from the specified ConnectorItem.
        /// </summary>
        /// <remarks>
        ///     <para>
        ///         Upon the removal of a subscriber the specified callback delegate is removed from the corresponding Dictionary
        ///         entry for the specified <see cref="Item"/>.
        ///     </para>
        ///     Upon removal of the final subscriber, the Dictionary key corresponding to the specified <see cref="Item"/> is
        ///     completely removed.
        /// </remarks>
        /// <param name="item">The <see cref="Item"/> for which the subscription should be removed.</param>
        /// <param name="callback">The callback delegate to be invoked upon change of the subscribed Item.</param>
        /// <returns>A value indicating whether the operation succeeded.</returns>
        public bool UnSubscribe(Item item, Action <object> callback)
        {
            logger.EnterMethod(xLogger.Params(item, callback));
            logger.Debug("UnSubscribing from Item '" + item.FQN + "' on Provider '" + ItemProviderName + "'...");

            bool retVal = false;

            if (Subscriptions.ContainsKey(item))
            {
                int count = Subscriptions[item].Count;

                Subscriptions[item].Remove(callback);

                logger.Debug("Subscriptions to Item '" + item.FQN + "' on Provider '" + ItemProviderName + "' changed from " + count + " to " + Subscriptions[item].Count + ".");

                if (Subscriptions[item].Count == 0)
                {
                    Subscriptions.Remove(item);

                    logger.Debug("Item '" + item.FQN + "' has no further subscribers and has been removed from the Subscriptions list.");
                }

                retVal = true;
            }
            else
            {
                logger.Debug("Subscription for Item '" + item.FQN + "' on Provider '" + ItemProviderName + "' not found.");
            }

            logger.ExitMethod(retVal);
            return(retVal);
        }
Exemplo n.º 9
0
 public bool Remove(string subscriberID, int povDirection)
 {
     if (!Subscriptions.ContainsKey(subscriberID))
     {
         return(false);
     }
     Subscriptions.Remove(subscriberID);
     return(true);
 }
Exemplo n.º 10
0
 public bool Add(dynamic handler, string subscriberID, int povDirection)
 {
     if (Subscriptions.ContainsKey(subscriberID))
     {
         Subscriptions[subscriberID].Callback = handler;
     }
     else
     {
         Subscriptions.Add(subscriberID, new Subscription(handler));
     }
     return(true);
 }
Exemplo n.º 11
0
        private void OnDynamicImageChange(object sender, FileSystemEventArgs args)
        {
            logger.Info("File watcher for " + args.FullPath);

            Item key = Find("Simulation.Binary.DynamicImage");

            if (Subscriptions.ContainsKey(key))
            {
                foreach (Action <object> callback in Subscriptions[key])
                {
                    callback.Invoke(ReadFile(args.FullPath));
                    logger.Info("Invoked dynamic image change delegate");
                }
            }
        }
Exemplo n.º 12
0
        public void SubscribeTo(Type type, Action <RemoteSubscriptionHandle> callback)
        {
            if (Subscriptions.ContainsKey(type))
            {
                Subscriptions[type]++;
            }
            else
            {
                Subscriptions.Add(type, 1);
            }

            callback(new RemoteSubscriptionHandle {
                PublisherNodeID = EllaConfiguration.Instance.NodeId + 1, PublisherId = 12, SubscriberNodeID = EllaConfiguration.Instance.NodeId
            });
        }
Exemplo n.º 13
0
        public void Dispose()
        {
            if (_isDisposed)
            {
                return;
            }

            if (_subscriptions.ContainsKey(_subscription))
            {
                _subscriptions.TryRemove(_subscription, out _);
            }

            _isDisposed = true;
            GC.SuppressFinalize(this);
        }
Exemplo n.º 14
0
        /// <summary>
        ///     Removes a subscription from the specified Item.
        /// </summary>
        /// <remarks>
        ///     Decrements the number of subscribers within the <see cref="Subscriptions"/> Dictionary. Upon removal of the final
        ///     subscriber, the subscription is completely removed.
        /// </remarks>
        /// <param name="item">The <see cref="Item"/> for which the subscription should be removed.</param>
        /// <threadsafety instance="true"/>
        /// <returns>An <see cref="Result"/> containing the result of the operation.</returns>
        public Result UnSubscribe(Item item)
        {
            logger.EnterMethod(xLogger.Params(item));
            logger.Info("Removing Subscription for Item '" + item.FQN + "'...");

            Result retVal = new Result();

            try
            {
                // always ensure the key exists before trying to reference it.
                if (!Subscriptions.ContainsKey(item))
                {
                    retVal.AddError("The Item '" + item.FQN + "' is not currently subscribed.");
                }
                else
                {
                    // lock the Subscriptions collection
                    lock (SubscriptionsLock)
                    {
                        // decrement the number of active subscriptions
                        Subscriptions[item]--;

                        // if the number of subscriptions is zero (or less than zero somehow), remove it from the dictionary.
                        if (Subscriptions[item] <= 0)
                        {
                            Subscriptions.Remove(item);
                            retVal.AddInfo("The Item '" + item.FQN + "' has been fully unsubscribed.");
                        }
                        else
                        {
                            retVal.AddInfo("The Item '" + item.FQN + "' now has " + Subscriptions[item] + " subscriber(s).");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                retVal.AddError("Error unsubscribing from Item '" + item.FQN + "': " + ex.Message);
            }

            retVal.LogResult(logger);
            logger.ExitMethod(retVal);
            return(retVal);
        }
Exemplo n.º 15
0
        public void Subscribe(NatsSubscription natsSubscription)
        {
            if (Subscriptions.ContainsKey(natsSubscription))
            {
                return;
            }

            Logger.Info($"{nameof(Subscribe)}: {natsSubscription.Subject}");
            List <IAsyncSubscription> subs = new List <IAsyncSubscription>();

            foreach (var conn in ConnectionsByName.Values)
            {
                IAsyncSubscription sub = conn.SubscribeAsync(natsSubscription.Subject, OnMessage);
                subs.Add(sub);
            }

            Subscriptions[natsSubscription] = subs;
            natsSubscription.Subscribed     = subs.Any();
            Subscribed?.Invoke(natsSubscription);
        }
Exemplo n.º 16
0
        public async Task SubscribeToChunk(ChunkKey key)
        {
            if (Subscriptions.ContainsKey(key))
            {
                return;
            }

            var channel = OutgoingChannel;//copy to local for closure;
            var chunkHandlerSubscription = await BattleHandler.GetChunkHandlerAndSubscribeAsync(key, (chunkKey, update) => OnChunkUpdateAsync(key, update, channel));

            if (Subscriptions.TryAdd(key, chunkHandlerSubscription))
            {
                await SendChunkStateAsync(key, chunkHandlerSubscription);
            }
            else
            {
                chunkHandlerSubscription.Dispose();
                throw new InvalidOperationException("Duplicate subscription is detected.");
            }
        }
Exemplo n.º 17
0
 protected void ConfirmDataPushing(string taskName, string subscription, Action taskFunc)
 {
     lock (taskName)
     {
         if (DataPushingTasks != null)
         {
             if (subscription != null)
             {
                 if (!Subscriptions.ContainsKey(taskName))
                 {
                     Subscriptions[taskName] = new HashSet <string>();
                 }
                 Subscriptions[taskName].Add(subscription);
             }
             if (!DataPushingTasks.ContainsKey(taskName))
             {
                 DataPushingTasks[taskName] = new Task(() =>
                 {
                     while (true)
                     {
                         Thread.Sleep(Interval);
                         lock (Locker)
                         {
                             if (!IsOnline)
                             {
                                 break;
                             }
                             taskFunc.Invoke();
                         }
                     }
                     if (DataPushingTasks != null)
                     {
                         DataPushingTasks.Remove(taskName);
                         Subscriptions.Remove(taskName);
                     }
                 });
                 DataPushingTasks[taskName].Start();
             }
         }
     }
 }
Exemplo n.º 18
0
        /// <summary>
        ///     Creates a subscription to the specified Item.
        /// </summary>
        /// <remarks>
        ///     <para>
        ///         Upon the addition of the initial subscriber, an entry is added to the <see cref="Subscriptions"/> Dictionary
        ///         keyed with the specified Item with a new <see cref="List{T}"/> of type <see cref="Action{T}"/> containing one
        ///         entry corresponding to the specified callback delegate.
        ///     </para>
        ///     <para>
        ///         Successive additions add each of the specified callback delegates to the <see cref="Subscriptions"/> dictionary.
        ///     </para>
        /// </remarks>
        /// <param name="item">The <see cref="Item"/> to which the subscription should be added.</param>
        /// <param name="callback">The callback delegate to be invoked upon change of the subscribed Item.</param>
        /// <returns>A value indicating whether the operation succeeded.</returns>
        public bool Subscribe(Item item, Action <object> callback)
        {
            bool retVal = false;

            try
            {
                if (!Subscriptions.ContainsKey(item))
                {
                    Subscriptions.Add(item, new List <Action <object> >());
                }

                Subscriptions[item].Add(callback);

                retVal = true;
            }
            catch (Exception ex)
            {
                logger.Exception(ex);
            }

            return(retVal);
        }
Exemplo n.º 19
0
        /// <summary>
        ///     Creates a subscription to the specified Item.
        /// </summary>
        /// <remarks>
        ///     Upon the addition of the initial subscriber, an entry is added to the <see cref="Subscriptions"/> Dictionary keyed
        ///     with the specified Item and with a quantity of one. Successive subscriptions increment the quantity by one.
        /// </remarks>
        /// <param name="item">The <see cref="Item"/> to which the subscription should be added.</param>
        /// <threadsafety instance="true"/>
        /// <returns>An <see cref="Result"/> containing the result of the operation.</returns>
        public Result Subscribe(Item item)
        {
            logger.EnterMethod(xLogger.Params(item));
            logger.Info("Creating new Subscription to Item '" + item.FQN + "'...");

            Result retVal = new Result();

            try
            {
                // lock the Subscriptions collection
                lock (SubscriptionsLock)
                {
                    // always ensure the key exists before trying to reference it.
                    if (Subscriptions.ContainsKey(item))
                    {
                        // if it exists, increment the number of subscriptions
                        Subscriptions[item]++;
                    }
                    else
                    {
                        // if it doesn't yet exist, add it and set the number of subscriptions to 1.
                        Subscriptions.Add(item, 1);
                    }

                    retVal.AddInfo("The Item '" + item.FQN + "' now has " + Subscriptions[item] + " subscriber(s).");
                }
            }
            catch (Exception ex)
            {
                retVal.AddError("Error subscribing to Item '" + item.FQN + "': " + ex.Message);
            }

            retVal.LogResult(logger);
            logger.ExitMethod(retVal);
            return(retVal);
        }