예제 #1
0
 public EventExecutionContext(WorkflowContext workflowContext, IEvent @event, EventConfiguration eventConfiguration, StateEventConfiguration stateEventConfiguration)
 {
     Event = @event;
     EventConfiguration      = eventConfiguration;
     StateEventConfiguration = stateEventConfiguration;
     WorkflowContext         = workflowContext;
 }
예제 #2
0
 public void TestRoundtrip()
 {
     using (var data = new MemoryStream())
     {
         var @event = new EventConfiguration
         {
             Name             = "My custom event",
             FilterExpression = "%d"
         };
         using (var writer = XmlWriter.Create(data))
         {
             writer.WriteStartElement("Test");
             @event.Save(writer);
             writer.WriteEndElement();
         }
         data.Position = 0;
         using (var reader = XmlReader.Create(data))
         {
             var actualEvent = new EventConfiguration();
             reader.MoveToContent();
             actualEvent.Restore(reader);
             actualEvent.Name.Should().Be("My custom event");
             actualEvent.FilterExpression.Should().Be("%d");
         }
     }
 }
예제 #3
0
        public IListener StartListening <TEvent, THandler>(EventConfiguration configuration = null)
            where TEvent : Event
            where THandler : IHandler <TEvent>
        {
            if (_eventBusInitializer.IsSuccessfullyInitialized <TEvent>())
            {
                ListenToInternal <TEvent, THandler>();
            }

            if (configuration == null)
            {
                configuration = new DefaultEventConfiguration();
            }

            var setupTask = _eventBusInitializer.SetupMessageBusWithSnsAndSqs <TEvent>(configuration);

            setupTask.Wait();

            if (setupTask.Result)
            {
                ListenToInternal <TEvent, THandler>();
            }

            return(this);
        }
예제 #4
0
        public async Task <bool> PublishAsync <TEvent>(TEvent content, EventConfiguration configuration = null) where TEvent : Event
        {
            var channel = AblyRealtime.Channels.Get(content.ChannelName);

            _logger.Info($"Publishing event {typeof(TEvent)}", content);

            try
            {
                var result = await channel.PublishAsync(new Message
                {
                    Data = content
                });

                if (result.IsFailure)
                {
                    _logger.Error($"Failed to publish event {typeof(TEvent)}", nameof(TEvent), content, result.Error.Message);
                }

                return(result.IsSuccess);
            }
            catch (Exception exception)
            {
                _logger.Error($"Failed to publish event {typeof(TEvent)}", nameof(TEvent), content, exception.ToString());
                return(false);
            }
        }
        private EventConfiguration GetEventConfigurationFromForm(int userId, CurrentConfig config)
        {
            var eventConfig = new EventConfiguration
            {
                PropertyId         = config.PropertyId,
                PropertyOperator   = config.PropertyOperator,
                PropertyValue      = config.PropertyValue,
                Operator           = config.Operator,
                ResultValue        = Convert.ToInt32(config.ResultValue),
                Function           = config.Function,
                Period             = Convert.ToInt32(config.Period),
                UserId             = userId,
                Template           = config.Template,
                TemplateProperties = EventConfigurationHelper.ConvertTemplatePropertiesFromNamesToIds(config.TemplateProperties),
                Category           = string.Empty,
                CategoryId         = 0
            };

            if (!IsNewConfiguration(config.Id))
            {
                eventConfig.Id = Convert.ToInt32(config.Id);
            }

            return(eventConfig);
        }
예제 #6
0
        public static string FormatEventToString(EventConfiguration config)
        {
            var propertyName = DataConfigurationHelper.GetPropertyName(config.PropertyId);

            return(string.Format("{0}({1} {2} {3}) {4} {5}",
                                 config.Function, propertyName, config.PropertyOperator, config.PropertyValue, config.Operator, config.ResultValue));
        }
예제 #7
0
 public EventExecutor(Type stateType, Type eventType, EventConfiguration configuration)
 {
     _configuration = configuration;
     _stateType     = stateType;
     _eventType     = eventType;
     _stateDistance = stateType.DistanceFrom(configuration.StateType);
     _eventDistance = eventType.DistanceFrom(configuration.EventType);
 }
예제 #8
0
 private async Task <string> GetQueueUrl(string queueName, EventConfiguration configuration)
 {
     if (!await _sqsOperations.QueueExists(queueName))
     {
         return(await _sqsOperations.CreateQueue(queueName, configuration));
     }
     return(await _sqsOperations.GetQueueUrl(queueName));
 }
예제 #9
0
 public static void DeleteConfiguration(EventConfiguration config)
 {
     using (var session = Connector.OpenSession())
         using (var transaction = session.BeginTransaction())
         {
             session.Delete(config);
             transaction.Commit();
         }
 }
        public BlobEventRepository(EventConfiguration configuration, ILoggerWrapper logger)
        {
            _configuration = configuration;
            _logger        = logger;

            var storageAccount = CloudStorageAccount.Parse(configuration.StorageConnectionString);
            var blobClient     = storageAccount.CreateCloudBlobClient();

            _container = blobClient.GetContainerReference(configuration.StorageContainerName);
        }
예제 #11
0
        /// <summary>
        ///     TODO The crete json event configuration template.
        /// </summary>
        /// <param name="eventObject">
        ///     TODO The bubbling event.
        /// </param>
        /// <returns>
        ///     The <see cref="string" />.
        /// </returns>
        public static string CreteJsonEventConfigurationTemplate(IEventAssembly eventObject)
        {
            try
            {
                var eventConfiguration = new EventConfiguration();
                eventConfiguration.Event = new Event(
                    eventObject.Id,
                    "{Configuration ID to execute}",
                    eventObject.Name,
                    eventObject.Description);

                eventConfiguration.Event.EventProperties = new List <EventProperty>();
                foreach (var Property in eventObject.Properties)
                {
                    if (Property.Value.Name != "DataContext")
                    {
                        var eventProperty = new EventProperty(Property.Value.Name, "Value to set");
                        eventConfiguration.Event.EventProperties.Add(eventProperty);
                    }
                }

                var eventCorrelationTemplate = new Event(
                    "{Event component ID to execute if Correlation = true}",
                    "{Configuration ID to execute if Correlation = true}",
                    "EventName",
                    "EventDescription");
                eventCorrelationTemplate.Channels = new List <Channel>();
                var points = new List <Point>();
                points.Add(new Point("Point ID", "Point Name", "Point Description"));
                eventCorrelationTemplate.Channels.Add(
                    new Channel("Channel ID", "Channel Name", "Channel Description", points));

                var events = new List <Event>();
                events.Add(eventCorrelationTemplate);
                eventConfiguration.Event.Channels = new List <Channel>();
                eventConfiguration.Event.Channels.Add(
                    new Channel("Channel ID", "Channel Name", "Channel Description", points));

                eventConfiguration.Event.Correlation = new Correlation("Correlation Name", "C# script", events);

                var serializedMessage = JsonConvert.SerializeObject(
                    eventConfiguration,
                    Formatting.Indented,
                    new JsonSerializerSettings {
                    ReferenceLoopHandling = ReferenceLoopHandling.Ignore
                });
                return(serializedMessage);

                // return "<![CDATA[" + serializedMessage + "]]>";
            }
            catch (Exception ex)
            {
                return(ex.Message);
            }
        }
        public Database.Models.Data GetSmartResult(ISession session, EventConfiguration config, string ip)
        {
            var         property = session.Query <DataPropertiesConfiguration>().First(x => x.Id == config.PropertyId);
            IList <int> query;

            if ((PropertyType)property.TypeId == PropertyType.Int || (PropertyType)property.TypeId == PropertyType.DateTime)
            {
                config.Function = "max";
                var max = GetEventConditionResult(session, config, ip);

                config.Function = "min";
                var min = GetEventConditionResult(session, config, ip);

                query = session.CreateSQLQuery(string.Format(
                                                   @"select 
                        d.id
                    from
                        pgdb.data as d
                    inner join
                        pgdb.data_property as dp
                    on
                        d.id = dp.data_id
                    where
                        d.category = {0} and
                        dp.property_id = {1} and
                        dp.value between {2} and {3};",
                                                   config.Category, config.PropertyId, min, max))
                        .AddEntity(typeof(int)).List <int>();
            }
            else
            {
                query = session.CreateSQLQuery(string.Format(
                                                   @"select 
                        d.id
                    from
                        pgdb.data as d
                    inner join
                        pgdb.data_property as dp
                    on
                        d.id = dp.data_id
                    where
                        d.category = {0} and
                        dp.property_id = {1} and
                        dp.value = {2}",
                                                   config.Category, config.PropertyId, config.PropertyValue))
                        .AddEntity(typeof(int)).List <int>();
            }

            var random = new Random();
            var index  = random.Next(query.Count);
            var id     = query[index];

            return(session.Query <Database.Models.Data>().First(x => x.Id == id));
        }
        private CurrentConfig GetCurrentConfig(EventConfiguration config, int userId)
        {
            var operators = new List <string>()
            {
                "=", "<", ">"
            };
            var functions = new List <string>()
            {
                "SUM", "AVG", "COUNT"
            };
            var properties = DataConfigurationHelper.GetUserDataProperties(userId);

            return(new CurrentConfig
            {
                Id = config.Id.ToString(),
                PropertyId = config.PropertyId,
                PropertyList =
                    properties.Select(x => new SelectListItem
                {
                    Text = x.Name,
                    Value = x.Id.ToString(),
                    Selected = x.Id == config.PropertyId
                }),
                PropertyOperator = config.PropertyOperator,
                PropertyOperatorList =
                    operators.Select(x => new SelectListItem
                {
                    Text = x,
                    Value = x,
                    Selected = x == config.PropertyOperator
                }),
                PropertyValue = config.PropertyValue,
                Operator = config.Operator,
                OperatorList =
                    operators.Select(x => new SelectListItem
                {
                    Text = x,
                    Value = x,
                    Selected = x == config.Operator
                }),
                ResultValue = config.ResultValue.ToString(),
                Function = config.Function,
                FunctionList =
                    functions.Select(x => new SelectListItem
                {
                    Text = x,
                    Value = x,
                    Selected = x == config.Function
                }),
                Period = config.Period.ToString(),
                Template = config.Template,
                TemplateProperties = EventConfigurationHelper.ConvertTemplatePropertiesFromIdsToNames(config.TemplateProperties)
            });
        }
예제 #14
0
        public void TestRoundtrip()
        {
            var config = new EventConfiguration
            {
                Name             = "My custom event",
                FilterExpression = "%d"
            };
            var actualConfig = config.Roundtrip();

            actualConfig.Name.Should().Be("My custom event");
            actualConfig.FilterExpression.Should().Be("%d");
        }
        public string ParseTemplate(ISession session, EventConfiguration config, Database.Models.Data data)
        {
            var configProperties = session.Query <EventConfigurationProperty>().Where(x => x.EventConfigurationId == config.Id);

            foreach (var configProperty in configProperties)
            {
                var property = session.Query <DataProperty>().First(x => x.PropertyId == configProperty.PropertyId);

                config.Template.Replace(string.Format("{{0}}", configProperty.Position), property.Value);
            }

            return(config.Template);
        }
            public IEventConfigurator <TActualState, TActualEvent> On <TActualState, TActualEvent>()
                where TActualState : TState
                where TActualEvent : TEvent
            {
                var eventMap  = _events;
                var stateType = typeof(TActualState);
                var eventType = typeof(TActualEvent);
                var eventKey  = new EventKey(stateType, eventType);
                var eventList = eventMap.TryGet(eventKey, TryGetMode.GetOrCreate, _ => new List <EventConfiguration>());
                var eventData = new EventConfiguration(stateType, eventType);

                eventList.Add(eventData);
                return(new EventConfigurator <TActualState, TActualEvent>(eventData));
            }
예제 #17
0
        public static void RegisterServices(IServiceCollection services)
        {
            ContextConfiguration.Register(services);
            BusConfiguration.Register(services);
            EventConfiguration.Register(services);
            ValidationConfiguration.Register(services);
            HandlerConfiguration.Register(services);
            ServiceConfiguration.Register(services);
            RepositoryConfiguration.Register(services);

            // Infra - Identity Services
            //services.AddTransient<IEmailSender, AuthEmailMessageSender>();
            //services.AddTransient<ISmsSender, AuthSMSMessageSender>();

            // Infra - Identity
            //services.AddScoped<IUser, AspNetUser>();
        }
 private void Reload()
 {
     _customSituations = _xmlWrapper.GetCustomSituations();
     _VxSettings       = _xmlWrapper.GetVideoXpertSettings();
     if ((_VxSettings != null) && (_VxSettings.IsChanged()))
     {
         _xmlWrapper.SaveVideoXpertSettings(_VxSettings);
     }
     _AxSettings = _xmlWrapper.GetACSSettings();
     if ((_AxSettings != null) && (_AxSettings.IsChanged()))
     {
         _xmlWrapper.SaveACSSettings(_AxSettings);
     }
     _eventConfiguration = _xmlWrapper.GetEventConfiguration();
     _acServerSettings   = _xmlWrapper.GetAccessControlServerSettings();
     _cameraAssociations = _xmlWrapper.GetCameraAssociations();
     _scripts            = _xmlWrapper.GetScripts();
 }
예제 #19
0
        public async Task <bool> PublishAsync <TEvent>(TEvent content, EventConfiguration configuration = null) where TEvent : Event
        {
            if (_eventBusInitializer.IsSuccessfullyInitialized <TEvent>())
            {
                return(await PublishInternalAsync(content));
            }

            if (configuration == null)
            {
                configuration = new DefaultEventConfiguration();
            }

            if (await _eventBusInitializer.SetupMessageBusWithSnsAndSqs <TEvent>(configuration))
            {
                return(await PublishInternalAsync(content));
            }

            return(false);
        }
예제 #20
0
        public async Task <string> CreateQueue(string name, EventConfiguration configuration)
        {
            var createQueueRequest = new CreateQueueRequest
            {
                QueueName  = name,
                Attributes =
                {
                    { "ReceiveMessageWaitTimeSeconds", $"{configuration.ReceiveMessageWaitTimeSeconds}" },
                    { "MessageRetentionPeriod",        $"{configuration.MessageRetentionPeriodSeconds}" }
                }
            };

            var createQueueResponse = await _client.CreateQueueAsync(createQueueRequest);

            if (createQueueResponse.HttpStatusCode != HttpStatusCode.OK)
            {
                _logger.Error($"Could not create queue {name}", createQueueResponse.HttpStatusCode);
            }

            return(createQueueResponse.QueueUrl);
        }
        public int GetEventConditionResult(ISession session, EventConfiguration config, string ip)
        {
            var query = session.CreateSQLQuery(string.Format(
                                                   @"select 
                        {0}(dp.value)
                    from
                        pgdb.data as d
                    inner join
                        pgdb.data_property as dp
                    on
                        d.id = dp.data_id
                    where
                        d.user_id = {1} and
                        d.ip = {2} and
                        d.category = {3} and
                        dp.property_id = {4} and
                        dp.value {5} {6};",
                                                   config.Function, config.UserId, ip, config.Category, config.PropertyId, config.PropertyOperator, config.PropertyValue))
                        .AddEntity(typeof(int));

            return(query.List <int>().First());
        }
예제 #22
0
        public IListener StartListening <TEvent, THandler>(EventConfiguration configuration)
            where TEvent : Event
            where THandler : IHandler <TEvent>
        {
            var handler = GetHandler <TEvent>();

            if (handler == default(IHandler <TEvent>))
            {
                Logger.Warn($"No handler that implements {typeof(IHandler<TEvent>)} was found for the event {typeof(TEvent)}");
                return(this);
            }

            var @event  = GetEvent <TEvent>();
            var channel = AblyRealtime.Channels.Get(@event.ChannelName);

            channel.Subscribe(async(m) =>
            {
                await handler.HandleAsync(JsonConvert.DeserializeObject <TEvent>(m.Data.ToString()));
            });

            return(this);
        }
예제 #23
0
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove <OneToManyCascadeDeleteConvention>();

            modelBuilder.Entity <IdentityUser>().ToTable("AspNetUsers");

            EntityTypeConfiguration <ApplicationUser> table =
                modelBuilder.Entity <ApplicationUser>().ToTable("AspNetUsers");

            table.Property((ApplicationUser u) => u.UserName).IsRequired();

            modelBuilder.Entity <ApplicationUser>().HasMany <IdentityUserRole>((ApplicationUser u) => u.Roles);
            modelBuilder.Entity <IdentityUserRole>().HasKey((IdentityUserRole r) =>
                                                            new { UserId = r.UserId, RoleId = r.RoleId }).ToTable("AspNetUserRoles");

            EntityTypeConfiguration <IdentityUserLogin> entityTypeConfiguration =
                modelBuilder.Entity <IdentityUserLogin>().HasKey((IdentityUserLogin l) =>
                                                                 new
            {
                UserId        = l.UserId,
                LoginProvider = l.LoginProvider,
                ProviderKey
                    = l.ProviderKey
            }).ToTable("AspNetUserLogins");

            modelBuilder.Entity <IdentityRole>().ToTable("AspNetRoles");

            EntityTypeConfiguration <ApplicationRole> entityTypeConfiguration1 = modelBuilder.Entity <ApplicationRole>().ToTable("AspNetRoles");

            entityTypeConfiguration1.Property((ApplicationRole r) => r.Name).IsRequired();
            //Entities Configurations
            //Ivoice Material
            var invoice_material_config = new TournamentConfiguration(modelBuilder);
            //Invoice Equipemnt
            var invoice_equipemnt_config = new EventConfiguration(modelBuilder);

            //var eventdetails_config = new EventDetailsConfiguration(modelBuilder);
        }
예제 #24
0
        public async Task <bool> SetupMessageBusWithSnsAndSqs <TEvent>(EventConfiguration configuration) where TEvent : Event
        {
            var @event = (Event)Activator.CreateInstance <TEvent>();

            var snsTopicName = EventUtils.GetTopicName(@event);
            var queueName    = EventUtils.GetQueueName(@event);

            var snsTopicArn = await GetTopicArn(snsTopicName);

            var queueUrl = await GetQueueUrl(queueName, configuration);

            var isSuccessfullyInitialized = await LinkTopicToQueue(snsTopicArn, queueUrl);

            _events.Add(new MessagingInitializerModel
            {
                TopicArn  = snsTopicArn,
                EventType = typeof(TEvent),
                IsSuccessfullyInitialized = isSuccessfullyInitialized,
                QueueUrl          = queueUrl,
                CancellationToken = new CancellationTokenSource()
            });

            return(isSuccessfullyInitialized);
        }
예제 #25
0
 public new static void RegisterDeviceEventConfigurations()
 {
     EventConfiguration   eventConfiguration   = new EventConfiguration("geolocation", typeof(DeviceEventGeo));
     MessageConfiguration messageConfiguration = new MessageConfiguration("geolocation");
 }
 public EventConfigurator(EventConfiguration configuration)
 {
     _configuration = configuration;
 }
        public bool CheckEvent(ISession session, EventConfiguration config, string ip)
        {
            var value = GetEventConditionResult(session, config, ip);

            return(IsResultCorrect(value, config.ResultValue, config.Operator) ? true : false);
        }