예제 #1
0
        public static string ToAuditDataHtml(this IApplicationEvent applicationEvent)
        {
            if (applicationEvent.Event == "Insert" && applicationEvent.Data.OrEmpty().StartsWith("<Data>"))
            {
                return(applicationEvent.Data.To <XElement>().Elements().Select(p => $"<div class='prop'><span class='key'>{p.Name}</span>: <span class='val'>{p.Value.HtmlEncode()}</span></div>").ToLinesString());
            }

            if (applicationEvent.Event == "Update" && applicationEvent.Data.OrEmpty().StartsWith("<DataChange>"))
            {
                var data          = applicationEvent.Data.To <XElement>();
                var old           = data.Element("old");
                var newData       = data.Element("new");
                var propertyNames = old.Elements().Select(x => x.Name.LocalName)
                                    .Concat(newData.Elements().Select(x => x.Name.LocalName)).Distinct().ToArray();

                return(propertyNames.Select(p => $"<div class='prop'>Changed <span class='key'>{p}</span> from <span class='old'>\"{ old.GetValue<string>(p).HtmlEncode() }\"</span> to <span class='new'>\"{ newData.GetValue<string>(p).HtmlEncode() }\"</span></div>").ToLinesString());
            }

            if (applicationEvent.Event == "Delete" && applicationEvent.Data.OrEmpty().StartsWith("<DataChange>"))
            {
                var data = applicationEvent.Data.To <XElement>();
                var old  = data.Element("old");

                var propertyNames = old.Elements().Select(x => x.Name.LocalName).ToArray();

                return(propertyNames.Select(p => $"<div class='prop'><span class='key'>{p}</span> was <span class='old'>\"{old.GetValue<string>(p).HtmlEncode() }\"</span></div>").ToLinesString());
            }

            return(applicationEvent.Data.OrEmpty().HtmlEncode());
        }
예제 #2
0
        public void Publish(IApplicationEvent applicationEvent)
        {
            Guard.Against.Null(applicationEvent, nameof(applicationEvent));

            var channel = _objectPool.Get();

            object message = (object)applicationEvent;

            try
            {
                string exchangeName = MessagingConstants.Exchanges.FRONTDESK_CLINICMANAGEMENT_EXCHANGE;
                channel.ExchangeDeclare(exchangeName, "direct", true, false, null);

                var sendBytes = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(message));

                var properties = channel.CreateBasicProperties();
                properties.Persistent = true;

                channel.BasicPublish(
                    exchange: exchangeName,
                    routingKey: "entity-changes",
                    basicProperties: properties,
                    body: sendBytes);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                _objectPool.Return(channel);
            }
        }
예제 #3
0
        /// <summary>
        /// Loads the item recorded in this event.
        /// </summary>
        public virtual IEntity LoadItem(IApplicationEvent applicationEvent)
        {
            var type = AppDomain.CurrentDomain.GetAssemblies().Select(a => a.GetType(applicationEvent.ItemType)).ExceptNull().FirstOrDefault();

            if (type == null)
            {
                throw new Exception("Could not load the type " + applicationEvent.ItemType);
            }

            if (applicationEvent.Event == "Update" || applicationEvent.Event == "Insert")
            {
                return(Database.Get(applicationEvent.ItemKey.To <Guid>(), type));
            }

            if (applicationEvent.Event == "Delete")
            {
                var result = Activator.CreateInstance(type) as GuidEntity;
                result.ID = applicationEvent.ItemKey.To <Guid>();

                foreach (var p in XElement.Parse(applicationEvent.Data).Elements())
                {
                    var old      = p.Value;
                    var property = type.GetProperty(p.Name.LocalName);
                    property.SetValue(result, old.To(property.PropertyType));
                }

                return(result);
            }

            throw new NotSupportedException();
        }
예제 #4
0
        void Undo(IApplicationEvent operation)
        {
            Entity item;

            switch (operation.Event)
            {
            case "Insert":
                Database.Delete(operation.LoadItem(), DeleteBehaviour.BypassAll);
                break;

            case "Delete":
                item = operation.LoadItem() as Entity;
                Database.Save(item, SaveBehaviour.BypassSaved | SaveBehaviour.BypassSaving);
                break;

            case "Update":
                item = operation.LoadItem().Clone() as Entity;

                foreach (var p in GetOldDataNode(operation).Elements())
                {
                    var old      = p.Value;
                    var property = item.GetType().GetProperty(p.Name.LocalName);
                    property.SetValue(item, old.To(property.PropertyType));
                }

                Database.Save(item, SaveBehaviour.BypassSaved | SaveBehaviour.BypassSaving);
                break;

            default:
                // Ignore other cases
                break;
            }
        }
예제 #5
0
 private void OnApplicationEvent(IApplicationEvent evt)
 {
     if (!_isEnabled)
     {
         return;
     }
     _ = _eventBus.PublishAsync(evt); // Fire and forget
 }
예제 #6
0
        public void Raise(IApplicationEvent evt)
        {
            var handlers = GetHandlersForThisEvent(evt.GetType());

            foreach (var handler in handlers)
            {
                handler(evt);
            }
        }
예제 #7
0
 private void GetParticipantApplicationEventHandler(IApplicationEvent applicationEvent)
 {
     var data = (GetParticipantApplicationEvent)applicationEvent;
     var global = _mockDataService.ReadObject(GetGlobalModel, MockFileName.GlobalModel, data.CallerContext);
     if (global != null)
     {
         data.DBParticipant = global.DomainObject;
     }
 }
예제 #8
0
        protected void ProjectEvent(IApplicationEvent @event)
        {
            var projectionCoordinator = _actorSystem.GetActorFromAddressBook(ActorAddresses.ProjectionCoordinator);

            var projectFeedback = projectionCoordinator.Ask <ProjectionCoordinator.ProjectionsCompleted>(
                new ProjectionCoordinator.Project(Guid.NewGuid(), @event), TimeSpan.FromSeconds(20)).Result;

            if (!projectFeedback.Successfully)
            {
                throw new Exception(string.Format("Unable to successfully project {0} application event!", @event.GetType().FullName));
            }
        }
예제 #9
0
        private async Task OnEventAsync(IApplicationEvent evt)
        {
            // Lookup all clients that are already in the game and notify them
            var connectionIds = _playerConnections.GetAll();

            foreach (var connectionId in connectionIds)
            {
                var playerId = _playerConnections.GetPlayerId(connectionId);
                var client   = _hubContext.Clients.Client(connectionId);
                await client?.SendAsync("IApplicationEvent", evt);
            }
        }
예제 #10
0
        public static string ToAuditDataHtml(this IApplicationEvent applicationEvent, bool excludeIds = false)
        {
            if (applicationEvent.Event == "Insert" && applicationEvent.Data.OrEmpty().StartsWith("<Data>"))
            {
                // return applicationEvent.Data.To<XElement>().Elements().Select(p => $"<div class='prop'><span class='key'>{p.Name}</span>: <span class='val'>{p.Value.HtmlEncode()}</span></div>").ToLinesString();

                var insertData = applicationEvent.Data.To <XElement>().Elements().ToArray();

                if (excludeIds)
                {
                    insertData = insertData.Except(x => x.Name.LocalName.EndsWith("Id") && insertData.Select(p => p.Name.LocalName).Contains(x.Name.LocalName.TrimEnd("Id")))
                                 .Except(x => x.Name.LocalName.EndsWith("Ids") && insertData.Select(p => p.Name.LocalName).Contains(x.Name.LocalName.TrimEnd("Ids"))).ToArray();
                }

                return(insertData.Select(p => $"<div class='prop'><span class='key'>{p.Name.LocalName.ToLiteralFromPascalCase()}</span>: <span class='val'>{p.Value.HtmlEncode()}</span></div>").ToLinesString());
            }

            if (applicationEvent.Event == "Update" && applicationEvent.Data.OrEmpty().StartsWith("<DataChange>"))
            {
                var data          = applicationEvent.Data.To <XElement>();
                var old           = data.Element("old");
                var newData       = data.Element("new");
                var propertyNames = old.Elements().Select(x => x.Name.LocalName)
                                    .Concat(newData.Elements().Select(x => x.Name.LocalName)).Distinct().ToArray();

                if (excludeIds)
                {
                    propertyNames = propertyNames.Except(p => p.EndsWith("Id") && propertyNames.Contains(p.TrimEnd("Id")))
                                    .Except(p => p.EndsWith("Ids") && propertyNames.Contains(p.TrimEnd("Ids"))).ToArray();
                }

                return(propertyNames.Select(p => $"<div class='prop'>Changed <span class='key'>{p.ToLiteralFromPascalCase()}</span> from <span class='old'>\"{ old.GetValue<string>(p).HtmlEncode() }\"</span> to <span class='new'>\"{ newData.GetValue<string>(p).HtmlEncode() }\"</span></div>").ToLinesString());
            }

            if (applicationEvent.Event == "Delete" && applicationEvent.Data.OrEmpty().StartsWith("<DataChange>"))
            {
                var data = applicationEvent.Data.To <XElement>();
                var old  = data.Element("old");

                var propertyNames = old.Elements().Select(x => x.Name.LocalName).ToArray();

                if (excludeIds)
                {
                    propertyNames = propertyNames.Except(p => p.EndsWith("Id") && propertyNames.Contains(p.TrimEnd("Id")))
                                    .Except(p => p.EndsWith("Ids") && propertyNames.Contains(p.TrimEnd("Ids"))).ToArray();
                }

                return(propertyNames.Select(p => $"<div class='prop'><span class='key'>{p.ToLiteralFromPascalCase()}</span> was <span class='old'>\"{old.GetValue<string>(p).HtmlEncode() }\"</span></div>").ToLinesString());
            }

            return(applicationEvent.Data.OrEmpty().HtmlEncode());
        }
예제 #11
0
        private void SendEventToProjectors(Guid correlationId, IApplicationEvent @event)
        {
            var eventType = @event.GetType();

            _correlationId = correlationId;
            _subscriptions[eventType].ForEach(p => p.Tell(new ProjectApplicationEvent(correlationId, @event)));
            _subscribersForEvent = new List <IActorRef>();
            _subscribersForEvent.AddRange(_subscriptions[eventType]);
            _projectRequestor = Sender;
            _projectionsOK    = true;

            Become(WaitingForProjectorResponses);
        }
예제 #12
0
        private void DispatchApplicationEvent(IApplicationEvent applicataionEvent)
        {
            switch (applicataionEvent)
            {
            case LoginEvent loginEvent:
                _logger.Information($"[{nameof(DispatchApplicationEvent)}] Dispatch {nameof(LoginEvent)} =>  " +
                                    $"UserName: {loginEvent.UserName}; " +
                                    $"Login state: {loginEvent.Successful}; "
                                    );             // hier an den jeweiligen service schicken der das event verarbeiten soll, z.B email, notification signalr
                break;

            default:
                throw new SmartHubException("Unknown event error");
            }
        }
예제 #13
0
        public void Publish(IApplicationEvent applicationEvent)
        {
            var factory = new ConnectionFactory();

              IConnection conn = factory.CreateConnection(); //uses defaults
              using (IModel channel = conn.CreateModel()) {
            channel.ExchangeDeclare("ContactUpdate", ExchangeType.Direct);
            channel.QueueDeclare("BarcelonaQueue", false, false, false, null);
            channel.QueueBind("BarcelonaQueue", "ContactUpdate", "", null);
            IBasicProperties props = channel.CreateBasicProperties();
            string json = JsonConvert.SerializeObject(applicationEvent, Formatting.None);

            byte[] messageBodyBytes = Encoding.UTF8.GetBytes(json);
            channel.BasicPublish("ContactUpdate", "", props, messageBodyBytes);
              }
        }
        public void Handle_HasCurrentLifetimeScope_ShouldHandleEvent(
            [Frozen] Mock<IContainer> container,
            [Frozen] Mock<IApplicationEventHandler<IApplicationEvent>> eventHandler,
            IApplicationEvent applicationEvent,
            ApplicationEventLifetimeScopeDecorator<IApplicationEvent> decorator)
        {
            // Act

            decorator.Handle(applicationEvent);

            // Assert

            eventHandler.Verify(h => h.Handle(applicationEvent), Times.Once);

            container.Verify(c => c.BeginLifetimeScope(), Times.Never);
        }
예제 #15
0
        public void Publish(IApplicationEvent applicationEvent)
        {
            var factory = new ConnectionFactory();

            IConnection conn = factory.CreateConnection(); //uses defaults

            using (IModel channel = conn.CreateModel()) {
                channel.ExchangeDeclare("ContactUpdate", ExchangeType.Direct);
                channel.QueueDeclare("BarcelonaQueue", false, false, false, null);
                channel.QueueBind("BarcelonaQueue", "ContactUpdate", "", null);
                IBasicProperties props = channel.CreateBasicProperties();
                string           json  = JsonConvert.SerializeObject(applicationEvent, Formatting.None);

                byte[] messageBodyBytes = Encoding.UTF8.GetBytes(json);
                channel.BasicPublish("ContactUpdate", "", props, messageBodyBytes);
            }
        }
예제 #16
0
        public void Publish(IApplicationEvent applicationEvent)
        {
            using (var sqlConnection = new SqlConnection(ConnectionString))
            {
                sqlConnection.Open();
                using (var sqlTransaction = sqlConnection.BeginTransaction())
                {
                    var conversationHandle = ServiceBrokerWrapper.BeginConversation(sqlTransaction, SchedulerService, NotifierService, Contract);

                    string json = JsonConvert.SerializeObject(applicationEvent, Formatting.None);

                    ServiceBrokerWrapper.Send(sqlTransaction, conversationHandle, MessageType, ServiceBrokerWrapper.GetBytes(json));

                    ServiceBrokerWrapper.EndConversation(sqlTransaction, conversationHandle);

                    sqlTransaction.Commit();
                }
                sqlConnection.Close();
            }
        }
예제 #17
0
        internal void Append(IApplicationEvent eventInfo, IEntity record)
        {
            string description;

            if (eventInfo.Event == "Delete")
            {
                description = "Deleted {0} '{1}'".FormatWith(record.GetType().Name, record.ToString());
            }
            else if (eventInfo.Event == "Insert")
            {
                description = "Inserted {0} '{1}'".FormatWith(record.GetType().Name, record.ToString());
            }
            else if (eventInfo.Event == "Update")
            {
                description = "Update {0} '{1}':".FormatWith(record.GetType().Name, record.ToString());

                if (eventInfo.Data.HasValue())
                {
                    foreach (var child in GetOldDataNode(eventInfo).Elements())
                    {
                        var property = child.Name.LocalName;

                        if (property == "IsCodeDirty")
                        {
                            continue;
                        }

                        var oldValue = child.Value;
                        var newValue = EntityManager.ReadProperty(record, property).ToStringOrEmpty();

                        description += property + " changed from '{0}' to '{1}' | ".FormatWith(oldValue, newValue);
                    }
                }
            }
            else
            {
                throw new NotSupportedException();
            }

            Operations.Insert(0, new KeyValuePair <IApplicationEvent, string>(eventInfo, description.TrimEnd(" | ")));
        }
        /// <summary>
        ///     Delegates the event and dispatches to all event handlers that subscribes to <see cref="IApplicationEvent" />.
        /// </summary>
        /// <param name="applicationEvent">Event to be dispatched.</param>
        public void Dispatch(IApplicationEvent applicationEvent)
        {
            Guard.ArgumentIsNotNull(applicationEvent, nameof(applicationEvent));

            var handlerType = typeof (IApplicationEventHandler<>).MakeGenericType(applicationEvent.GetType());
            dynamic handlers = _container.GetAllInstances(handlerType);

            foreach (var handler in handlers)
            {
                Task.Factory.StartNew(() =>
                {
                    try
                    {
                        handler.Handle((dynamic) applicationEvent);
                    }
                    catch
                    {
                        // supression of event handler exceptions
                    }
                });
            }
        }
        public void Handle_HasNoCurrentLifetimeScope_ShouldBeginNewLifetimeScopeBeforeHandleEvent(
            [Frozen] Mock<IContainer> container,
            [Frozen] Mock<IApplicationEventHandler<IApplicationEvent>> eventHandler,
            IApplicationEvent applicationEvent,
            ApplicationEventLifetimeScopeDecorator<IApplicationEvent> decorator)
        {
            // Arrange

            var callOrder = 0;

            container.Setup(c => c.GetCurrentLifetimeScope()).Returns(null);
            container.Setup(c => c.BeginLifetimeScope()).Callback(() => callOrder++.Should().Be(0));
            eventHandler.Setup(c => c.Handle(applicationEvent)).Callback(() => callOrder++.Should().Be(1));

            // Act

            decorator.Handle(applicationEvent);

            // Assert

            container.Verify(c => c.BeginLifetimeScope(), Times.Once);

            eventHandler.Verify(h => h.Handle(applicationEvent), Times.Once);
        }
예제 #20
0
        static XElement GetOldDataNode(IApplicationEvent operation)
        {
            var node = XElement.Parse(operation.Data);

            return(node.Element("old") ?? node);
        }
예제 #21
0
 /// <summary>
 /// Loads the item recorded in this event.
 /// </summary>
 public static IEntity LoadItem(this IApplicationEvent applicationEvent)
 {
     return(CurrentApplicationEventManager.LoadItem(applicationEvent));
 }
예제 #22
0
        public async Task PublishAsync(IApplicationEvent applicationEvent)
        {
            logger.LogInformation("Event published: {EventType}", applicationEvent.GetType());

            await Task.CompletedTask;
        }
예제 #23
0
 public async Task PublishAsync(IApplicationEvent @event)
 {
     await _mediator.Publish(@event);
 }
예제 #24
0
 public ProjectApplicationEvent(Guid correlationId, IApplicationEvent @event)
 {
     CorrelationId = correlationId;
     Event         = @event;
 }
예제 #25
0
 public void Publish(IApplicationEvent applicationEvent)
 {
     throw new NotImplementedException();
 }
예제 #26
0
 private void GetGlobalWebModelApplicationEventHandler(IApplicationEvent applicationEvent)
 {
     var data = (GetGlobalWebModelApplicationEvent)applicationEvent;
     data.GlobalWebModel = _mockDataService.ReadObject(GetGlobalModel, MockFileName.GlobalModel, data.CallerContext);
 }
예제 #27
0
 public void Publish(IApplicationEvent applicationEvent)
 {
     #warning Implement publishing applicationEvent to a messaging queue.
     #warning Send event to queue as JSON.
 }
예제 #28
0
 private void PublishAppEvent(IApplicationEvent @event)
 {
     _publisher.Publish(@event);
 }
예제 #29
0
 public Project(Guid id, IApplicationEvent @event)
 {
     Id    = id;
     Event = @event;
 }
예제 #30
0
 protected virtual void Save(IApplicationEvent eventInfo) => Database.Save(eventInfo);
예제 #31
0
 /// <summary>
 /// Loads the item recorded in this event.
 /// </summary>
 public static async Task <IEntity> LoadItem(this IApplicationEvent applicationEvent) =>
 await CurrentApplicationEventManager.LoadItem(applicationEvent);
 public void Publish(IApplicationEvent @event)
 {
     _bus.Publish(@event, @event.GetType());
 }
예제 #33
0
 protected virtual Task Save(IApplicationEvent eventInfo) => Entity.Database.Save(eventInfo);