Example #1
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();
            }
        }
        public bool Match(IPublication publication, ISubscription subscription, EventArgs e)
        {
            var publisher = publication.Publisher as IVhptIdentificationProvider;
            var subscriber = subscription.Subscriber as IVhptIdentificationProvider;

            return publisher != null && subscriber != null && publisher.Identification.Equals(subscriber.Identification);
        }
Example #3
0
 public void Initialize(IModelContext model)
 {
     _clientUnit = model.Clients.HandleRemoveChanges(removed: client =>
     {
         if (_clients.ContainsKey(client))
         {
             _clients[client].StopListen();
             _clients.Remove(client);
         }
     });
     _interlocutorUnit = model.Interlocutors.HandleRemoveChanges(removed: interlocutor =>
     {
         if (_interlocutors.ContainsKey(interlocutor))
         {
             _interlocutors[interlocutor].StopListen();
             _interlocutors.Remove(interlocutor);
         }
     });
     _roomUnit = model.Rooms.HandleRemoveChanges(removed: room =>
     {
         if (_rooms.ContainsKey(room))
         {
             _rooms[room].StopListen();
             _rooms.Remove(room);
         }
     });
 }
 public LatestProfile( IListenedShow latestShow, IShow show, UserProfile profile, ISubscription subscription )
 {
     LatestListenedShow = latestShow;
     LatestShow = show;
     Profile = profile;
     Subscription = subscription;
 }
		public virtual IRequestResult Accept(ISubscription subscription, IMessage message) {
			var bundle = new ProcessableUnit { Subscription = subscription, Message = message };
            Accepting(bundle);
            //RealizeIdentifier(subscription);
            BundlePrototype.IsNull(() => BundlePrototype = subscription);
			return Result();
		}
        public void CreateSubscription()
        {
            var phoneNumber = "44556677";
            var subscriptionRegistration = ObjectFactory.GetInstance<ISubscriptionRegistration>();
            var customerRegistration = ObjectFactory.GetInstance<ICustomerRegistration>();

            subscription = SubscriptionHelper.CreateSubscriptionWithDefaultCustomer(subscriptionRegistration,customerRegistration, phoneNumber, "DK", CustomerStatus.Normal);
        }
 public void SaveCommit( ISubscription subscription, out bool success )
 {
     using ( IUnitOfWork u = UnitOfWork.Begin() ) {
         Save( subscription, out success );
         if ( success )
             u.Commit();
     }
 }
Example #8
0
 public static PlanSubscription MapSubscriptionToPlanSubscription(ISubscription subscription, Func<string, Plan> lookupPlanById)
 {
     return new PlanSubscription
                {
                    Id = subscription.SubscriptionID,
                    Plan = lookupPlanById(subscription.Product.Handle),
                    Subscriber = MapCustomerToSubscriber(subscription.Customer) // in actual system probably look up db
                };
 }
        public void Delete( ISubscription subscription )
        {
            Checks.Argument.IsNotNull( subscription, "subscription" );

            using ( IUnitOfWork u = UnitOfWork.Begin() ) {
                _repo.Remove( subscription );
                u.Commit();
            }
        }
Example #10
0
        public void MakeProxy(string EndpoindAddress, object callbackinstance)
        {
            NetTcpBinding netTcpbinding = new NetTcpBinding(SecurityMode.None);
            EndpointAddress endpointAddress = new EndpointAddress(EndpoindAddress);
            InstanceContext context = new InstanceContext(callbackinstance);        

            DuplexChannelFactory<ISubscription> channelFactory = new DuplexChannelFactory<ISubscription>(new InstanceContext(this), netTcpbinding, endpointAddress);
            _proxy  = channelFactory.CreateChannel();
        }
        public LiveFeedsHub()
        {
            var eventActivity = new EventActivity(
                new ActivitySettings(ActivityDrilldown.Second));

            subscription = eventActivity.CreateSubscription(
                "order:placed",
                OnDataReceive);
        }
Example #12
0
        public void Start()
        {
            publisher = bus.CreatePublisher<ProcessingJobUpdatedMessage>();

            subscriber = bus.Subscribe<MoveToNextWorkflowStateMessage>(m =>
            {
                Console.WriteLine("[Processor] Processing {0}", m.JobId);
                ProcessJob(m.JobId);
            });
        }
        public async Task SaveSubscription(ISubscription subscription)
        {
            Debug.Assert(_count != DEFAULT_COUNT_VALUE, "Count field is not inited, LoadSubscriptions() wasn't called before SaveSubscription()");

            var serializable = new SubscriptionDto {Uri = subscription.Uri};
            var key = string.Format(CACHE_KEY_FMT, _count);
            this.Log().Info("Inserting subscription to {0} into cache", serializable.Uri);
            await Cache.Local.InsertObject(key, serializable.Uri.OriginalString);
            _count++;
        }
        private void SetupSubscription()
        {
            _subscription.SafeDispose();
            if (_source == null)
                return;

            _subscription = _source.Subscribe();
            if (_subscription.Start(() => DispatcherConsumer.Global.RunOnRefresh(UpdateSubscription), null))
                UpdateSubscription();
        }
Example #15
0
 public bool Add(ISubscription subscription)
 {
     var wasAdded = false;
     foreach (var resolver in resolvers)
     {
         wasAdded = resolver.Add(subscription);
         if (wasAdded) break;
     }
     return wasAdded;
 }
Example #16
0
 public void StartListen()
 {
     _interlocutorUnit = ModelContext.Interlocutors.HandleRemoveChanges(removed: interlocutor =>
     {
         if (!_sessions.ContainsKey(interlocutor)) return;
         var target = _sessions[interlocutor];
         MessageFeed.Unsubscribe(target);
         _sessions.Remove(interlocutor);
     });
 }
        /// <summary>
        /// Returns whether the publication and subscription match and the event published by the
        /// publisher will be relayed to the subscriber.
        /// <para>
        /// This is the case if the name of the subscriber is a prefix to the name of the publisher.
        /// </para>
        /// </summary>
        /// <param name="publication">The publication.</param>
        /// <param name="subscription">The subscription.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        /// <returns><code>true</code> if event has to be sent to the subscriber.</returns>
        public bool Match(IPublication publication, ISubscription subscription, EventArgs e)
        {
            object publisher = publication.Publisher;
            object subscriber = subscription.Subscriber;

            string publisherName = publisher is INamedItem ? ((INamedItem)publisher).EventBrokerItemName : string.Empty;
            string subscriberName = subscriber is INamedItem ? ((INamedItem)subscriber).EventBrokerItemName : string.Empty;

            return publisherName.StartsWith(subscriberName);
        }
Example #18
0
 public void StartListen()
 {
     _roomUnit = _presenter.RoomSource.HandleAddRemoveChanges(
                              added: room => RegisterResource(new RoomResourceViewModel(room)),
                              removed: room => UnRegisterResource(_registeredResources.FirstOrDefault(resource => resource.Model == room)));
     _contactUnit = _presenter.InterlocutorSource.HandleAddRemoveChanges(
                                 added: interlocutor => RegisterResource(new InterlocutorResourceViewModel(interlocutor)),
                                 removed: interlocutor => UnRegisterResource(_registeredResources.FirstOrDefault(resource => resource.Model == interlocutor)));
     _triggerUnit = _trigger.Subscribe(unit => Update());
 }
Example #19
0
        public void Start()
        {
            priceSubscription = bus.Subscribe<PriceMessage>(OnPrice, ConfigurePriceSubscription);

            var binding = priceSubscription.Queues.Single();

            bus.Publish(new ConnectMessage(
                id,
                binding.Name,
                new[] { "GOOG" }));
        }
        /// <summary>
        /// Returns whether the publication and subscription match and the event published by the
        /// publisher will be relayed to the subscriber.
        /// <para>
        /// This is the case if the name of the subscriber is a prefix to the name of the publisher.
        /// </para>
        /// </summary>
        /// <param name="publication">The publication.</param>
        /// <param name="subscription">The subscription.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        /// <returns><code>true</code> if event has to be sent to the subscriber.</returns>
        public bool Match(IPublication publication, ISubscription subscription, EventArgs e)
        {
            Ensure.ArgumentNotNull(publication, "publication");
            Ensure.ArgumentNotNull(subscription, "subscription");

            object publisher = publication.Publisher;
            object subscriber = subscription.Subscriber;

            string publisherName = publisher is INamedItem ? ((INamedItem)publisher).EventBrokerItemName : string.Empty;
            string subscriberName = subscriber is INamedItem ? ((INamedItem)subscriber).EventBrokerItemName : string.Empty;

            return publisherName.StartsWith(subscriberName, StringComparison.Ordinal);
        }
 public SubscriptionDetails(ISubscription s )
 {
     Id = s.Id;
     Label = s.Label;
     Created = s.Created;
     IsActive = s.IsActive;
     CurrentStoreCount = s.StoreCount;
     StoreLimit = s.StoreCountLimit;
     StoreSizeLimit = s.StoreSizeLimit;
     TotalSizeLimit = s.TotalSizeLimit;
     IsTrial = s.IsTrial;
     Stores = s.Stores.Select(store => new StoreDetail(store)).ToList();
 }
        public EventActivityHub(
            ISubscription<EventActivitySubscriptionInfo> subscription,
            Func<Task<IEnumerable<string>>> getEventNames,
            Func<string, Task<IEnumerable<ActivityTimeframe>>> getTimeframes)
            : base(getEventNames, getTimeframes)
        {
            if (subscription == null)
            {
                throw new ArgumentNullException("subscription");
            }

            this.subscription = subscription;
        }
 public WhiteListForecastWorker(
     ISubscription[] subscriptions,
     IDeployment deployment,
     IOperation operation,
     WhiteListService[] allowedServices,
     int pollingIntervalInMinutes)
     : base(GetWorkerId(typeof(WhiteListForecastWorker).FullName))
 {
     this.subscriptions = subscriptions;
     this.deployment = deployment;
     this.operation = operation;
     this.allowedServices = allowedServices;
     this.pollingIntervalInMinutes = pollingIntervalInMinutes;
 }
Example #24
0
        public void SetOwner(ICharacter owningCharacter)
        {
            this.ResetOwner();
            if (owningCharacter == null)
            {
                return;
            }

            this.Owner = owningCharacter;
            this.Owner.Deleting += this.OnOwnerDeleting;
            this.commandRequestSubscription = this.notificationCenter.Subscribe<CommandRequestMessage>(
                (message, subscription) => this.ProcessCommandForCharacter(message.Content, message.Arguments),
                message => message.Sender == this.Owner);
        }
        /// <summary>
        /// Instances a new PlayerConnectionState.
        /// </summary>
        /// <param name="player">An instance of a Player type that will be performing network communication</param>
        /// <param name="currentSocket">The Socket used to communicate with the client.</param>
        /// <param name="bufferSize">The storage size of the data buffer</param>
        public PlayerConnectionState(IPlayer player, Socket currentSocket, int bufferSize)
        {
            this.Player = player;
            this.notificationManager = player.NotificationCenter;
            this.systemMessageSubscription = this.notificationManager.Subscribe<InformationMessage>(
                callback: (msg, sub) => this.SendMessage(msg.Content),
                condition: msg => !string.IsNullOrEmpty(msg.Content) && msg.Target == this.Player);
            this.Player.Deleted += this.PlayerDeleted;

            this.CurrentSocket = currentSocket;
            this.bufferSize = bufferSize;
            this.Buffer = new byte[bufferSize];

            this.outgoingMessageQueue.CollectionChanged += MessageAddedToOutboundQueue;
        }
        public void Save( ISubscription subscription, out bool success )
        {
            Checks.Argument.IsNotNull( subscription, "subscription" );

            success = false;

            if ( null == _repo.FindById( subscription.Id ) ) {
                try {
                    _repo.Add( subscription );
                    success = true;
                }
                catch ( Exception ex ) {
                    success = false;
                }
            }
        }
        private void ScheduleWork(ISubscription subscription)
        {
            var workContext = new WorkContext(subscription, this);

            ThreadPool.QueueUserWorkItem(state =>
            {
                var context = (WorkContext)state;

                context.Broker._counters.MessageBusAllocatedWorkers.Increment();

                DoWork(context);

                context.Broker._counters.MessageBusAllocatedWorkers.Decrement();
            },
            workContext);
        }
Example #28
0
        public void RemoveSubscription(ISubscription subscription)
        {
            try
            {
                SubscriptionLock.EnterWriteLock();

                if (_subcriptionIdentities.Remove(subscription.Identity))
                {
                    Subscriptions.Remove(subscription);
                }
            }
            finally
            {
                SubscriptionLock.ExitWriteLock();
            }
        }
Example #29
0
 public static PlanSubscription MapSubscription(ISubscription chargifySubscription)
 {
     return new PlanSubscription
                {
                    ChargifySubscriptionID = chargifySubscription.SubscriptionID,
                    Plan = MapProductToPlan(chargifySubscription.Product),
                    Account = MapCustomerToAccount(chargifySubscription.Customer),
                    ActivatedAt = chargifySubscription.ActivatedAt.ToUniversalTime(),
                    NextAssessmentAt = chargifySubscription.NextAssessmentAt.ToUniversalTime(),
                    CurrentPeriodStartedAt = chargifySubscription.CurrentPeriodStartedAt.ToUniversalTime(),
                    CurrentPeriodEndsAt = chargifySubscription.CurrentPeriodEndsAt.ToUniversalTime(),
                    ExpiresAt = chargifySubscription.ExpiresAt.ToUniversalTime(),
                    TrialStartedAt = chargifySubscription.TrialStartedAt.ToUniversalTime(),
                    TrialEndedAt = chargifySubscription.TrialEndedAt.ToUniversalTime(),
                    State = MapChargifySubscriptionState(chargifySubscription.State.ToString())
                };
 }
Example #30
0
        public override void Initialize()
        {
            base.Initialize();

            this.DrawOrder = 100;

            this.spriteBatch = new SpriteBatch(this.Game.GraphicsDevice);
            this.CurrentScore = 0;

            this.ScoreFont = this.Game.Content.Load<SpriteFont>("ScoreFont");

            // Subscribe to brick destroyed events
            IEventAggregator eventAggregator = this.Game.Services.GetService<IEventAggregator>();
            if (eventAggregator != null)
            {
                brickDestroyedSubscription = eventAggregator.Subscribe<BrickDestroyedEvent>(OnBrickDestroyed);
            }
        }
Example #31
0
 /// <summary>
 /// Called before an event is relayed from the publication to the subscribers.
 /// </summary>
 /// <param name="eventTopic">The event topic.</param>
 /// <param name="publication">The publication.</param>
 /// <param name="subscription">The subscription.</param>
 /// <param name="handler">The handler.</param>
 /// <param name="sender">The sender.</param>
 /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
 public override void RelayingEvent(IEventTopicInfo eventTopic, IPublication publication, ISubscription subscription, IHandler handler, object sender, EventArgs e)
 {
     this.log.DebugFormat(
         CultureInfo.InvariantCulture,
         "Relaying event '{6}' from publisher '{0}' [{1}] to subscriber '{2}' [{3}] with EventArgs '{4}' with handler '{5}'.",
         publication.Publisher,
         publication.Publisher is INamedItem ? ((INamedItem)publication.Publisher).EventBrokerItemName : string.Empty,
         subscription.Subscriber,
         subscription.Subscriber is INamedItem ? ((INamedItem)subscription.Subscriber).EventBrokerItemName : string.Empty,
         e,
         handler,
         eventTopic.Uri);
 }
Example #32
0
 public void OnSubscribe(ISubscription subscription) => _probe.Ref.Tell(new OnSubscribe(subscription));
Example #33
0
 public SubscriptionWrapper(ISubscription wrapped)
 {
     _wrapped    = wrapped;
     ChunkFilter = c => true;
 }
Example #34
0
 public SubscriptionWrapper(ISubscription wrapped)
 {
     _wrapped = wrapped;
 }
Example #35
0
 public DisposableSubscription(ISubscription action)
 {
     this.action = action;
 }
Example #36
0
 protected override ISubscription ConfigureConsumer(ISubscription consumer, CancellationToken token)
 {
     return(new TplSubscription(consumer, token));
 }
Example #37
0
 public State(ISubscription subscription, long requested, bool isCanceled)
 {
     Subscription = subscription;
     Requested    = requested;
     IsCanceled   = isCanceled;
 }
Example #38
0
 public InitiateInputWorkflow(IInitiateInputDialog dialog,
                              ISubscription subscription)
     :
     base(dialog, subscription)
 {
 }
Example #39
0
 private void raiseDispose()
 {
     IsDisposed = true;
     action     = null;
     Disposed.Raise(this);
 }
Example #40
0
 /// <summary>
 /// Expects and returns <see cref="ISubscription"/>.
 /// </summary>
 public ISubscription ExpectSubscription()
 {
     _subscription = _probe.ExpectMsg <OnSubscribe>().Subscription;
     return(_subscription);
 }
Example #41
0
 /// <summary>
 /// TBD
 /// </summary>
 /// <param name="subscription">TBD</param>
 public void OnSubscribe(ISubscription subscription) => _subscriber.OnSubscribe(subscription);
Example #42
0
 /// <summary>
 /// Called after a subscription was created.
 /// </summary>
 /// <param name="eventTopic">The event topic.</param>
 /// <param name="subscription">The subscription.</param>
 public override void CreatedSubscription(IEventTopicInfo eventTopic, ISubscription subscription)
 {
 }
 public void OnSubscribe(ISubscription s)
 {
     parent.arbiter.Set(s);
 }
Example #44
0
 public Task ReadAllByOperationIdAsync(string operationId, ISubscription subscription, CancellationToken cancellationToken)
 {
     return(_persistence.ReadAllByOperationIdAsync(operationId, subscription, cancellationToken));
 }
Example #45
0
 /// <inheritdoc />
 public void Handle(EventBase @event, Exception exception, ISubscription subscription)
 {
     this.logger.LogError(exception, "Error handling the event {0}", @event.GetType().Name);
     throw exception;
 }
Example #46
0
        public Read_Result Read_Classic(string OPCURL, string UpdateInterval, string ItemIds)
        {
            try
            {
                Read_Result Read_Result = new Read_Result(); RegisteredTag NewRegisteredTag;
                if (ItemIds.IsNullOrWhiteSpace())
                {
                    return(Read_Result);
                }
                Opc.Da.Server ConnectedOPDAServer = ConnectToOPCServer(OPCURL);
                if (ConnectedOPDAServer == null)
                {
                    return new Read_Result()
                           {
                               success = false, result = null, error = "Fail to Connect to OPC Server '" + OPCURL + "'"
                           }
                }
                ;
                string[] ItemIdsSplit = ItemIds.Split(',');
                int      LastIndex    = ItemIdsSplit.Count() - 1;
                if (ItemIdsSplit[LastIndex].IsNullOrEmpty())
                {
                    ItemIdsSplit = ItemIdsSplit.RemoveAt(LastIndex);
                }
                if (ItemIdsSplit.Count() > 0)
                {
                    int UpdateIntervalInMS = UpdateInterval.ToInt(1000);
                    if (UpdateIntervalInMS < 250)
                    {
                        UpdateIntervalInMS = 250;
                    }
                    foreach (string ItemId in ItemIdsSplit)
                    {
                        //if (ItemId.IsNullOrWhiteSpace()) continue;
                        //Check if the Item has already been subscribed
                        if (this.RegisteredTags.TryGetValue(ItemId, out RegisteredTag FoundRegisteredTag))
                        {
                            //Straight forward case, simply obtain data
                            if (UpdateIntervalInMS >= FoundRegisteredTag.UpdateIntervalInMS)
                            {
                                FoundRegisteredTag.LastCalled = DateTime.Now;
                                Read_Result.result.Add(new DataValue(FoundRegisteredTag.Id, true, FoundRegisteredTag.TSUTC, FoundRegisteredTag.SourceTSUTC, FoundRegisteredTag.Value, FoundRegisteredTag.QualityOK));
                                continue;
                            }

                            //If the Update Interval is more Frequent we need to remove the tag and subscribe it to a group which has higher update rate
                            else
                            {
                                FoundRegisteredTag.UpdateIntervalInMS = UpdateIntervalInMS;
                                Subscription SubscriptionWhereTagIs = ConnectedOPDAServer.Subscriptions.FindSubcriptionThatHasItem(ItemId, out Item ItemFound);
                                if (SubscriptionWhereTagIs != null)
                                {
                                    SubscriptionWhereTagIs.RemoveItems(new ItemIdentifier[] { ItemFound });                                 //Remove From Subscription
                                }
                            }
                        }


                        //Tag WAS not found in Registered Tags Dictionary (or was removed due to update interval changed)
                        //Check if there are any subscriptions which have same Update Interval and has room for items
                        NewRegisteredTag = new RegisteredTag(ItemId, UpdateIntervalInMS);
                        ItemValueResult readResult;
                        Subscription    SuitableSubscription = ConnectedOPDAServer.Subscriptions.FindSubcription(S => S.State.UpdateRate == UpdateIntervalInMS && S.Items.Count() < this.OPCGroupSizeLimit);
                        if (SuitableSubscription != null)
                        {
                            //if a suitable subscription was found, Add item to this subscription
                            ItemResult[] IR = SuitableSubscription.AddItems(new Item[] { new Item()
                                                                                         {
                                                                                             ItemName = ItemId
                                                                                         } });
                            if (IR.Count() <= 0)
                            {
                                Read_Result.result.Add(new DataValue(ItemId, false, DateTime.UtcNow, DateTime.MinValue, "Failed to Add Item to OPC Group", false)); continue;
                            }
                            if (IR[0].ResultID == ResultID.S_OK)
                            {
                                readResult = SuitableSubscription.Read(new Item[] { IR[0] })[0];
                            }
                            else
                            {
                                Read_Result.result.Add(new DataValue(ItemId, false, DateTime.UtcNow, DateTime.MinValue, IR[0].ResultID.ToString(), false)); continue;
                            }
                        }
                        else
                        {
                            //If no Subscriptions found, create new Subscription
                            ISubscription NewSubscription = ConnectedOPDAServer.CreateSubscription(new SubscriptionState()
                            {
                                UpdateRate = UpdateIntervalInMS
                            });
                            NewSubscription.DataChanged -= new DataChangedEventHandler(this.OnOPCSubscriptionDataChanged);
                            NewSubscription.DataChanged += new DataChangedEventHandler(this.OnOPCSubscriptionDataChanged);
                            ItemResult[] IR = NewSubscription.AddItems(new Item[] { new Item()
                                                                                    {
                                                                                        ItemName = ItemId
                                                                                    } });
                            if (IR.Count() <= 0)
                            {
                                Read_Result.result.Add(new DataValue(ItemId, false, DateTime.UtcNow, DateTime.MinValue, "Failed to Add Item to new OPC Group", false)); continue;
                            }
                            if (IR[0].ResultID == ResultID.S_OK)
                            {
                                readResult = NewSubscription.Read(new Item[] { IR[0] })[0];
                            }
                            else
                            {
                                Read_Result.result.Add(new DataValue(ItemId, false, DateTime.UtcNow, DateTime.MinValue, IR[0].ResultID.ToString(), false)); continue;
                            }
                        }

                        NewRegisteredTag.TSUTC = DateTime.UtcNow;
                        if (readResult.TimestampSpecified)
                        {
                            NewRegisteredTag.SourceTSUTC = readResult.Timestamp;
                        }
                        else
                        {
                            NewRegisteredTag.SourceTSUTC = DateTime.UtcNow;
                        }
                        if (readResult.Quality == Quality.Good)
                        {
                            NewRegisteredTag.QualityOK = true;
                            if (readResult.Value is string || readResult.Value.IsNumericType())
                            {
                                NewRegisteredTag.Value = (IComparable)readResult.Value;
                            }
                            else
                            {
                                if (readResult.Value is System.Collections.IEnumerable array)
                                {
                                    string res = "";
                                    foreach (var item in array)
                                    {
                                        res = res + item.ToString() + ",";
                                    }
                                    if (res != "")
                                    {
                                        res.RemoveLastCharacter();
                                    }
                                    NewRegisteredTag.Value = res;
                                }
                                else
                                {
                                    NewRegisteredTag.Value = readResult.Value.GetType().ToString();
                                }
                            }
                        }
                        else
                        {
                            NewRegisteredTag.QualityOK = false;
                            NewRegisteredTag.Value     = null;
                        }
                        Read_Result.result.Add(new DataValue(NewRegisteredTag.Id, true, NewRegisteredTag.TSUTC, NewRegisteredTag.SourceTSUTC, NewRegisteredTag.Value, NewRegisteredTag.QualityOK));


                        //Add New Tag to the Registered Tags
                        NewRegisteredTag.LastCalled = DateTime.Now;
                        RegisteredTags.Add(ItemId, NewRegisteredTag);
                    }
                }
                return(Read_Result);
            }
            catch (Exception ex)
            {
                return(new Read_Result()
                {
                    success = false, error = ex.ToString()
                });
            }
        }
Example #47
0
 public void OnSubscribe(ISubscription subscription)
 {
     ArbiterSet(subscription);
 }
Example #48
0
 public void Update(ISubscription subscription)
 {
     subscriptionDAL.Update(subscription);
 }
 internal Unsubscriber(Subscriptions subscriptions, ISubscription subscription)
 {
     _subscriptions = subscriptions;
     _subscription  = subscription;
 }
Example #50
0
 public override void ResetValue(ISubscription subscription)
 {
 }
        public void OnSubscribe(ISubscription s)
        {
            actual.OnSubscribe(s);

            s.Request(long.MaxValue);
        }
Example #52
0
        public void TestAsyncPendingSubscriptionBatchSizeExactlyOne()
        {
            int total         = 10;
            int receivedCount = 0;

            AutoResetEvent   evSubDone = new AutoResetEvent(false);
            ManualResetEvent evStart   = new ManualResetEvent(false);

            byte[] data = Encoding.UTF8.GetBytes("0123456789");

            using (NATSServer.CreateFastAndVerify(Context.Server1.Port))
            {
                var opts = Context.GetTestOptions(Context.Server1.Port);
                opts.SubscriptionBatchSize = 1;

                using (IConnection c = Context.ConnectionFactory.CreateConnection(opts))
                {
                    ISubscription s = c.SubscribeAsync("foo", (sender, args) =>
                    {
                        evStart.WaitOne(60000);

                        receivedCount++;
                        if (receivedCount == total)
                        {
                            evSubDone.Set();
                        }
                    });

                    for (int i = 0; i < total; i++)
                    {
                        c.Publish("foo", data);
                    }
                    c.Flush();

                    Thread.Sleep(1000);

                    int expectedPendingCount = total - 1;

                    // Exactly 1 message will be dequeued
                    Assert.True(s.QueuedMessageCount == expectedPendingCount);

                    Assert.True((s.MaxPendingBytes == (data.Length * total)) ||
                                (s.MaxPendingBytes == (data.Length * expectedPendingCount)));
                    Assert.True((s.MaxPendingMessages == total) ||
                                (s.MaxPendingMessages == expectedPendingCount));
                    Assert.True((s.PendingBytes == (data.Length * total)) ||
                                (s.PendingBytes == (data.Length * expectedPendingCount)));

                    long pendingBytes;
                    long pendingMsgs;

                    s.GetPending(out pendingBytes, out pendingMsgs);
                    Assert.True(pendingBytes == s.PendingBytes);
                    Assert.True(pendingMsgs == s.PendingMessages);

                    long maxPendingBytes;
                    long maxPendingMsgs;
                    s.GetMaxPending(out maxPendingBytes, out maxPendingMsgs);
                    Assert.True(maxPendingBytes == s.MaxPendingBytes);
                    Assert.True(maxPendingMsgs == s.MaxPendingMessages);


                    Assert.True((s.PendingMessages == total) ||
                                (s.PendingMessages == expectedPendingCount));

                    Assert.True(s.Delivered == 1);
                    Assert.True(s.Dropped == 0);

                    evStart.Set();
                    evSubDone.WaitOne(10000);

                    Assert.True(s.QueuedMessageCount == 0);

                    Assert.True((s.MaxPendingBytes == (data.Length * total)) ||
                                (s.MaxPendingBytes == (data.Length * expectedPendingCount)));
                    Assert.True((s.MaxPendingMessages == total) ||
                                (s.MaxPendingMessages == expectedPendingCount));

                    Assert.True(s.PendingMessages == 0);
                    Assert.True(s.PendingBytes == 0);

                    Assert.True(s.Delivered == total);
                    Assert.True(s.Dropped == 0);

                    s.Unsubscribe();
                }
            }
        }
Example #53
0
 public void Delete(ISubscription subscription)
 {
     subscriptionDAL.Delete(subscription);
 }
Example #54
0
 public void OnSubscribe(ISubscription subscription) => subscription.Cancel();
 /// <summary>
 /// Returns whether the publication and subscription match and the event published by the
 /// publisher will be relayed to the subscriber.
 /// <para>
 /// This is the always the case for global publications.
 /// </para>
 /// </summary>
 /// <param name="publication">The publication.</param>
 /// <param name="subscription">The subscription.</param>
 /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
 /// <returns><code>true</code> if event has to be sent to the subscriber.</returns>
 public bool Match(IPublication publication, ISubscription subscription, EventArgs e)
 {
     // globally all publishers and subscribers match
     return(true);
 }
Example #56
0
 /// <summary>
 /// Called after the event was relayed from the publication to the subscribers.
 /// </summary>
 /// <param name="eventTopic">The event topic.</param>
 /// <param name="publication">The publication.</param>
 /// <param name="subscription">The subscription.</param>
 /// <param name="handler">The handler.</param>
 /// <param name="sender">The sender.</param>
 /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
 public override void RelayedEvent(IEventTopicInfo eventTopic, IPublication publication, ISubscription subscription, IHandler handler, object sender, EventArgs e)
 {
     Debug.WriteLine(
         "Relayed event '{6}' from publisher '{0}' [{1}] to subscriber '{2}' [{3}] with EventArgs '{4}' with handler '{5}'.",
         publication.Publisher,
         publication.Publisher is INamedItem ? ((INamedItem)publication.Publisher).EventBrokerItemName : string.Empty,
         subscription.Subscriber,
         subscription.Subscriber is INamedItem ? ((INamedItem)subscription.Subscriber).EventBrokerItemName : string.Empty,
         e,
         handler,
         eventTopic.Uri);
 }
Example #57
0
 public virtual void Subscribe(ISubscription <T> subscription)
 {
     _observers.Add(subscription);
 }
Example #58
0
 public ISubscription EnhanceSubscription(ISubscription subscription)
 {
     return(subscription);
 }
Example #59
0
 public OnSubscribe(ISubscription subscription)
 {
     Subscription = subscription;
 }
Example #60
0
        /// <summary>
        /// Called when a publication or subscription matcher did not match and the event was not relayed to a subscription.
        /// </summary>
        /// <param name="eventTopic">The event topic.</param>
        /// <param name="publication">The publication.</param>
        /// <param name="subscription">The subscription.</param>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        public override void SkippedEvent(IEventTopicInfo eventTopic, IPublication publication, ISubscription subscription, object sender, EventArgs e)
        {
            List <IMatcher> matchers = new List <IMatcher>();

            var publicationMatchers  = from matcher in publication.PublicationMatchers where !matcher.Match(publication, subscription, e) select matcher;
            var subscriptionMatchers = from matcher in subscription.SubscriptionMatchers where !matcher.Match(publication, subscription, e) select matcher;

            matchers.AddRange(publicationMatchers);
            matchers.AddRange(subscriptionMatchers);

            StringBuilder sb = new StringBuilder();

            using (TextWriter writer = new StringWriter(sb))
            {
                foreach (IMatcher matcher in matchers)
                {
                    matcher.DescribeTo(writer);
                    writer.Write(", ");
                }
            }

            if (sb.Length > 0)
            {
                sb.Length -= 2;
            }

            Debug.WriteLine(
                "Skipped event '{0}' from publisher '{1}' [{2}] to subscriber '{3}' [{4}] with EventArgs '{5}' because the matchers '{6}' did not match.",
                eventTopic.Uri,
                publication.Publisher,
                publication.Publisher is INamedItem ? ((INamedItem)publication.Publisher).EventBrokerItemName : string.Empty,
                subscription.Subscriber,
                subscription.Subscriber is INamedItem ? ((INamedItem)subscription.Subscriber).EventBrokerItemName : string.Empty,
                e,
                sb);
        }