private void _clientSocket_OnMessage(object sender, MessageEventArgs e)
        {
            Debug.WriteLine(e.Data);
            WebSocketMessage message;

            using (StringReader stringReader = new StringReader(e.Data))
                using (JsonTextReader jsonReader = new JsonTextReader(stringReader))
                {
                    message = _serializer.Deserialize <WebSocketMessage>(jsonReader);
                }
            switch (message.MessageType)
            {
            case WebSocketMessage.WebSocketMessageType.EventNotification:
                EventNotification?.Invoke(this, new WebSocketMessageEventArgs(message));
                break;

            case WebSocketMessage.WebSocketMessageType.ObjectDisposed:
                _referenceResolver.RemoveReference(message.DtoGuid);
                break;

            default:
                _receivedMessages[message.MessageGuid] = message;
                _messageHandler.Set();
                break;
            }
        }
Example #2
0
        public virtual void MonitorNotifyEvent(NodeId id, EventNotification ev)
        {
            Application.ServerMonitorKey key = new Application.ServerMonitorKey(id, NodeAttribute.EventNotifier);
            try
            {
                this.monitorMapRW.EnterReadLock();
                if (!this.monitorMap.TryGetValue(key, out List <MonitoredItem> monitoredItemList))
                {
                    return;
                }

                for (int index = 0; index < monitoredItemList.Count; ++index)
                {
                    if (monitoredItemList[index].QueueEvent.Count >= monitoredItemList[index].QueueSize)
                    {
                        monitoredItemList[index].QueueOverflowed = true;
                    }
                    else
                    {
                        monitoredItemList[index].QueueEvent.Enqueue(ev);
                    }

                    if (monitoredItemList[index].ParentSubscription.ChangeNotification == Subscription.ChangeNotificationType.None)
                    {
                        monitoredItemList[index].ParentSubscription.ChangeNotification = Subscription.ChangeNotificationType.AtPublish;
                    }
                }
            }
            finally
            {
                this.monitorMapRW.ExitReadLock();
            }
        }
        public override MailMessage GetEventNotificationMailMessage(EventNotification model)
        {
            if (!ShouldHandle(model.Event))
            {
                return(null);
            }

            string notificationType = "Occurrence 404";

            if (model.IsNew)
            {
                notificationType = "New 404";
            }
            else if (model.IsRegression)
            {
                notificationType = "Regression 404";
            }

            if (model.IsCritical)
            {
                notificationType = String.Concat("Critical ", notificationType.ToLower());
            }

            var requestInfo = model.Event.GetRequestInfo();
            var mailerModel = new EventNotificationModel(model)
            {
                BaseUrl = Settings.Current.BaseURL,
                Subject = String.Concat(notificationType, ": ", model.Event.Source.Truncate(120)),
                Url     = requestInfo != null?requestInfo.GetFullPath(true, true, true) : model.Event.Source
            };

            return(_emailGenerator.GenerateMessage(mailerModel, "Notice").ToMailMessage());
        }
Example #4
0
 /// <summary>
 /// Constructs an acknowledgment from an event notification.
 /// </summary>
 public EventAcknowledgement(EventNotification notification)
 {
     m_sourceName    = notification.SourceID;
     m_conditionName = notification.ConditionName;
     m_activeTime    = notification.ActiveTime;
     m_cookie        = notification.Cookie;
 }
        void Raise <TEvent>(Composer composer, TInstance instance, TEvent @event, Action <Composer, Activity <TInstance>, TInstance> callback)
            where TEvent : Event
        {
            List <Activity <TInstance> > activities;

            if (!_activityCache.TryGetValue(@event, out activities))
            {
                return;
            }

            composer.Execute(() =>
            {
                var notification = new EventNotification(instance, @event);

                var taskComposer = new TaskComposer <TInstance>(composer.CancellationToken);

                ((Composer)taskComposer).Execute(() => _raisingObserver.OnNext(notification));

                foreach (var activity in activities)
                {
                    callback(taskComposer, activity, instance);
                }

                ((Composer)taskComposer).Execute(() => _raisedObserver.OnNext(notification));

                return(taskComposer.Finish());
            });
        }
        public void CollectionView_CurrentChanging(object sender, CurrentChangingEventArgs e)
        {
            _currentChangingFired = true;

            if (_expectedEventQueue.Count > 0)
            {
                EventNotification eventNotification = _expectedEventQueue[0];
                if (eventNotification.EventType == "CurrentChanging")
                {
                    _expectedEventQueue.RemoveAt(0);
                }
                else
                {
                    if (string.IsNullOrEmpty(eventNotification.Parameter))
                    {
                        Assert.Fail("CurrentChanging event was fired when we were expecting a " +
                                    eventNotification.EventType + " event.");
                    }
                    else
                    {
                        Assert.Fail("CurrentChanging event was fired when we were expecting a " +
                                    eventNotification.EventType + " event with Parameter: " + eventNotification.Parameter);
                    }
                }
            }
        }
Example #7
0
        public Task Handle(EventNotification <BasketCleanedEvent> notification, CancellationToken cancellationToken)
        {
            LogHelper.AddInfo("BasketCleanedEventHandler calisti.");


            return(Task.FromResult(0));
        }
        public void CollectionView_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            _collectionChangeFired = true;

            if (_expectedEventQueue.Count > 0)
            {
                EventNotification eventNotification = _expectedEventQueue[0];
                if (eventNotification.EventType == "CollectionChanged")
                {
                    if (eventNotification.Parameter == e.Action.ToString())
                    {
                        _expectedEventQueue.RemoveAt(0);
                    }
                    else
                    {
                        Assert.Fail("CollectionChanged event was fired with the wrong action type. Got: " + e.Action.ToString() + ", Expected:" + eventNotification.Parameter);
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(eventNotification.Parameter))
                    {
                        Assert.Fail("CollectionChanged(" + e.Action.ToString() + ") event was fired when we were expecting a " +
                                    eventNotification.EventType + " event.");
                    }
                    else
                    {
                        Assert.Fail("CollectionChanged(" + e.Action.ToString() + ") event was fired when we were expecting a " +
                                    eventNotification.EventType + " event with Parameter: " + eventNotification.Parameter);
                    }
                }
            }
        }
        public void WhenStartCalledThenShouldConsumePublishedEventWithSingleSubscription()
        {
            using (var scope = ServiceProvider.CreateScope())
            {
                var @event       = new SampleReceiverEvent();
                var notification = new EventNotification <SampleReceiverEvent>(streamId: @event.Subject, @event: @event, correlationId: null, causationId: null, timestamp: DateTimeOffset.UtcNow, userId: null);
                var sender       = scope.ServiceProvider.GetRequiredService <IQueueMessageSender>();
                var receiver     = scope.ServiceProvider.GetRequiredService <IQueueMessageReceiver>();
                var sentTime     = DateTimeOffset.MinValue;

                Func <Task> act = async() => await receiver.StartAsync(CancellationToken.None);

                act.Should().NotThrow();

                Func <Task> verify = async() =>
                {
                    // Let the consumer actually startup, needs to open a connection which may take a short amount of time.
                    await Task.Delay(500);

                    await sender.SendAsync(notification);

                    sentTime = DateTimeOffset.UtcNow;

                    // Delay to ensure that we pick up the message.
                    await Task.Delay(250);
                };

                verify.Should().NotThrow();

                SampleReceiverEventHandler.Received.Should().Be(1);
            }
        }
Example #10
0
        /// <summary>
        /// Converts a ONEVENTSTRUCT struct to a EventNotification object.
        /// </summary>
        internal static EventNotification GetEventNotification(OpcRcw.Ae.ONEVENTSTRUCT input)
        {
            EventNotification output = new EventNotification();

            output.SourceID         = input.szSource;
            output.Time             = OpcCom.Interop.GetFILETIME(Convert(input.ftTime));
            output.Severity         = input.dwSeverity;
            output.Message          = input.szMessage;
            output.EventType        = (EventType)input.dwEventType;
            output.EventCategory    = input.dwEventCategory;
            output.ChangeMask       = input.wChangeMask;
            output.NewState         = input.wNewState;
            output.Quality          = new Opc.Da.Quality(input.wQuality);
            output.ConditionName    = input.szConditionName;
            output.SubConditionName = input.szSubconditionName;
            output.AckRequired      = input.bAckRequired != 0;
            output.ActiveTime       = OpcCom.Interop.GetFILETIME(Convert(input.ftActiveTime));
            output.Cookie           = input.dwCookie;
            output.ActorID          = input.szActorID;

            object[] attributes = OpcCom.Interop.GetVARIANTs(ref input.pEventAttributes, input.dwNumEventAttrs, false);

            output.SetAttributes(attributes);

            return(output);
        }
Example #11
0
        public MailMessage GetEventNotificationMailMessage(EventNotification model)
        {
            if (String.IsNullOrEmpty(model.Event.Message))
            {
                return(null);
            }

            string notificationType = "Occurrence event";

            if (model.IsNew)
            {
                notificationType = "New event";
            }
            else if (model.IsRegression)
            {
                notificationType = "Regression event";
            }

            if (model.IsCritical)
            {
                notificationType = String.Concat("Critical ", notificationType.ToLower());
            }

            var requestInfo = model.Event.GetRequestInfo();
            var mailerModel = new EventNotificationModel(model)
            {
                BaseUrl = Settings.Current.BaseURL,
                Subject = String.Concat(notificationType, ": ", model.Event.Message.Truncate(120)),
                Message = model.Event.Message,
                Url     = requestInfo != null?requestInfo.GetFullPath(true, true, true) : null
            };

            return(_emailGenerator.GenerateMessage(mailerModel, "Notice").ToMailMessage());
        }
Example #12
0
 internal void OnEventNotification(EventNotification notification)
 {
     if (_eventHandlers.ContainsKey(notification.eventId))
     {
         var handler = _eventHandlers[notification.eventId];
         handler.Method.Invoke(handler.Target, new object[] { this, notification.eventArgs });
     }
 }
 public EventNotificationModel(EventNotification notification)
 {
     Event            = notification.Event;
     IsNew            = notification.IsNew;
     IsCritical       = notification.IsCritical;
     IsRegression     = notification.IsRegression;
     TotalOccurrences = notification.TotalOccurrences;
 }
Example #14
0
 void SpawnEffectAppliedNotification(UnitEffect effect)
 {
     if (!effect.ShowApplyNotification)
     {
         return;
     }
     EventNotification.SpawnEffectNotification(EffectNotifactionPrefab, EffectNotificationsContainer, effect, effect.GetShortHandle() + " applied");
     EnableUnitUI();
 }
        public MailMessage GetEventNotificationMailMessage(EventNotification model)
        {
            if (!ShouldHandle(model.Event))
            {
                return(null);
            }

            throw new NotImplementedException();
        }
Example #16
0
        public void SendNotice(string emailAddress, EventNotification model)
        {
            var msg = _pluginManager.GetEventNotificationMailMessage(model);

            msg.To.Add(emailAddress);
            msg.Headers.Add("X-Mailer-Machine", Environment.MachineName);
            msg.Headers.Add("X-Mailer-Date", DateTime.Now.ToString());
            SendMessage(msg);
        }
Example #17
0
    void SpawnEffectExpiredNotification(UnitEffect effect)
    {
        if (!effect.ShowRemoveNotification)
        {
            return;
        }

        EventNotification.SpawnEffectNotification(EffectNotifactionPrefab, EffectNotificationsContainer, effect, effect.GetShortHandle() + " removed");
        EnableUnitUI();
    }
Example #18
0
    void SpawnInventoryNotification(IInventoryItem item, int count)
    {
        if (count <= 0 || !TurnSystem.HasTurn(m_Unit))
        {
            return;
        }

        EventNotification.SpawnInventoryNotification(EffectNotifactionPrefab, EffectNotificationsContainer, item, count, "");
        EnableUnitUI();
    }
Example #19
0
 public void PublishEvent(EventNotification notification)
 {
     _notifications.Add(notification);
     _loggingAdapter.WriteEntry(new LogEntry(LoggingEventType.Information, "New event published. {notification}",
                                             new Dictionary <string, object>()
     {
         { "notification", JsonConvert.SerializeObject(notification) },
         { "processItemId", notification.ProcessItemId }
     }));
 }
 public void Save(EventNotification eventNotification)
 {
     using (var adapter = PersistenceLayer.GetDataAccessAdapter())
     {
         var entity = Mapper.Map <EventNotification, EventNotificationEntity>(eventNotification);
         if (!adapter.SaveEntity(entity))
         {
             throw new PersistenceFailureException();
         }
     }
 }
Example #21
0
        public void SendNotice(string emailAddress, EventNotification model)
        {
            var message = _pluginManager.GetEventNotificationMailMessage(model);

            if (message == null)
            {
                return;
            }

            message.To = emailAddress;
            QueueMessage(message.ToMailMessage());
        }
        public void WhenStartCalledThenShouldNotConsumePublishedEventWithoutSubscription()
        {
            var services = new ServiceCollection();

            services.AddLogging(o => o.AddDebug())
            .AddOpenEventSourcing()
            .AddEvents()
            .AddRabbitMq(o =>
            {
                o.UseConnection(Configuration.GetValue <string>("RabbitMQ:ConnectionString"))
                .UseExchange(e =>
                {
                    e.WithName($"test-exchange-{Guid.NewGuid()}");
                    e.UseExchangeType("topic");
                })
                .AddSubscription(s =>
                {
                    s.UseName($"receiver-queue-{Guid.NewGuid()}");
                });
            })
            .AddJsonSerializers();

            var sp = services.BuildServiceProvider(new ServiceProviderOptions {
                ValidateOnBuild = true, ValidateScopes = true
            });

            using (var scope = sp.CreateScope())
            {
                var @event       = new SampleNonSubscriptionReceiverEvent();
                var notification = new EventNotification <SampleNonSubscriptionReceiverEvent>(streamId: @event.Subject, @event: @event, correlationId: null, causationId: null, timestamp: DateTimeOffset.UtcNow, userId: null);
                var sender       = scope.ServiceProvider.GetRequiredService <IQueueMessageSender>();
                var receiver     = scope.ServiceProvider.GetRequiredService <IQueueMessageReceiver>();

                Func <Task> act = async() => await receiver.StartAsync(CancellationToken.None);

                act.Should().NotThrow();

                Func <Task> verify = async() =>
                {
                    // Let the consumer actually startup, needs to open a connection which may take a short amount of time.
                    await Task.Delay(500);

                    await sender.SendAsync(notification);

                    // Delay to ensure that we pick up the message.
                    await Task.Delay(250);
                };

                verify.Should().NotThrow();

                SampleNonSubscriptionReceiverEventHandler.Received.Should().Be(0);
            }
        }
        public void WhenCreateMessageCalledWithEventThenShouldPopulateCorrelationIdFromEvent()
        {
            using (var scope = ServiceProvider.CreateScope())
            {
                var factory      = scope.ServiceProvider.GetRequiredService <IMessageFactory>();
                var @event       = new FakeEvent();
                var notification = new EventNotification <FakeEvent>(streamId: @event.Subject, @event: @event, correlationId: CorrelationId.New(), causationId: null, timestamp: @event.Timestamp, userId: null);
                var result       = factory.CreateMessage(notification);

                result.CorrelationId.Should().Be(notification.CorrelationId.ToString());
            }
        }
Example #24
0
    public void FireNotification(EventNotification notif, object help = null)
    {
        List <EventReceiver> tmp;

        if (_internalList.TryGetValue(notif, out tmp))
        {
            foreach (var t in tmp.Where(i => i.target != null))
            {
                t.callback(help);
            }
        }
    }
Example #25
0
        /// <inheritdoc />
        public async Task <bool> HandleEvent(EventType eventType, IEnumerable <string> parameters, CancellationToken cancellationToken)
        {
            if (!Running)
            {
                return(true);
            }

            string results;

            using (await SemaphoreSlimContext.Lock(Semaphore, cancellationToken).ConfigureAwait(false))
            {
                if (!Running)
                {
                    return(true);
                }

                var builder = new StringBuilder(Constants.DMTopicEvent);
                builder.Append('&');
                var notification = new EventNotification
                {
                    Type       = eventType,
                    Parameters = parameters
                };
                var json = JsonConvert.SerializeObject(notification);
                builder.Append(byondTopicSender.SanitizeString(Constants.DMParameterData));
                builder.Append('=');
                builder.Append(byondTopicSender.SanitizeString(json));

                var activeServer = GetActiveController();
                results = await activeServer.SendCommand(builder.ToString(), cancellationToken).ConfigureAwait(false);
            }

            if (results == Constants.DMResponseSuccess)
            {
                return(true);
            }

            List <Response> responses;

            try
            {
                responses = JsonConvert.DeserializeObject <List <Response> >(results);
            }
            catch
            {
                Logger.LogInformation("Recieved invalid response from DD when parsing event {0}:{1}{2}", eventType, Environment.NewLine, results);
                return(true);
            }

            await Task.WhenAll(responses.Select(x => Chat.SendMessage(x.Message, x.ChannelIds, cancellationToken))).ConfigureAwait(false);

            return(true);
        }
Example #26
0
        private static void InitEventNotification(CharityHubContext context)
        {
            if (context.EventNotifications.Any())
            {
                return;
            }

            var eventNotifications = new EventNotification[] {
                new EventNotification()
                {
                    Subject        = "Zbiórka",
                    CreatedDate    = new DateTime(2017, 11, 18, 12, 32, 12),
                    Body           = "Przy pałacu kultury o godzinie 12:30. Zapraszam!",
                    CharityEventId = 1,
                },
                new EventNotification()
                {
                    Subject        = "Zmiana terminu",
                    CreatedDate    = new DateTime(2017, 11, 18, 13, 32, 12),
                    Body           = "Zbiórka jednak o 14:00. Z góry przepraszamy",
                    CharityEventId = 1,
                },
                new EventNotification()
                {
                    Subject        = "Rodzaj jedzenia",
                    CreatedDate    = new DateTime(2017, 11, 19, 12, 32, 12),
                    Body           = "Prosimy o nie przynoszenie produktów z krótkim terminem przydatności",
                    CharityEventId = 2,
                },
                new EventNotification()
                {
                    Subject        = "Zbiórka",
                    CreatedDate    = new DateTime(2017, 11, 18, 11, 32, 12),
                    Body           = "W centrum o godzinie 10:30. Zapraszam!",
                    CharityEventId = 2,
                },
                new EventNotification()
                {
                    Subject        = "Pieniądze",
                    CreatedDate    = new DateTime(2017, 11, 20, 12, 32, 12),
                    Body           = "Pieniądze przekazujemy jedynie poprzez przelew na konto",
                    CharityEventId = 3,
                },
            };

            foreach (var s in eventNotifications)
            {
                context.EventNotifications.Add(s);
            }

            context.SaveChanges();
        }
Example #27
0
        public override MailMessage GetEventNotificationMailMessage(EventNotification model)
        {
            if (!ShouldHandle(model.Event))
            {
                return(null);
            }

            var error = model.Event.GetError();

            if (error == null)
            {
                return(null);
            }

            var stackingTarget = error.GetStackingTarget();

            if (stackingTarget?.Error == null)
            {
                return(null);
            }

            var    requestInfo = model.Event.GetRequestInfo();
            string errorType   = !String.IsNullOrEmpty(stackingTarget.Error.Type) ? stackingTarget.Error.Type : "Error";

            string notificationType = String.Concat(errorType, " occurrence");

            if (model.IsNew)
            {
                notificationType = String.Concat(!model.IsCritical ? "New " : "new ", error.Type);
            }
            else if (model.IsRegression)
            {
                notificationType = String.Concat(errorType, " regression");
            }

            if (model.IsCritical)
            {
                notificationType = String.Concat("Critical ", notificationType);
            }

            var mailerModel = new EventNotificationModel(model)
            {
                BaseUrl                                       = Settings.Current.BaseURL,
                Subject                                       = String.Concat(notificationType, ": ", stackingTarget.Error.Message.Truncate(120)),
                Url                                           = requestInfo != null?requestInfo.GetFullPath(true, true, true) : null,
                                               Message        = stackingTarget.Error.Message,
                                               TypeFullName   = errorType,
                                               MethodFullName = stackingTarget.Method != null?stackingTarget.Method.GetFullName() : null
            };

            return(_emailGenerator.GenerateMessage(mailerModel, "NoticeError").ToMailMessage());
        }
Example #28
0
        public static async Task AddEventNotification(EventNotification eventNotification)
        {
            await Init();

            if (eventNotification.Id != 0)
            {
                await db.UpdateAsync(eventNotification);
            }
            else
            {
                await db.InsertAsync(eventNotification);
            }
        }
Example #29
0
        public Task SendNoticeAsync(string emailAddress, EventNotification model)
        {
            var message = _pluginManager.GetEventNotificationMailMessage(model);

            if (message == null)
            {
                _logger.Warn().Message("Unable to create event notification mail message for event \"{0}\". User: \"{1}\"", model.EventId, emailAddress).Write();
                return(Task.CompletedTask);
            }

            message.To = emailAddress;
            return(QueueMessageAsync(message.ToMailMessage()));
        }
        public void WhenSendAsyncCalledWithSingleEventThenShouldSendEvent()
        {
            using (var scope = ServiceProvider.CreateScope())
            {
                var sender       = scope.ServiceProvider.GetRequiredService <IQueueMessageSender>();
                var @event       = new SameSenderEvent();
                var notification = new EventNotification <SameSenderEvent>(streamId: @event.Subject, @event: @event, correlationId: null, causationId: null, timestamp: DateTimeOffset.UtcNow, userId: null);

                Func <Task> act = async() => await sender.SendAsync(notification);

                act.Should().NotThrow();
            }
        }
Example #31
0
 private void notifyEventTimeout(EventNotification evt)
 {
     NewEvent(evt, true);
 }
Example #32
0
 /* Watches an event. */
 public void Watch(string name, EventNotification notify)
 {
     stream.WriteByte(10);
       if(esocket == null)
       {
     int eport = Convert.ToInt32(Receive());
     en = new Dictionary<string, EventNotification>();
     esocket = new TcpClient(ehost, eport);
     estream = esocket.GetStream();
     string id = Receive();
     byte[] msg = System.Text.Encoding.UTF8.GetBytes(id);
     estream.Write(msg, 0, msg.Length);
     estream.WriteByte(0);
     estream.ReadByte();
     new Thread(Listen).Start();
       }
       Send(name);
       info = Receive();
       if(!Ok())
       {
     throw new IOException(info);
       }
       en.Add(name, notify);
 }
Example #33
0
 private void notifyEvent(EventNotification evt)
 {
     NewEvent(evt, false);
 }