Пример #1
0
        public void subscribing_two_handlers_results_in_both_callbacks()
        {
            var wasCalled1 = false;
            var wasCalled2 = false;

            using (var subscriptions = new Subscriptions())
            {
                subscriptions.Add <object>(_ => wasCalled1 = true);
                subscriptions.Add <object>(_ => wasCalled2 = true);
                EventBus <object> .Publish(new object());
            }

            Assert.IsTrue(wasCalled1);
            Assert.IsTrue(wasCalled2);
        }
Пример #2
0
        /// <summary>
        /// Loads the configuration from the specified reader.
        /// </summary>
        protected override void Load(TextReader reader)
        {
            XmlDocument xmlDoc = new();

            xmlDoc.Load(reader);
            XmlElement rootElem = xmlDoc.DocumentElement;

            if (rootElem.SelectSingleNode("DeviceOptions") is XmlNode deviceOptionsNode)
            {
                DeviceOptions.LoadFromXml(deviceOptionsNode);
            }

            if (rootElem.SelectSingleNode("Subscriptions") is XmlNode subscriptionsNode)
            {
                foreach (XmlElement subscriptionElem in subscriptionsNode.SelectNodes("Subscription"))
                {
                    SubscriptionConfig subscriptionConfig = new() { Parent = Subscriptions };
                    subscriptionConfig.LoadFromXml(subscriptionElem);
                    Subscriptions.Add(subscriptionConfig);
                }
            }

            if (rootElem.SelectSingleNode("Commands") is XmlNode commandsNode)
            {
                foreach (XmlElement commandElem in commandsNode.SelectNodes("Command"))
                {
                    CommandConfig commandConfig = new() { Parent = Commands };
                    commandConfig.LoadFromXml(commandElem);
                    Commands.Add(commandConfig);
                }
            }
        }
Пример #3
0
 public void AddSubscription(Subscription subscription)
 {
     if (!Subscriptions.ContainsKey(subscription.UserId))
     {
         Subscriptions.Add(subscription.UserId, subscription);
     }
 }
Пример #4
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);
        }
        public ConfigurationService(IEnvironment environment, IProcessStatic processStatic, IHttpRuntimeStatic httpRuntimeStatic, IConfigurationManagerStatic configurationManagerStatic, IDnsStatic dnsStatic)
        {
            _environment                = environment;
            _processStatic              = processStatic;
            _httpRuntimeStatic          = httpRuntimeStatic;
            _configurationManagerStatic = configurationManagerStatic;
            _dnsStatic = dnsStatic;

            Configuration = new InternalConfiguration(_environment, _localConfiguration, _serverConfiguration, _runTimeConfiguration, _securityPoliciesConfiguration, _processStatic, _httpRuntimeStatic, _configurationManagerStatic, dnsStatic);

            _subscriptions.Add <ConfigurationDeserializedEvent>(OnConfigurationDeserialized);
            _subscriptions.Add <ServerConfigurationUpdatedEvent>(OnServerConfigurationUpdated);
            _subscriptions.Add <AppNameUpdateEvent>(OnAppNameUpdate);
            _subscriptions.Add <GetCurrentConfigurationRequest, IConfiguration>(OnGetCurrentConfiguration);
            _subscriptions.Add <SecurityPoliciesConfigurationUpdatedEvent>(OnSecurityPoliciesUpdated);
        }
        public IJsonResponse <Unit> Submit([JsonRequestBody] SubscriptionSubmitModel model)
        {
            return((
                       from r in model.MaybeDefined()

                       from sb in
                       Subscriptions.All.FirstOrDefault(s => s.Email == model.Email) ??
                       Subscriptions.Add(new Subscription {
                Email = model.Email, Verified = false
            })
                       where sb.Verified == false
                       from setToken in sb.VerificationToken = Guid.NewGuid()

                                                               from commit in Maybe.Do(UnitOfWork.Commit)

                                                               from send in Maybe.Do(() => EmailService.SendEmail(new Email {
                ToEmail = model.Email,
                Subject = Sites.CurrentSiteFriendlyName + ": почтовая рассылка",
                Body = string.Format(_emailBody, Sites.CurrentSiteFriendlyName, new Uri(new Uri(Request.Url.AbsoluteUri), Url.Action(( SubscriptionController c ) => c.Verify(sb.VerificationToken.ToString()))))
            }))

                                                               select Unit.Default
                       )
                   .LogErrors(Log.Error)
                   .AsJsonResponse());
        }
Пример #7
0
        public void subscribing_two_handlers_and_unsubscribing_collection_results_in_no_callback()
        {
            var wasCalled1 = false;
            var wasCalled2 = false;

            using (var subscriptions = new Subscriptions())
            {
                subscriptions.Add <object>(_ => wasCalled1 = true);
                subscriptions.Add <object>(_ => wasCalled2 = true);
            }

            EventBus <object> .Publish(new object());

            Assert.IsFalse(wasCalled1);
            Assert.IsFalse(wasCalled2);
        }
Пример #8
0
        public ChannelContext(DbContextOptions <ChannelContext> options)
            : base(options)
        {
            Database.EnsureCreated();
            if (!Channels.Any())
            {
                Channels.Add(new Channel {
                    Name = "Great New Channel", UserId = 1, Date = DateTime.Now, Description = "Great and New"
                });
                Channels.Add(new Channel {
                    Name = "Not great Channel", UserId = 1, Date = DateTime.Now, Description = "not great at all"
                });

                SaveChanges();
            }

            if (!Subscriptions.Any())
            {
                Subscriptions.Add(new Subscription {
                    UserId = 2, ChannelId = 1
                });
                SaveChanges();
            }

            if (!ChannelImages.Any())
            {
                ChannelImages.Add(new ChannelImage {
                    ChannelId = 1, Description = "Hey guys, it's a great new channel", Date = DateTime.Now, ImageId = 1
                });
                SaveChanges();
            }
        }
Пример #9
0
        protected void InternalSubscribe <T>(Action <T> subscriber, ThreadOption threadOption)
        {
            EventSubscription <T> subscription;

            switch (threadOption)
            {
            case ThreadOption.PublisherThread:
                subscription = new EventSubscription <T>(subscriber);
                break;

            case ThreadOption.BackgroundThread:
                subscription = new BackgroundEventSubscription <T>(subscriber);
                break;

            case ThreadOption.UIThread:
                subscription = new DispatcherEventSubscription <T>(subscriber, SynchronizationContext);
                break;

            default:
                subscription = new EventSubscription <T>(subscriber);
                break;
            }

            lock (Subscriptions)
            {
                Prune();
                Subscriptions.Add(subscription);
            }
        }
Пример #10
0
        public ResponseResult <Guid> SubscribeToTraidingPair(TradingPair pair, Action <TradeSimple> callBack)
        {
            var subscription = _bitfinexSocketClient.SubscribeToTradeUpdates("t" + pair.Name.ToUpper(), (data) =>
            {
                var input = data.Select(d => new TradeSimple()
                {
                    Price  = d.Price,
                    Amount = d.Amount
                }).First();

                callBack?.Invoke(input);
            });

            if (!subscription.Success)
            {
                return(new ResponseResult <Guid>(subscription.Error.Message));
            }
            else
            {
                var id = Guid.NewGuid();
                Subscriptions.Add(id, subscription.Data);

                return(new ResponseResult <Guid>(id));
            }
        }
Пример #11
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));
     }
 }
Пример #12
0
        public void Ask_PartialExecutes_AginstUser1Bid_ButAskSharesIsGreaterThanBidShares()
        {
            // Arrange.
            var existingBidOrder = new Order {
                Id = 100, Shares = 100, Subscription = new Subscription {
                    Owned = 0, UserId = _userId1
                }
            };

            var existingLimit = Limits.First();

            existingLimit.BidHead        = existingBidOrder;
            existingBidOrder.ParentLimit = existingLimit;

            Limits.Add(existingLimit);
            Orders.Add(existingBidOrder.Id, existingBidOrder);

            Subscriptions.Add(existingBidOrder.Subscription.UserId, existingBidOrder.Subscription);
            var existingSellerSubscription = new Subscription {
                Owned = 500, UserId = _userId2
            };

            Subscriptions.Add(existingSellerSubscription.UserId, existingSellerSubscription);

            // Act.
            Ask(_userId2, 1, 200);

            // Assert.
            var existingBidOrder2 = new Order {
                Id = 100, Shares = 0, Subscription = new Subscription {
                    Owned = 100, UserId = _userId1
                }
            };

            var existingLimit2 = new Limit {
                Price = 1 * ScaleFactor, BidHead = existingBidOrder2
            };

            existingBidOrder2.ParentLimit = existingLimit2;

            var existingSellerSubscription2 = new Subscription {
                Owned = 400, UserId = _userId2
            };
            var remainingSellersOrder = new Order
            {
                Id           = 1,
                ParentLimit  = existingLimit2,
                Shares       = 100,
                Subscription = existingSellerSubscription2
            };

            existingLimit2.AskHead = remainingSellersOrder;

            Assert.AreEqual(1, Limits.Count);
            Assert.AreEqual(2, Orders.Count);
            Assert.AreEqual(2, Subscriptions.Count);
            CollectionAssert.AreEqual(new Limit[] { existingLimit2 }, Limits, _limitTestComparer);
            CollectionAssert.AreEqual(new Order[] { existingBidOrder2, remainingSellersOrder }, (ICollection)Orders.Values, _orderTestComparer);
            CollectionAssert.AreEqual(new Subscription[] { existingBidOrder2.Subscription, existingSellerSubscription2 }, (ICollection)Subscriptions.Values, _subscriptionTestComparer);
        }
Пример #13
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);
        }
Пример #14
0
        public void Ask_Adds1Order_OnExistingLimit_With1Order()
        {
            // Arrange.
            var existingOrder = new Order {
                Shares = 100, Subscription = new Subscription {
                    Owned = 100, UserId = _userId2
                }
            };

            var existingLimit = Limits.First();

            existingLimit.AskHead     = existingOrder;
            existingOrder.ParentLimit = existingLimit;

            Limits.Add(existingLimit);
            Orders.Add(existingOrder.Id, existingOrder);
            Subscriptions.Add(existingOrder.Subscription.UserId, existingOrder.Subscription);
            Subscriptions.Add(_userId1, new Subscription {
                Owned = 5, UserId = _userId1
            });

            // Act.
            Ask(_userId1, 1, 5);

            // Assert.
            var existingOrder2 = new Order {
                Shares = 100, Subscription = new Subscription {
                    Owned = 100, UserId = _userId2
                }
            };

            var existingLimit2 = new Limit {
                Price = 1 * ScaleFactor
            };

            existingOrder2.ParentLimit = existingLimit2;

            var order = new Order
            {
                Id           = 1,
                Next         = existingOrder2,
                Shares       = 5,
                Subscription = new Subscription
                {
                    Owned  = 5,
                    UserId = _userId1
                }
            };

            existingLimit2.AskHead = order;
            existingOrder2.Prev    = order;
            order.ParentLimit      = existingLimit2;

            Assert.AreEqual(1, Limits.Count);
            Assert.AreEqual(2, Orders.Count);
            Assert.AreEqual(2, Subscriptions.Count);
            CollectionAssert.AreEqual(new Limit[] { existingLimit2 }, Limits, _limitTestComparer);
            CollectionAssert.AreEqual(new Order[] { existingOrder2, order }, (ICollection)Orders.Values, _orderTestComparer);
            CollectionAssert.AreEqual(new Subscription[] { existingOrder2.Subscription, order.Subscription }, (ICollection)Subscriptions.Values, _subscriptionTestComparer);
        }
Пример #15
0
        public override Task Initialize()
        {
            // Complete any initialization operations here
            Subscriptions.Add("TSLA");

            return(Task.CompletedTask);
        }
Пример #16
0
        public void Cancel_Removes1OrderFromExistingLimitThatContains2OrdersAndRemovesFromOrders_WhenOrderIsAskType()
        {
            // Arrange.
            AssertConstructor();

            Subscriptions.Add(_userId1, new Subscription {
                Owned = 5, UserId = _userId1
            });
            Subscriptions.Add(_userId2, new Subscription {
                Owned = 10, UserId = _userId2
            });
            Subscriptions.Add(_userId3, new Subscription {
                Owned = 15, UserId = _userId3
            });
            Ask(_userId1, 1, 5);
            var newOrder = Ask(_userId2, 1, 10);

            Ask(_userId3, 1, 15);

            // Make sure the above actually worked.
            Assert.AreEqual(1, Limits.Count);
            Assert.AreEqual(3, Orders.Count);
            Assert.AreEqual(3, Subscriptions.Count);

            // Act.
            Cancel(newOrder.Id);

            Assert.AreEqual(1, Limits.Count);
            Assert.AreEqual(2, Orders.Count);
            Assert.AreEqual(3, Subscriptions.Count);
        }
Пример #17
0
        /// <summary>
        /// Subscribe to the given publishing endpoint.
        /// </summary>
        /// <param name="publishName">The name of the publishing endpoint.</param>
        /// <param name="arguments">Arguments to the publish function.</param>
        /// <typeparam name="RecordType">The type of the record in the collection.</typeparam>
        public Subscription Subscribe(string publishName, params object[] arguments)
        {
            string requestId = string.Format("{0}-{1}", publishName, this.NextId());

            // Setup backing store.
            if (Subscriptions.Contains(requestId))
            {
                return(Subscriptions [requestId]);
            }
            else
            {
                Subscriptions.Add(new Subscription()
                {
                    name = requestId
                });
            }

            Send(new SubscribeMessage()
            {
                name   = publishName,
                Params = arguments,
                id     = requestId
            });

            return(Subscriptions [requestId]);
        }
Пример #18
0
        public void AddSubscription(ISubscription subscription)
        {
            if (subscription == null)
            {
                throw new ArgumentNullException("subscription");
            }

            try
            {
                SubscriptionLock.EnterWriteLock();

                MarkUsed();

                Subscriptions.Add(subscription);

                // Created -> HasSubscriptions
                Interlocked.CompareExchange(ref State,
                                            TopicState.HasSubscriptions,
                                            TopicState.NoSubscriptions);
            }
            finally
            {
                SubscriptionLock.ExitWriteLock();
            }
        }
Пример #19
0
 public void AddSubscription(Subscription subscription)
 {
     if (Subscriptions == null)
     {
         Subscriptions = new List <Subscription>();
     }
     Subscriptions.Add(subscription);
 }
Пример #20
0
 public void AddSubscription(string message)
 {
     if (null == Subscriptions)
     {
         Subscriptions = new List <string>();
     }
     Subscriptions.Add(message);
 }
Пример #21
0
 public void subscribing_null_callback_does_not_crash()
 {
     using (var subscriptions = new Subscriptions())
     {
         subscriptions.Add <object>(null);
         EventBus <object> .Publish(new object());
     }
 }
Пример #22
0
 public virtual IEnumerable <UserSubscription> GetUserSubscriptions(string userId)
 {
     if (!Subscriptions.TryGetValue(userId, out var subscriptions))
     {
         Subscriptions.Add(userId, subscriptions = new List <UserSubscription>());
     }
     return(subscriptions);
 }
Пример #23
0
 private void MonitorEntityChanges()
 {
     Subscriptions.Add(NotifyingCollection.EntityAdded.Subscribe(OnEntityAddedToCollection));
     Subscriptions.Add(NotifyingCollection.EntityRemoved.Subscribe(OnEntityRemovedFromCollection));
     Subscriptions.Add(NotifyingCollection.EntityComponentsAdded.Subscribe(OnEntityComponentAdded));
     Subscriptions.Add(NotifyingCollection.EntityComponentsRemoving.Subscribe(OnEntityComponentRemoving));
     Subscriptions.Add(NotifyingCollection.EntityComponentsRemoved.Subscribe(OnEntityComponentRemoved));
 }
 public void Subscribe(User user)
 {
     if (Subscriptions.FirstOrDefault(x => x.Subscripter == user) == null)
     {
         Subscriptions.Add(new UserUser {
             Subscriber = this, Subscripter = user
         });
     }
 }
Пример #25
0
        void IDataStore.Save(Subscription sub)
        {
            if (!Subscriptions.Any(s => s.Id == sub.Id))
            {
                Subscriptions.Add(sub);
            }

            SaveChanges();
        }
Пример #26
0
 public void CreateSubscription(Subscription subscription)
 {
     if (IsPremium)
     {
         AddNotification(new Notification("Premium", "O aluno já tem uma assinatura ativa"));
         return;
     }
     Subscriptions.Add(new Subscription());
 }
Пример #27
0
        /// <summary>
        /// Initialize a set of <see cref="IEventAnnouncer"/> types this system will subscribe to for future events.
        /// </summary>
        /// <param name="systems">The types of <see cref="IEventAnnouncer"/> this system will subscribe to.</param>
        public void Subscribe(params Type[] systems)
        {
            Subscriptions.Clear();

            for (int i = 0; i < systems.Length; i++)
            {
                Subscriptions.Add(systems[i]);
            }
        }
Пример #28
0
        public void Subscribe(PvPBattle battle)
        {
            if (battle == null || battle.Deleted || battle.State == PvPBattleState.Internal || IsSubscribed(battle))
            {
                return;
            }

            Subscriptions.Add(battle);
        }
        public void Add(string subscription)
        {
            if (Subscriptions == null)
            {
                Subscriptions = new List <string>();
            }

            Subscriptions.Add(subscription);
        }
Пример #30
0
        public void AddSubscriptions(params ServiceBusSubscription[] subscriptions)
        {
            Subscriptions ??= new ObservableCollection <ServiceBusSubscription>();

            foreach (var subscription in subscriptions)
            {
                subscription.Topic = this;
                Subscriptions.Add(subscription);
            }
        }