Exemplo n.º 1
0
 void userKicked_Published(object sender, EventSubscription<UserKicked>.PublishedEventArgs e)
 {
     // Inform that user has been kicked and exit the application when UserKicked event is published
     ExecuteOnUIThread(() =>
     {
         MessageBox.Show("You have been kicked");
         this.Close();
     });
 }
 public void NullActionThrows()
 {
     var filterDelegateReference = new MockDelegateReference()
     {
         Target = (Predicate<object>)(arg =>
         {
             return true;
         })
     };
     var eventSubscription = new EventSubscription<object>(null, filterDelegateReference);
 }
        public static EventListener Create(EventSubscription eventSubscription)
        {
            switch (eventSubscription.EventType)
            {
                case "NewSensorData":
                    return new SensorDataEventListener(eventSubscription);
                case "NewPosition":
                    return new PositionEventListener(eventSubscription);
            }

            throw new ArgumentOutOfRangeException("eventSubscription", "EventType does not exist.");
        }
Exemplo n.º 4
0
        public void FilterShouldNotBeNull()
        {
            var action = new Mock<IDelegateReference>();
            action.SetupGet(a => a.Target).Returns((Action<object>)delegate { });

            var filter = new Mock<IDelegateReference>();
            filter.SetupGet(a => a.Target).Returns((Predicate<object>)delegate { return true; });

            var subscription = new EventSubscription<object>(action.Object, filter.Object);

            Assert.That(subscription.Filter, Is.Not.Null);
        }
 /// <summary>
 /// Creates an instance of the correct child eventlistener
 /// </summary>
 /// <param name="eventSubscription"></param>
 /// <returns></returns>
 public static EventListener Create(EventSubscription eventSubscription)
 {
     switch (eventSubscription.EventType)
     {
         case "ButtonPressed":
         case "HumidityChanged":
         case "LightChanged":
         case "TemperatureChanged":
             return new SensorDataEventListener(eventSubscription);
         case "LocationUpdated":
             return new PositionEventListener(eventSubscription);
     }
     throw new ArgumentOutOfRangeException("eventSubscription", "EventType does not exist.");
 }
        public void NullTargetInFilterThrows()
        {
            var actionDelegateReference = new MockDelegateReference()
            {
                Target = (Action<object>)delegate { }
            };

            var filterDelegateReference = new MockDelegateReference()
            {
                Target = null
            };
            var eventSubscription = new EventSubscription<object>(actionDelegateReference,
                                                                                filterDelegateReference);
        }
        public void CanInitEventSubscription()
        {
            var actionDelegateReference = new MockDelegateReference((Action<object>)delegate { });
            var filterDelegateReference = new MockDelegateReference((Predicate<object>)delegate { return true; });
            var eventSubscription = new EventSubscription<object>(actionDelegateReference, filterDelegateReference, null, EventCommunicatorsRelationship.All);

            var subscriptionToken = new SubscriptionToken(t => { });

            eventSubscription.SubscriptionToken = subscriptionToken;

            Assert.Same(actionDelegateReference.Target, eventSubscription.Action);
            Assert.Same(filterDelegateReference.Target, eventSubscription.Filter);
            Assert.Same(subscriptionToken, eventSubscription.SubscriptionToken);
        }
Exemplo n.º 8
0
        private void SubscribeToEvents()
        {
            // Workaround for issue #2 'EventSubscription<TEvent> default constructor does not start the service'
            // This issue is fixed in nvents 0.7
            Events.Service.Start();

            // Create a EventSubscription for the MessageSent event
            var messageSent = new EventSubscription<MessageSent>();
            // Register a handler for when Published is raised for MessageSent event
            messageSent.Published += messageSent_Published;

            // Create a EventSubscription for the UserKicked event and filter to only the current user
            var userKicked = new EventSubscription<UserKicked>(user => user.UserId == currentUser.Id);
            // Register a handler for when Published is raised for UserKicked event (will only be raised for events that passes the subscription filter)
            userKicked.Published += userKicked_Published;
        }
 public void DifferentTargetTypeInActionThrows()
 {
     var actionDelegateReference = new MockDelegateReference()
     {
         Target = (Action<int>)delegate { }
     };
     var filterDelegateReference = new MockDelegateReference()
     {
         Target = (Predicate<string>)(arg =>
         {
             return true;
         })
     };
     var eventSubscription = new EventSubscription<string>(actionDelegateReference,
                                                                     filterDelegateReference);
 }
Exemplo n.º 10
0
        public void GetExecutionStrategyDoesNotExecuteActionIfFilterReturnsFalse()
        {
            bool actionExecuted = false;
            var actionDelegate = new Mock<IDelegateReference>();

            actionDelegate.SetupGet(d => d.Target).Returns((Action<int>)delegate { actionExecuted = true; });

            var filterDelegate = new Mock<IDelegateReference>();

            filterDelegate.SetupGet(d => d.Target).Returns((Predicate<int>)delegate { return false; });

            var eventSubscription = new EventSubscription<int>(actionDelegate.Object, filterDelegate.Object);

            var publishAction = eventSubscription.GetExecutionStrategy();

            publishAction.Invoke(new object[] { null });

            Assert.That(actionExecuted, Is.False);
        }
 public void NullTargetInActionThrows()
 {
     Assert.ThrowsException<ArgumentException>(() =>
     {
         var actionDelegateReference = new MockDelegateReference()
         {
             Target = null
         };
         var filterDelegateReference = new MockDelegateReference()
         {
             Target = (Predicate<object>)(arg =>
             {
                 return true;
             })
         };
         var eventSubscription = new EventSubscription<object>(actionDelegateReference,
                                                                         filterDelegateReference);
     });
 }
        public void DifferentTargetTypeInActionThrows()
        {
            var actionDelegateReference = new MockDelegateReference()
            {
                Target = (Action<int>)delegate { }
            };
            var filterDelegateReference = new MockDelegateReference()
            {
                Target = (Predicate<string>)(arg =>
                {
                    return true;
                })
            };

            Assert.Throws<ArgumentException>(
                () =>
                {
                    var eventSubscription = new EventSubscription<string>(actionDelegateReference,
                        filterDelegateReference, null, EventCommunicatorsRelationship.All);
                });
        }
Exemplo n.º 13
0
        public IEnumerable<EventSubscription> GetAll()
        {
            var subscriptions = new List<EventSubscription>();
            var path = GetPathForSubscriptions();
            var files = Directory.GetFiles(path);

            foreach (var file in files)
            {
                var json = File.ReadAllText(file);
                var holder = _serializer.FromJson<EventSubscriptionHolder>(json);
                var subscription = new EventSubscription();
                subscription.Id = Guid.Parse(holder.Id);
                subscription.LastEventId = holder.LastEventId;
                subscription.Owner = Type.GetType(holder.Owner);
                subscription.EventType = Type.GetType(holder.EventType);
                subscription.EventName = holder.EventName;
                subscription.Method = subscription.Owner.GetMethod(Bifrost.Events.ProcessMethodInvoker.ProcessMethodName, new Type[] { subscription.EventType });
                subscriptions.Add(subscription);
            }

            return subscriptions;
        }
Exemplo n.º 14
0
        public void GetExecutionStrategyShouldReturnDelegateThatExecutesTheFilterAndThenTheAction()
        {
            var executedDelegates = new List<string>();

            var actionDelegate = new Mock<IDelegateReference>();

            actionDelegate.SetupGet(d => d.Target).Returns((Action<object>) delegate { executedDelegates.Add("Action"); });

            var filterDelegate = new Mock<IDelegateReference>();

            filterDelegate.SetupGet(d => d.Target).Returns((Predicate<object>) delegate { executedDelegates.Add("Filter"); return true; });

            var eventSubscription = new EventSubscription<object>(actionDelegate.Object, filterDelegate.Object);

            var publishAction = eventSubscription.GetExecutionStrategy();

            Assert.That(publishAction, Is.Not.Null);

            publishAction.Invoke(null);

            Assert.That(executedDelegates.Count, Is.EqualTo(2));
            Assert.That(executedDelegates[0], Is.EqualTo("Filter"));
            Assert.That(executedDelegates[1], Is.EqualTo("Action"));
        }
Exemplo n.º 15
0
 public Task <string> CreateEventSubscription(EventSubscription subscription) => _innerService.CreateEventSubscription(subscription);
 public static void AddQueueHandler(
     this EventSubscription subscription, IQueue queue, IQueueMessageMapper mapper = null, long id = 0)
 {
     subscription.AddHandler(new QueueHandler(subscription, id, queue, mapper));
 }
        public async Task <string> EventSource()
        {
            // use the event stream content type, as per specification
            HttpContext.Response.ContentType = "text/event-stream";

            // get the last event id out of the header
            string lastEventIdString = HttpContext.Request.Headers["Last-Event-ID"].FirstOrDefault();
            int    temp;
            int?   lastEventId = null;

            if (lastEventIdString != null && int.TryParse(lastEventIdString, out temp))
            {
                lastEventId = temp;
            }

            string remoteIp = HttpContext.Connection.RemoteIpAddress.ToString();


            // open the current request stream for writing.
            // Use UTF-8 encoding, and do not close the stream when disposing.
            using (var clientStream = new StreamWriter(HttpContext.Response.Body, Encoding.UTF8, 1024, true)
            {
                AutoFlush = true
            }) {
                // subscribe to the heartbeat event. Elsewhere, a timer will push updates to this event periodically.
                using (EventSubscription <EventSourceUpdate> subscription = eventsService.SubscribeTo <EventSourceUpdate>("heartbeat")) {
                    try {
                        logger.LogInformation($"Opened event source stream to address: {remoteIp}");

                        await clientStream.WriteLineAsync($":connected {DateTimeOffset.Now.ToString("o")}");

                        // If a last event id is given, pump out any intermediate events here.
                        if (lastEventId != null)
                        {
                            // We're not doing anything that stores events in this heartbeat demo,
                            // so do nothing here.
                        }

                        // start pumping out events as they are pushed to the subscription queue
                        while (true)
                        {
                            // asynchronously wait for an event to fire before continuing this loop.
                            // this is implemented with a semaphore slim using the async wait, so it
                            // should play nice with the async framework.
                            EventSourceUpdate update = await subscription.WaitForData();

                            // push the update down the request stream to the client
                            if (update != null)
                            {
                                string updateString = update.ToString();
                                await clientStream.WriteAsync(updateString);
                            }

                            if (HttpContext.RequestAborted.IsCancellationRequested == true)
                            {
                                break;
                            }
                        }
                    }
                    catch (Exception e) {
                        // catch client closing the connection
                        logger.LogInformation($"Closed event source stream from {remoteIp}. Message: {e.Message}");
                    }
                }
            }

            return(":closed");
        }
Exemplo n.º 18
0
 public PSEventSubscriptionListInstance(EventSubscription eventSubscription)
     : base(eventSubscription)
 {
 }
        public void StrategyPassesArgumentToDelegates()
        {
            string passedArgumentToAction = null;
            string passedArgumentToFilter = null;

            var actionDelegateReference = new MockDelegateReference((Action<string>)(obj => passedArgumentToAction = obj));
            var filterDelegateReference = new MockDelegateReference((Predicate<string>)(obj =>
                                                                                            {
                                                                                                passedArgumentToFilter = obj;
                                                                                                return true;
                                                                                            }));

            var eventSubscription = new EventSubscription<string>(actionDelegateReference, filterDelegateReference);
            var publishAction = eventSubscription.GetExecutionStrategy();

            publishAction.Invoke(new[] { "TestString" });

            Assert.AreEqual("TestString", passedArgumentToAction);
            Assert.AreEqual("TestString", passedArgumentToFilter);
        }
        public void CanInitEventSubscription()
        {
            var actionDelegateReference = new MockDelegateReference((Action<object>)delegate { });
            var filterDelegateReference = new MockDelegateReference((Predicate<object>)delegate { return true; });
            var eventSubscription = new EventSubscription<object>(actionDelegateReference, filterDelegateReference);

            var subscriptionToken = new SubscriptionToken();

            eventSubscription.SubscriptionToken = subscriptionToken;

            Assert.AreSame(actionDelegateReference.Target, eventSubscription.Action);
            Assert.AreSame(filterDelegateReference.Target, eventSubscription.Filter);
            Assert.AreSame(subscriptionToken, eventSubscription.SubscriptionToken);
        }
 /// <summary>
 /// Constructor
 /// </summary>
 /// <param name="eventSubscription">Data of the event to listen to</param>
 protected EventListener(EventSubscription eventSubscription)
 {
     this.EventSubscription = eventSubscription;
 }
Exemplo n.º 22
0
        public void Save(EventSubscription subscription)
        {
            var path = GetPathForSubscriptions();
            var file = string.Format("{0}\\{1}.{2}.{3}", path, subscription.Owner.Namespace, subscription.Owner.Name, subscription.EventName);

            var holder = new EventSubscriptionHolder
            {
                Id = subscription.Id.ToString(),
                LastEventId = subscription.LastEventId,
                Owner = string.Format("{0}.{1}, {2}", subscription.Owner.Namespace, subscription.Owner.Name, subscription.Owner.Assembly.GetName().Name),
                EventType = string.Format("{0}.{1}, {2}", subscription.EventType.Namespace, subscription.EventType.Name, subscription.EventType.Assembly.GetName().Name),
                EventName = subscription.EventName
            };

            var json = _serializer.ToJson(holder);
            File.WriteAllText(file, json);
        }
 /// <summary>
 /// Create or update an event subscription to a domain.
 /// </summary>
 /// <remarks>
 /// Asynchronously creates a new event subscription or updates an existing
 /// event subscription.
 /// </remarks>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group within the user's subscription.
 /// </param>
 /// <param name='domainName'>
 /// Name of the domain topic.
 /// </param>
 /// <param name='eventSubscriptionName'>
 /// Name of the event subscription to be created. Event subscription names must
 /// be between 3 and 100 characters in length and use alphanumeric letters
 /// only.
 /// </param>
 /// <param name='eventSubscriptionInfo'>
 /// Event subscription properties containing the destination and filter
 /// information.
 /// </param>
 public static EventSubscription CreateOrUpdate(this IDomainEventSubscriptionsOperations operations, string resourceGroupName, string domainName, string eventSubscriptionName, EventSubscription eventSubscriptionInfo)
 {
     return(operations.CreateOrUpdateAsync(resourceGroupName, domainName, eventSubscriptionName, eventSubscriptionInfo).GetAwaiter().GetResult());
 }
        public void DifferentTargetTypeInFilterThrows()
        {
            Assert.ThrowsException<ArgumentException>(() =>
            {

                var actionDelegateReference = new MockDelegateReference()
                {
                    Target = (Action<string>)delegate { }
                };

                var filterDelegateReference = new MockDelegateReference()
                {
                    Target = (Predicate<int>)(arg =>
                    {
                        return true;
                    })
                };
                var eventSubscription = new EventSubscription<string>(actionDelegateReference,
                                                                                filterDelegateReference);
            });
        }
Exemplo n.º 25
0
        /// <summary>
        /// Subscribes to the role player changed event.
        /// </summary>
        /// <param name="domainRelationshipInfo">RelationshipInfo, which changes cause a notification.</param>
        /// <param name="bSourceRole"></param>
        /// <param name="elementId">Id of the role player, on which role changes to notify the observer.</param>
        /// <param name="action">Action to call on the observer.</param>
        public void Subscribe(DomainRelationshipInfo domainRelationshipInfo, bool bSourceRole, Guid elementId, Action <RolePlayerChangedEventArgs> action)
        {
            IDelegateReference actionReference = new DelegateReference(action, false);
            IDelegateReference filterReference = new DelegateReference(new Predicate <RolePlayerChangedEventArgs>(delegate { return(true); }), true);
            IEventSubscription subscription    = new EventSubscription <RolePlayerChangedEventArgs>(actionReference, filterReference);

            #region dictionarySource
            if (bSourceRole)
            {
                lock (dictionarySource)
                {
                    Guid domainClassId = domainRelationshipInfo.Id;

                    if (!dictionarySource.Keys.Contains(domainClassId))
                    {
                        dictionarySource.Add(domainClassId, new Dictionary <Guid, List <IEventSubscription> >());
                    }

                    if (!dictionarySource[domainClassId].Keys.Contains(elementId))
                    {
                        dictionarySource[domainClassId].Add(elementId, new List <IEventSubscription>());
                    }
                    dictionarySource[domainClassId][elementId].Add(subscription);

                    // process descendants
                    foreach (DomainClassInfo info in domainRelationshipInfo.AllDescendants)
                    {
                        domainClassId = info.Id;

                        if (!dictionarySource.Keys.Contains(domainClassId))
                        {
                            dictionarySource.Add(domainClassId, new Dictionary <Guid, List <IEventSubscription> >());
                        }

                        if (!dictionarySource[domainClassId].Keys.Contains(elementId))
                        {
                            dictionarySource[domainClassId].Add(elementId, new List <IEventSubscription>());
                        }
                        dictionarySource[domainClassId][elementId].Add(subscription);
                    }
                }
            }
            #endregion

            #region dictionaryTarget
            if (!bSourceRole)
            {
                lock (dictionaryTarget)
                {
                    Guid domainClassId = domainRelationshipInfo.Id;

                    if (!dictionaryTarget.Keys.Contains(domainClassId))
                    {
                        dictionaryTarget.Add(domainClassId, new Dictionary <Guid, List <IEventSubscription> >());
                    }

                    if (!dictionaryTarget[domainClassId].Keys.Contains(elementId))
                    {
                        dictionaryTarget[domainClassId].Add(elementId, new List <IEventSubscription>());
                    }
                    dictionaryTarget[domainClassId][elementId].Add(subscription);

                    // process descendants
                    foreach (DomainClassInfo info in domainRelationshipInfo.AllDescendants)
                    {
                        domainClassId = info.Id;

                        if (!dictionaryTarget.Keys.Contains(domainClassId))
                        {
                            dictionaryTarget.Add(domainClassId, new Dictionary <Guid, List <IEventSubscription> >());
                        }

                        if (!dictionaryTarget[domainClassId].Keys.Contains(elementId))
                        {
                            dictionaryTarget[domainClassId].Add(elementId, new List <IEventSubscription>());
                        }
                        dictionaryTarget[domainClassId][elementId].Add(subscription);
                    }
                }
            }
            #endregion
        }
Exemplo n.º 26
0
        public void GetExecutionStrategyShouldReturnNullIfActionIsNull()
        {
            var actionDelegate = new Mock<IDelegateReference>();

            actionDelegate.SetupGet(d => d.Target).Returns((Action<object>)delegate { });

            var filterDelegate = new Mock<IDelegateReference>();

            filterDelegate.SetupGet(d => d.Target).Returns((Predicate<object>)delegate { return true; });

            var eventSubscription = new EventSubscription<object>(actionDelegate.Object, filterDelegate.Object);

            var publishAction = eventSubscription.GetExecutionStrategy();

            Assert.That(publishAction, Is.Not.Null);

            actionDelegate.SetupGet(d => d.Target).Returns(null);

            publishAction = eventSubscription.GetExecutionStrategy();

            Assert.That(publishAction, Is.Null);
        }
Exemplo n.º 27
0
        private async Task <bool> SeedSubscription(Event evt, EventSubscription sub, HashSet <string> toQueue, CancellationToken cancellationToken)
        {
            foreach (var eventId in await _eventRepository.GetEvents(sub.EventName, sub.EventKey, sub.SubscribeAsOf, cancellationToken))
            {
                if (eventId == evt.Id)
                {
                    continue;
                }

                var siblingEvent = await _eventRepository.GetEvent(eventId, cancellationToken);

                if ((!siblingEvent.IsProcessed) && (siblingEvent.EventTime < evt.EventTime))
                {
                    await QueueProvider.QueueWork(eventId, QueueType.Event);

                    return(false);
                }

                if (!siblingEvent.IsProcessed)
                {
                    toQueue.Add(siblingEvent.Id);
                }
            }

            if (!await _lockProvider.AcquireLock(sub.WorkflowId, cancellationToken))
            {
                Logger.LogInformation("Workflow locked {0}", sub.WorkflowId);
                return(false);
            }

            try
            {
                var workflow = await _workflowRepository.GetWorkflowInstance(sub.WorkflowId, cancellationToken);

                IEnumerable <ExecutionPointer> pointers = null;

                if (!string.IsNullOrEmpty(sub.ExecutionPointerId))
                {
                    pointers = workflow.ExecutionPointers.Where(p => p.Id == sub.ExecutionPointerId && !p.EventPublished && p.EndTime == null);
                }
                else
                {
                    pointers = workflow.ExecutionPointers.Where(p => p.EventName == sub.EventName && p.EventKey == sub.EventKey && !p.EventPublished && p.EndTime == null);
                }

                foreach (var p in pointers)
                {
                    p.EventData      = evt.EventData;
                    p.EventPublished = true;
                    p.Active         = true;
                }
                workflow.NextExecution = 0;
                await _workflowRepository.PersistWorkflow(workflow, cancellationToken);

                await _subscriptionRepository.TerminateSubscription(sub.Id, cancellationToken);

                return(true);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, ex.Message);
                return(false);
            }
            finally
            {
                await _lockProvider.ReleaseLock(sub.WorkflowId);

                await QueueProvider.QueueWork(sub.WorkflowId, QueueType.Workflow);
            }
        }
 protected EventListener(EventSubscription eventSubscription)
 {
     this.EventSubscription = eventSubscription;
 }
        /// <summary>
        /// Processes the Query
        /// Retreives the data from the events
        /// For use in IEventSource
        /// </summary>
        /// <param name="query">Query</param>
        /// <returns>Whether the Query succeeded or not</returns>
        public static bool TryQuery(EventSubscription eventSubscription, TagBlink tagBlink, out TagBlink ReturnTagBlink)
        {
            ReturnTagBlink = new TagBlink();
            int    hours    = TimeZoneInfo.Local.BaseUtcOffset.Hours;
            string timezone = hours >= 0 ? " +" + hours : " " + hours;

            //filters
            foreach (string filterKey in eventSubscription.Filters.Keys)
            {
                List <string> filterValues = eventSubscription.Filters[filterKey];
                bool          availaible   = false;
                try
                {
                    switch (filterKey)
                    {
                    case "TagID":
                        foreach (string filterValue in filterValues)
                        {
                            if (tagBlink["TagID"] == filterValue)
                            {
                                availaible = true;
                            }
                        }
                        if (!availaible)
                        {
                            return(false);
                        }
                        break;

                    case "":
                        break;

                    default:
                        throw new FaultException("Filtering on: " + filterKey + " is not supported yet in WsnEngine");
                    }
                }
                //TODO: catch more specific exception
                catch (Exception)
                {
                    throw new FaultException("Filtering on: " + filterKey + " is not supported for an " + eventSubscription.EventType + " event.");
                }
            }

            //fields!!
            foreach (string field in eventSubscription.Fields)
            {
                try
                {
                    switch (field)
                    {
                    //convert to the correct formats
                    //add the fields to the Query (select)
                    case "TagID":
                        ReturnTagBlink["TagID"] = tagBlink["TagID"];
                        break;

                    case "Name":
                        ReturnTagBlink["Name"] = tagBlink["name"];
                        break;

                    case "Serial":
                        ReturnTagBlink["Serial"] = tagBlink["sensor"];
                        break;

                    case "Location":
                        ReturnTagBlink["Location/X"] = tagBlink["X"];
                        ReturnTagBlink["Location/Y"] = tagBlink["Y"];
                        break;

                    case "Location/X":
                        ReturnTagBlink["Location/X"] = tagBlink["X"];
                        break;

                    case "Location/Y":
                        ReturnTagBlink["Location/Y"] = tagBlink["Y"];
                        break;

                    case "Buttons":
                        //skip if this boolean is 0
                        ReturnTagBlink["Buttons"] = tagBlink["Button"];
                        break;

                    case "Temperature":
                        ReturnTagBlink["Temperature"] = tagBlink["temperature"];
                        break;

                    case "Light":
                        ReturnTagBlink["Light"] = tagBlink["Light"];
                        break;

                    case "Humidity":
                        ReturnTagBlink["Humidity"] = tagBlink["Humidity"];
                        break;

                    case "RTLSBlinkTime":
                        ReturnTagBlink["RTLSBlinkTime"] = DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss") + timezone;
                        break;

                    case "All":
                        //switch on the type of event
                        switch (eventSubscription.EventType)
                        {
                        case "TemperatureChanged":
                            ReturnTagBlink["TagID"]         = tagBlink["TagID"];
                            ReturnTagBlink["Temperature"]   = tagBlink["Temperature"];
                            ReturnTagBlink["RTLSBlinkTime"] = DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss") + timezone;
                            break;

                        case "LightChanged":
                            ReturnTagBlink["TagID"]         = tagBlink["TagID"];
                            ReturnTagBlink["Light"]         = tagBlink["Light"];
                            ReturnTagBlink["RTLSBlinkTime"] = DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss") + timezone;
                            break;

                        case "HumidityChanged":
                            ReturnTagBlink["TagID"]         = tagBlink["TagID"];
                            ReturnTagBlink["Humidity"]      = tagBlink["Humidity"];
                            ReturnTagBlink["RTLSBlinkTime"] = DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss") + timezone;
                            break;

                        case "ButtonPressed":
                            ReturnTagBlink["TagID"]         = tagBlink["TagID"];
                            ReturnTagBlink["Button"]        = tagBlink["Button"];
                            ReturnTagBlink["RTLSBlinkTime"] = DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss") + timezone;
                            break;

                        case "LocationUpdated":
                            ReturnTagBlink["TagID"]             = tagBlink["TagID"];
                            ReturnTagBlink["Location/X"]        = tagBlink["X"];
                            ReturnTagBlink["Location/Y"]        = tagBlink["Y"];
                            ReturnTagBlink["Location/MapID"]    = tagBlink["MapID"];
                            ReturnTagBlink["Location/Accuracy"] = tagBlink["Accuracy"];
                            ReturnTagBlink["RTLSBlinkTime"]     = DateTime.UtcNow.ToString("yyyy/MM/dd HH:mm:ss") + timezone;
                            break;
                        }
                        break;

                    default:
                        throw new FaultException("The field" + field.ToString() + " is not provided in the WSN engine");
                    }
                }
                //TODO: catch more specific exception
                catch (Exception)
                {
                    throw new FaultException("The field" + field.ToString() + " is not provided in the " + eventSubscription.EventType + " event.");
                }
            }
            return(true);
        }
 public void Subscribe(EventSubscription eventSubscription)
 {
     //this.Logger.Trace("Subscribe method called on Ekahau4EngineAdapterService.");
     this.Callback = OperationContext.Current.GetCallbackChannel<IEventSourceCallback>();
     this.WsnEngine.Subscribe(eventSubscription);
 }
Exemplo n.º 31
0
 public async Task <string> CreateEventSubscription(EventSubscription subscription)
 {
     subscription.Id = Guid.NewGuid().ToString();
     _subscriptions.Add(subscription);
     return(subscription.Id);
 }
 public void Subscribe()
 {
     World.Subscribe(EventSubscription.Create <KeyDownEvent>(TriggerActionOnProperKey, _owner));
 }
        public void GetPublishActionReturnsNullIfFilterIsNull()
        {
            var actionDelegateReference = new MockDelegateReference((Action<object>)delegate { });
            var filterDelegateReference = new MockDelegateReference((Predicate<object>)delegate { return true; });

            var eventSubscription = new EventSubscription<object>(actionDelegateReference, filterDelegateReference);

            var publishAction = eventSubscription.GetExecutionStrategy();

            Assert.IsNotNull(publishAction);

            filterDelegateReference.Target = null;

            publishAction = eventSubscription.GetExecutionStrategy();

            Assert.IsNull(publishAction);
        }
 public AvailableTargetsView()
 {
     Event.Subscribe(EventSubscription.Create <ShootSelected>(ShowOptions, this));
     Event.Subscribe(EventSubscription.Create <ActionCancelled>(e => ClearOptions(), this));
     Event.Subscribe(EventSubscription.Create <ActionConfirmed>(e => ClearOptions(), this));
 }
Exemplo n.º 35
0
        public override void ExecuteCmdlet()
        {
            if (this.ShouldProcess(this.EventSubscriptionName, $"Create a new Event Grid subscription {this.EventSubscriptionName}"))
            {
                string      scope;
                bool        isSubjectCaseSensitive = this.SubjectCaseSensitive.IsPresent;
                RetryPolicy retryPolicy            = null;

                if (!string.IsNullOrEmpty(this.ResourceId))
                {
                    scope = this.ResourceId;
                }
                else if (this.InputObject != null)
                {
                    scope = this.InputObject.Id;
                }
                else if (this.DomainInputObject != null)
                {
                    scope = this.DomainInputObject.Id;
                }
                else if (this.DomainTopicInputObject != null)
                {
                    scope = this.DomainTopicInputObject.Id;
                }
                else
                {
                    // ResourceID not specified, build the scope for the event subscription for either the
                    // subscription, or resource group, or custom topic depending on which of the parameters are provided.

                    scope = EventGridUtils.GetScope(
                        this.DefaultContext.Subscription.Id,
                        this.ResourceGroupName,
                        this.TopicName,
                        this.DomainName,
                        this.DomainTopicName);
                }

                if (this.IsParameterBound(c => c.MaxDeliveryAttempt) || this.IsParameterBound(c => c.EventTtl))
                {
                    retryPolicy = new RetryPolicy(
                        maxDeliveryAttempts: this.MaxDeliveryAttempt == 0 ? (int?)null : this.MaxDeliveryAttempt,
                        eventTimeToLiveInMinutes: this.EventTtl == 0 ? (int?)null : this.EventTtl);
                }

                if (!string.Equals(this.EndpointType, EventGridConstants.Webhook, StringComparison.OrdinalIgnoreCase))
                {
                    if (this.IsParameterBound(c => c.MaxEventsPerBatch) || this.IsParameterBound(c => c.PreferredBatchSizeInKiloByte))
                    {
                        throw new ArgumentException("MaxEventsPerBatch and PreferredBatchSizeInKiloByte are supported when EndpointType is webhook only.");
                    }

                    if (this.IsParameterBound(c => c.AzureActiveDirectoryApplicationIdOrUri) || this.IsParameterBound(c => c.AzureActiveDirectoryTenantId))
                    {
                        throw new ArgumentException("AzureActiveDirectoryApplicationIdOrUri and AzureActiveDirectoryTenantId are supported when EndpointType is webhook only.");
                    }
                }

                if (EventGridUtils.ShouldShowEventSubscriptionWarningMessage(this.Endpoint, this.EndpointType))
                {
                    WriteWarning(EventGridConstants.EventSubscriptionHandshakeValidationMessage);
                }

                if (this.IncludedEventType != null && this.IncludedEventType.Length == 1 && string.Equals(this.IncludedEventType[0], "All", StringComparison.OrdinalIgnoreCase))
                {
                    // Show Warning message for user
                    this.IncludedEventType = null;
                    WriteWarning(EventGridConstants.IncludedEventTypeDeprecationMessage);
                }

                EventSubscription eventSubscription = this.Client.CreateEventSubscription(
                    scope,
                    this.EventSubscriptionName,
                    this.Endpoint,
                    this.EndpointType,
                    this.SubjectBeginsWith,
                    this.SubjectEndsWith,
                    isSubjectCaseSensitive,
                    this.IncludedEventType,
                    this.Label,
                    retryPolicy,
                    this.DeliverySchema,
                    this.DeadLetterEndpoint,
                    this.ExpirationDate,
                    this.AdvancedFilter,
                    this.MaxEventsPerBatch,
                    this.PreferredBatchSizeInKiloByte,
                    this.AzureActiveDirectoryTenantId,
                    this.AzureActiveDirectoryApplicationIdOrUri);

                PSEventSubscription psEventSubscription = new PSEventSubscription(eventSubscription);
                this.WriteObject(psEventSubscription, true);
            }
        }
Exemplo n.º 36
0
 public CallQueue()
 {
     World.Subscribe(EventSubscription.Create <AgentCallStatusChanged>(PlayerAvailable, this));
     World.Subscribe(EventSubscription.Create <JobChanged>(JobChanged, this));
     _generator = new CallGenerator(Job.ReturnSpecialistLevel1);
 }
Exemplo n.º 37
0
 public PSEventSubscriptionListInstance(EventSubscription eventSubscription, string fullEndpointUrl)
     : base(eventSubscription, fullEndpointUrl)
 {
 }
Exemplo n.º 38
0
 public static void Subscribe <T>(EventSubscription <T> subscription)
 {
     _events.Subscribe(subscription);
     Resources.Put(Guid.NewGuid().ToString(), subscription);
 }
 public static void AddStorageHandler(this EventSubscription subscription, ILogHandler logHandler, long id = 0)
 {
     subscription.AddHandler(new StorageHandler(subscription, id, logHandler));
 }
Exemplo n.º 40
0
 public static void SubscribeForever(EventSubscription subscription)
 {
     _persistentEvents.Subscribe(subscription);
 }
 public static void AddQueueHandler(
     this EventSubscription subscription, IQueue queue, Func <DecodedEvent, object> mappingFunc, long id = 0)
 {
     AddQueueHandler(subscription, queue, new QueueMessageMapper(mappingFunc), id);
 }
Exemplo n.º 42
0
 public static void Subscribe(EventSubscription subscription)
 {
     _events.Subscribe(subscription);
     _eventSubs.Add(subscription);
     Resources.Put(subscription.GetHashCode().ToString(), subscription);
 }
 public async Task <EventSubscription> Subscription_CreateOrUpdateAsync(string scope, string eventSubscriptionName, EventSubscription subscription, CancellationToken cancellationToken = default)
 {
     return(await client.EventSubscriptions.CreateOrUpdateAsync(scope, eventSubscriptionName, subscription, cancellationToken).ConfigureAwait(false));
 }
        public void GetPublishActionReturnsNullIfActionIsNull()
        {
            var actionDelegateReference = new MockDelegateReference((Action<object>)delegate { });
            var filterDelegateReference = new MockDelegateReference((Predicate<object>)delegate { return true; });

            var eventSubscription = new EventSubscription<object>(actionDelegateReference, filterDelegateReference, null, EventCommunicatorsRelationship.All);

            var publishAction = eventSubscription.GetExecutionStrategy();

            Assert.NotNull(publishAction);

            actionDelegateReference.Target = null;

            publishAction = eventSubscription.GetExecutionStrategy();

            Assert.Null(publishAction);
        }
 public EventExpectation()
 {
     _subscription = new EventSubscription <T>(_ => _eventWasFired = true);
 }
Exemplo n.º 46
0
        public void Subscribe(EventSubscription eventSubscription)
        {
            if (!this.EventListeners.ContainsKey(eventSubscription.EventId))
            {
                //TODO: filters checken -> Ekahau
                var eventListener = EventListener.Create(eventSubscription);
                eventListener.EventReceived += this.EventListenerEventReceived;
                this.EventListeners.Add(eventSubscription.EventId, eventListener);

                //pass a reference to the event of the controller
                eventListener.Advise(ControllerRef);
            }      
        }
Exemplo n.º 47
0
        public override void ExecuteCmdlet()
        {
            if (string.IsNullOrEmpty(this.EventSubscriptionName))
            {
                // This can happen with the InputObject parameter set where the
                // event subscription name needs to be determined based on the piped in
                // EventSubscriptionObject
                if (this.InputObject == null)
                {
                    throw new Exception("Unexpected condition: Event Subscription name cannot be determined.");
                }

                this.EventSubscriptionName = this.InputObject.EventSubscriptionName;
            }

            if (this.ShouldProcess(this.EventSubscriptionName, $"Update existing Event Grid subscription {this.EventSubscriptionName}"))
            {
                string      scope;
                RetryPolicy retryPolicy                  = null;
                int?        maxEventsPerBatch            = null;
                int?        preferredBatchSizeInKiloByte = null;
                string      aadAppIdOrUri                = string.Empty;
                string      aadTenantId                  = string.Empty;

                if (!string.IsNullOrEmpty(this.ResourceId))
                {
                    scope = this.ResourceId;
                }
                else if (this.InputObject != null)
                {
                    scope = this.InputObject.Topic;
                }
                else
                {
                    // ResourceID not specified, build the scope for the event subscription for either the
                    // subscription, or resource group, or custom topic depending on which of the parameters are provided.

                    scope = EventGridUtils.GetScope(
                        this.DefaultContext.Subscription.Id,
                        this.ResourceGroupName,
                        this.TopicName,
                        this.DomainName,
                        this.DomainTopicName);
                }

                EventSubscription existingEventSubscription = this.Client.GetEventSubscription(scope, this.EventSubscriptionName);
                if (existingEventSubscription == null)
                {
                    throw new Exception($"Cannot find an existing event subscription with name {this.EventSubscriptionName}.");
                }

                if (this.IsParameterBound(c => c.MaxDeliveryAttempt) || this.IsParameterBound(c => c.EventTtl))
                {
                    retryPolicy = new RetryPolicy(existingEventSubscription.RetryPolicy?.MaxDeliveryAttempts, existingEventSubscription.RetryPolicy?.EventTimeToLiveInMinutes);

                    // Only override the new values if any.
                    if (this.IsParameterBound(c => c.MaxDeliveryAttempt))
                    {
                        retryPolicy.MaxDeliveryAttempts = this.MaxDeliveryAttempt;
                    }

                    if (this.IsParameterBound(c => c.EventTtl))
                    {
                        retryPolicy.EventTimeToLiveInMinutes = this.EventTtl;
                    }
                }
                else
                {
                    retryPolicy = existingEventSubscription.RetryPolicy;
                }

                if (string.Equals(this.EndpointType, EventGridConstants.Webhook, StringComparison.OrdinalIgnoreCase))
                {
                    WebHookEventSubscriptionDestination dest = existingEventSubscription.Destination as WebHookEventSubscriptionDestination;
                    if (dest != null)
                    {
                        maxEventsPerBatch            = this.IsParameterBound(c => c.MaxEventsPerBatch) ? (int?)this.MaxEventsPerBatch : dest.MaxEventsPerBatch.HasValue ? dest.MaxEventsPerBatch : null;
                        preferredBatchSizeInKiloByte = this.IsParameterBound(c => c.PreferredBatchSizeInKiloByte) ? (int?)this.PreferredBatchSizeInKiloByte : dest.PreferredBatchSizeInKilobytes.HasValue ? dest.PreferredBatchSizeInKilobytes : null;
                        aadAppIdOrUri = this.IsParameterBound(c => c.AzureActiveDirectoryApplicationIdOrUri) ? this.AzureActiveDirectoryApplicationIdOrUri : dest.AzureActiveDirectoryApplicationIdOrUri;
                        aadTenantId   = this.IsParameterBound(c => c.AzureActiveDirectoryTenantId) ? this.AzureActiveDirectoryTenantId : dest.AzureActiveDirectoryTenantId;
                    }
                    else
                    {
                        maxEventsPerBatch            = this.IsParameterBound(c => c.MaxEventsPerBatch) ? (int?)this.MaxEventsPerBatch : null;
                        preferredBatchSizeInKiloByte = this.IsParameterBound(c => c.PreferredBatchSizeInKiloByte) ? (int?)this.PreferredBatchSizeInKiloByte : null;
                        aadAppIdOrUri = this.IsParameterBound(c => c.AzureActiveDirectoryApplicationIdOrUri) ? this.AzureActiveDirectoryApplicationIdOrUri : string.Empty;
                        aadTenantId   = this.IsParameterBound(c => c.AzureActiveDirectoryTenantId) ? this.AzureActiveDirectoryTenantId : string.Empty;
                    }
                }
                else
                {
                    if (this.IsParameterBound(c => c.MaxEventsPerBatch) || this.IsParameterBound(c => c.PreferredBatchSizeInKiloByte))
                    {
                        throw new ArgumentException("MaxEventsPerBatch and PreferredBatchSizeInKiloByte are supported when EndpointType is webhook only.");
                    }

                    if (this.IsParameterBound(c => c.AzureActiveDirectoryApplicationIdOrUri) || this.IsParameterBound(c => c.AzureActiveDirectoryTenantId))
                    {
                        throw new ArgumentException("AzureActiveDirectoryApplicationIdOrUri and AzureActiveDirectoryTenantId are supported when EndpointType is webhook only.");
                    }
                }

                if (EventGridUtils.ShouldShowEventSubscriptionWarningMessage(this.Endpoint, this.EndpointType))
                {
                    WriteWarning(EventGridConstants.EventSubscriptionHandshakeValidationMessage);
                }

                if (this.IncludedEventType != null && this.IncludedEventType.Length == 1 && string.Equals(this.IncludedEventType[0], "All", StringComparison.OrdinalIgnoreCase))
                {
                    // Show Warning message for user
                    this.IncludedEventType = null;
                    WriteWarning(EventGridConstants.IncludedEventTypeDeprecationMessage);
                }

                EventSubscription eventSubscription = this.Client.UpdateEventSubscription(
                    scope: scope,
                    eventSubscriptionName: this.EventSubscriptionName,
                    endpoint: this.Endpoint,
                    endpointType: this.EndpointType,
                    subjectBeginsWith: this.SubjectBeginsWith ?? existingEventSubscription.Filter.SubjectBeginsWith,
                    subjectEndsWith: this.SubjectEndsWith ?? existingEventSubscription.Filter.SubjectEndsWith,
                    isSubjectCaseSensitive: existingEventSubscription.Filter.IsSubjectCaseSensitive,
                    includedEventTypes: this.IncludedEventType,
                    labels: this.Label,
                    retryPolicy: retryPolicy,
                    deadLetterEndpoint: this.DeadLetterEndpoint,
                    expirationDate: this.ExpirationDate,
                    advancedFilter: this.AdvancedFilter,
                    maxEventsPerBatch: maxEventsPerBatch,
                    preferredBatchSizeInKiloByte: preferredBatchSizeInKiloByte,
                    aadAppIdOrUri: aadAppIdOrUri,
                    aadTenantId: aadTenantId);

                PSEventSubscription psEventSubscription = new PSEventSubscription(eventSubscription);
                this.WriteObject(psEventSubscription);
            }
        }
        public void NullActionThrows()
        {
            var filterDelegateReference = new MockDelegateReference()
            {
                Target = (Predicate<object>)(arg =>
                {
                    return true;
                })
            };

            Assert.Throws<ArgumentNullException>(
                () =>
                {
                    var eventSubscription = new EventSubscription<object>(null, filterDelegateReference, null, EventCommunicatorsRelationship.All);
                });
        }
Exemplo n.º 49
0
 public GovernmentTaxes(IAccount playerAccount)
 {
     _playerAccount = playerAccount;
     World.Subscribe(EventSubscription.Create <HourChanged>(HourChanged, this));
     World.Subscribe(EventSubscription.Create <SalaryPaymentOccured>(ApplyIncomeTaxes, this));
 }
        public void NullTargetInFilterThrows()
        {
            var actionDelegateReference = new MockDelegateReference()
            {
                Target = (Action<object>)delegate { }
            };

            var filterDelegateReference = new MockDelegateReference()
            {
                Target = null
            };

            Assert.Throws<ArgumentException>(
                () =>
                {
                    var eventSubscription = new EventSubscription<object>(actionDelegateReference,
                        filterDelegateReference, null, EventCommunicatorsRelationship.All);
                });
        }
Exemplo n.º 51
0
 public FoodDelivery()
 {
     World.Subscribe(EventSubscription.Create <FoodOrdered>(Ordered, this));
 }
        public async Task <string> CreateEventSubscription(EventSubscription subscription)
        {
            await EventSubscriptions.InsertOneAsync(subscription);

            return(subscription.Id);
        }
        public void GetPublishActionReturnsDelegateThatExecutesTheFilterAndThenTheAction()
        {
            var executedDelegates = new List<string>();
            var actionDelegateReference =
                new MockDelegateReference((Action<object>)delegate { executedDelegates.Add("Action"); });

            var filterDelegateReference = new MockDelegateReference((Predicate<object>)delegate
                                                {
                                                    executedDelegates.Add(
                                                        "Filter");
                                                    return true;

                                                });

            var eventSubscription = new EventSubscription<object>(actionDelegateReference, filterDelegateReference);


            var publishAction = eventSubscription.GetExecutionStrategy();

            Assert.IsNotNull(publishAction);

            publishAction.Invoke(null);

            Assert.AreEqual(2, executedDelegates.Count);
            Assert.AreEqual("Filter", executedDelegates[0]);
            Assert.AreEqual("Action", executedDelegates[1]);
        }
Exemplo n.º 54
0
        public async Task <ExecutionResult <EventMessage> > AssignMessageToSubscriber(EventSubscription subscription, EventMessage message)
        {
            message.IsProcessing            = true;
            message.ProcessingStartDateTime = DateTime.Now;

            message.Subscription = message.Subscription.Any() ? new List <EventSubscription>(message.Subscription)
            {
                subscription
            } : new List <EventSubscription>()
            {
                subscription
            };

            return(await EventRepository.UpdateAsync(message));
        }
        public void GetPublishActionDoesNotExecuteActionIfFilterReturnsFalse()
        {
            bool actionExecuted = false;
            var actionDelegateReference = new MockDelegateReference()
            {
                Target = (Action<int>)delegate { actionExecuted = true; }
            };
            var filterDelegateReference = new MockDelegateReference((Predicate<int>)delegate
                                                                                            {
                                                                                                return false;
                                                                                            });

            var eventSubscription = new EventSubscription<int>(actionDelegateReference, filterDelegateReference);


            var publishAction = eventSubscription.GetExecutionStrategy();

            publishAction.Invoke(new object[] { null });

            Assert.IsFalse(actionExecuted);
        }
Exemplo n.º 56
0
 /// <summary>
 /// Create or update an event subscription to a topic.
 /// </summary>
 /// <remarks>
 /// Asynchronously creates a new event subscription or updates an existing
 /// event subscription.
 /// </remarks>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group within the user's subscription.
 /// </param>
 /// <param name='topicName'>
 /// Name of the domain topic.
 /// </param>
 /// <param name='eventSubscriptionName'>
 /// Name of the event subscription to be created. Event subscription names must
 /// be between 3 and 100 characters in length and use alphanumeric letters
 /// only.
 /// </param>
 /// <param name='eventSubscriptionInfo'>
 /// Event subscription properties containing the destination and filter
 /// information.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <EventSubscription> BeginCreateOrUpdateAsync(this ITopicEventSubscriptionsOperations operations, string resourceGroupName, string topicName, string eventSubscriptionName, EventSubscription eventSubscriptionInfo, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, topicName, eventSubscriptionName, eventSubscriptionInfo, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
Exemplo n.º 57
0
 /// <summary>
 /// Create or update an event subscription to a topic.
 /// </summary>
 /// <remarks>
 /// Asynchronously creates a new event subscription or updates an existing
 /// event subscription.
 /// </remarks>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='resourceGroupName'>
 /// The name of the resource group within the user's subscription.
 /// </param>
 /// <param name='topicName'>
 /// Name of the domain topic.
 /// </param>
 /// <param name='eventSubscriptionName'>
 /// Name of the event subscription to be created. Event subscription names must
 /// be between 3 and 100 characters in length and use alphanumeric letters
 /// only.
 /// </param>
 /// <param name='eventSubscriptionInfo'>
 /// Event subscription properties containing the destination and filter
 /// information.
 /// </param>
 public static EventSubscription BeginCreateOrUpdate(this ITopicEventSubscriptionsOperations operations, string resourceGroupName, string topicName, string eventSubscriptionName, EventSubscription eventSubscriptionInfo)
 {
     return(operations.BeginCreateOrUpdateAsync(resourceGroupName, topicName, eventSubscriptionName, eventSubscriptionInfo).GetAwaiter().GetResult());
 }
Exemplo n.º 58
0
        public void StrategyShouldPassArgumentToDelegates()
        {
            string passedArgumentToAction = null;
            string passedArgumentToFilter = null;

            var actionDelegate = new Mock<IDelegateReference>();

            actionDelegate.SetupGet(d => d.Target).Returns((Action<string>)(obj => passedArgumentToAction = obj));

            var filterDelegate = new Mock<IDelegateReference>();

            filterDelegate.SetupGet(d => d.Target).Returns((Predicate<string>)(obj => { passedArgumentToFilter = obj; return true; }));

            var eventSubscription = new EventSubscription<string>(actionDelegate.Object, filterDelegate.Object);
            var publishAction = eventSubscription.GetExecutionStrategy();

            publishAction.Invoke(new[] { "TestString" });

            Assert.That(passedArgumentToAction, Is.EqualTo("TestString"));
            Assert.That(passedArgumentToFilter, Is.EqualTo("TestString"));
        }
Exemplo n.º 59
0
        public override Task ProcessRequestAsync(IRequest req, IResponse res, string operationName)
        {
            if (HostContext.ApplyCustomHandlerRequestFilters(req, res))
            {
                return(TypeConstants.EmptyTask);
            }

            var feature = HostContext.GetPlugin <ServerEventsFeature>();

            var session = req.GetSession();

            if (feature.LimitToAuthenticatedUsers && !session.IsAuthenticated)
            {
                session.ReturnFailedAuthentication(req);
                return(TypeConstants.EmptyTask);
            }

            res.ContentType = MimeTypes.ServerSentEvents;
            res.AddHeader(HttpHeaders.CacheControl, "no-cache");
            res.ApplyGlobalResponseHeaders();
            res.UseBufferedStream = false;
            res.KeepAlive         = true;

            if (feature.OnInit != null)
            {
                feature.OnInit(req);
            }

            res.Flush();

            var serverEvents = req.TryResolve <IServerEvents>();
            var userAuthId   = session != null ? session.UserAuthId : null;
            var anonUserId   = serverEvents.GetNextSequence("anonUser");
            var userId       = userAuthId ?? ("-" + anonUserId);
            var displayName  = session.GetSafeDisplayName()
                               ?? "user" + anonUserId;

            var now            = DateTime.UtcNow;
            var subscriptionId = SessionExtensions.CreateRandomSessionId();

            //Handle both ?channel=A,B,C or ?channels=A,B,C
            var channels = new List <string>();
            var channel  = req.QueryString["channel"];

            if (!string.IsNullOrEmpty(channel))
            {
                channels.AddRange(channel.Split(','));
            }
            channel = req.QueryString["channels"];
            if (!string.IsNullOrEmpty(channel))
            {
                channels.AddRange(channel.Split(','));
            }

            if (channels.Count == 0)
            {
                channels = EventSubscription.UnknownChannel.ToList();
            }

            var subscription = new EventSubscription(res)
            {
                CreatedAt       = now,
                LastPulseAt     = now,
                Channels        = channels.ToArray(),
                SubscriptionId  = subscriptionId,
                UserId          = userId,
                UserName        = session != null ? session.UserName : null,
                DisplayName     = displayName,
                SessionId       = req.GetSessionId(),
                IsAuthenticated = session != null && session.IsAuthenticated,
                UserAddress     = req.UserHostAddress,
                OnPublish       = feature.OnPublish,
                //OnError = feature.OnError,
                Meta =
                {
                    { "userId",                           userId                                                                 },
                    { "displayName",                      displayName                                                            },
                    { "channels",                         string.Join(",", channels)                                             },
                    { AuthMetadataProvider.ProfileUrlKey, session.GetProfileUrl() ?? AuthMetadataProvider.DefaultNoProfileImgUrl },
                }
            };

            if (feature.OnCreated != null)
            {
                feature.OnCreated(subscription, req);
            }

            if (req.Response.IsClosed)
            {
                return(TypeConstants.EmptyTask); //Allow short-circuiting in OnCreated callback
            }
            var heartbeatUrl = feature.HeartbeatPath != null
                ? req.ResolveAbsoluteUrl("~/".CombineWith(feature.HeartbeatPath)).AddQueryParam("id", subscriptionId)
                : null;

            var unRegisterUrl = feature.UnRegisterPath != null
                ? req.ResolveAbsoluteUrl("~/".CombineWith(feature.UnRegisterPath)).AddQueryParam("id", subscriptionId)
                : null;

            heartbeatUrl  = AddSessionParamsIfAny(heartbeatUrl, req);
            unRegisterUrl = AddSessionParamsIfAny(unRegisterUrl, req);

            subscription.ConnectArgs = new Dictionary <string, string>(subscription.Meta)
            {
                { "id", subscriptionId },
                { "unRegisterUrl", unRegisterUrl },
                { "heartbeatUrl", heartbeatUrl },
                { "updateSubscriberUrl", req.ResolveAbsoluteUrl("~/event-subscribers/" + subscriptionId) },
                { "heartbeatIntervalMs", ((long)feature.HeartbeatInterval.TotalMilliseconds).ToString(CultureInfo.InvariantCulture) },
                { "idleTimeoutMs", ((long)feature.IdleTimeout.TotalMilliseconds).ToString(CultureInfo.InvariantCulture) }
            };

            if (feature.OnConnect != null)
            {
                feature.OnConnect(subscription, subscription.ConnectArgs);
            }

            serverEvents.Register(subscription, subscription.ConnectArgs);

            var tcs = new TaskCompletionSource <bool>();

            subscription.OnDispose = _ =>
            {
                try
                {
                    res.EndHttpHandlerRequest(skipHeaders: true);
                }
                catch { }
                tcs.SetResult(true);
            };

            return(tcs.Task);
        }
        public void NullTargetInFilterThrows()
        {
            Assert.ThrowsException<ArgumentException>(() =>
            {
                var actionDelegateReference = new MockDelegateReference()
                {
                    Target = (Action<object>)delegate { }
                };

                var filterDelegateReference = new MockDelegateReference()
                {
                    Target = null
                };
                var eventSubscription = new EventSubscription<object>(actionDelegateReference,
                                                                                filterDelegateReference);
            });
        }