Exemplo n.º 1
0
 public IEnumerable <string> HasSubject(ISenderConfiguration configuration, SenderRequest request)
 {
     if (!configuration.AllowEmptySubject && string.IsNullOrWhiteSpace(request.Subject))
     {
         yield return("Message subject cannot be empty");
     }
 }
Exemplo n.º 2
0
 public IEnumerable <string> HasBody(ISenderConfiguration configuration, SenderRequest request)
 {
     if (!configuration.AllowEmptyBody && string.IsNullOrWhiteSpace(request.Body))
     {
         yield return("Message body cannot be empty");
     }
 }
 public InfluxDataSender(ISenderConfiguration senderConfiguration)
 {
     _myLogger            = new MyLogger();
     _senderConfiguration = senderConfiguration;
     _dropOnFail          = false;
     _client = new Lazy <IInfluxDbAgent>(() => new InfluxDbAgent(senderConfiguration.Properties.Url, senderConfiguration.Properties.DatabaseName, senderConfiguration.Properties.UserName, senderConfiguration.Properties.Password, senderConfiguration.Properties.RequestTimeout));
 }
Exemplo n.º 4
0
 public InfluxDataSender(ISenderConfiguration senderConfiguration)
 {
     _myLogger = new MyLogger();
     _senderConfiguration = senderConfiguration;
     _dropOnFail = false;
     _client = new Lazy<IInfluxDbAgent>(() => new InfluxDbAgent(senderConfiguration.Properties.Url, senderConfiguration.Properties.DatabaseName, senderConfiguration.Properties.UserName, senderConfiguration.Properties.Password, senderConfiguration.Properties.RequestTimeout));
 }
Exemplo n.º 5
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RabbitSender"/> class.
        /// </summary>
        /// <param name="bus">
        /// A reference to the bus containing the sender
        /// </param>
        /// <param name="configuration">
        /// Конфигурация отправителя сообщений.
        /// </param>
        /// <param name="connectionPool">
        /// A bus connection pool
        /// </param>
        /// <param name="filters">
        /// Фильтры сообщений.
        /// </param>
        public RabbitSender(RabbitBus bus, ISenderConfiguration configuration, IConnectionPool <IRabbitConnection> connectionPool, IEnumerable <IMessageExchangeFilter> filters, IDictionary <Type, IMessageExchangeFilterDecorator> filterDecorators = null)
            : base(bus.Endpoint, configuration, filters, filterDecorators)
        {
            this.bus            = bus;
            this.connectionPool = connectionPool;
            this.senderOptions  = (RabbitSenderOptions)this.Configuration.Options;

            this.logger = LogManager.GetLogger($"{this.GetType().FullName}({this.bus.Endpoint}, {this.Configuration.Label})");
        }
Exemplo n.º 6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RabbitSender"/> class.
        /// </summary>
        /// <param name="bus">
        /// A reference to the bus containing the sender
        /// </param>
        /// <param name="configuration">
        /// Конфигурация отправителя сообщений.
        /// </param>
        /// <param name="connectionPool">
        /// A bus connection pool
        /// </param>
        /// <param name="filters">
        /// Фильтры сообщений.
        /// </param>
        public RabbitSender(RabbitBus bus, ISenderConfiguration configuration, IConnectionPool <IRabbitConnection> connectionPool, IEnumerable <IMessageExchangeFilter> filters)
            : base(bus.Endpoint, configuration, filters)
        {
            this.bus            = bus;
            this.connectionPool = connectionPool;
            this.senderOptions  = (RabbitSenderOptions)this.Configuration.Options;

            this.logger = LogManager.GetLogger($"{this.GetType().FullName}(Endpoint=\"{this.bus.Endpoint}\")");
        }
Exemplo n.º 7
0
        // TODO: refactor, don't copy filters

        /// <summary>
        /// Initializes a new instance of the <see cref="AbstractSender"/> class.
        /// </summary>
        /// <param name="endpoint">
        /// Sender's endpoint
        /// </param>
        /// <param name="configuration">
        /// Sender's configuration
        /// </param>
        /// <param name="filters">
        /// A list of message handling filters
        /// </param>
        protected AbstractSender(IEndpoint endpoint, ISenderConfiguration configuration, IEnumerable <IMessageExchangeFilter> filters)
        {
            this.endpoint        = endpoint;
            this.breadCrumbsTail = ";" + endpoint.Address;

            this.filters = new SendingExchangeFilter(this.InternalSend)
                           .ToEnumerable()
                           .Union(filters)
                           .ToList();

            this.Configuration = configuration;
        }
Exemplo n.º 8
0
        /// <summary>
        /// Registers a sender using <paramref name="configuration"/>
        /// </summary>
        /// <param name="configuration">
        /// Sender configuration
        /// </param>
        /// <returns>
        /// The <see cref="RabbitSender"/>.
        /// </returns>
        public RabbitSender RegisterSender(ISenderConfiguration configuration)
        {
            this.logger.Trace(
                $"Registering a new sender of [{configuration.Label}] with connection string [{configuration.Options.GetConnectionString()}]");

            var sender = new RabbitSender(this, configuration, this.connectionPool, this.Configuration.Filters.ToList());

            this.ComponentTracker.Register(sender);

            this.logger.Trace(
                $"A sender of [{configuration.Label}] with connection string [{configuration.Options.GetConnectionString()}] registered successfully");

            return(sender);
        }
Exemplo n.º 9
0
        public void Validate(ISenderConfiguration configuration, SenderRequest request)
        {
            var results = new[]
            {
                HasSubject(configuration, request),
                HasBody(configuration, request),
            };

            var errorMessages = results.SelectMany(m => m);

            if (errorMessages.Any())
            {
                throw new InvalidSenderRequestException(errorMessages);
            }
        }
Exemplo n.º 10
0
        private string?GetMessageBody(ISenderConfiguration configuration, SenderRequest request)
        {
            if (configuration.TemplateType == null)
            {
                return(request.Body);
            }

            var templateApplicator = _templateApplicators.FirstOrDefault(a => a.Supports(configuration));

            if (templateApplicator == null)
            {
                throw new NotSupportedException($"Template type {configuration.TemplateType} is not supported");
            }

            return(templateApplicator.Apply(configuration, request));
        }
Exemplo n.º 11
0
        public string Apply(ISenderConfiguration configuration, SenderRequest request)
        {
            if (string.IsNullOrWhiteSpace(configuration.Template))
            {
                throw new MissingTemplateExcpetion(configuration.Id);
            }

            if (string.IsNullOrWhiteSpace(request.Body))
            {
                return(string.Empty);
            }

            var template = HandlebarsDotNet.Handlebars.Compile(configuration.Template);
            var data     = JsonConvert.DeserializeObject(request.Body);

            return(template(data));
        }
Exemplo n.º 12
0
        public MailGeneratorService(
            IMailQueue queue = null,
            IDataStore dataStore = null,
            Func<Template, IRenderer> rendererFactory = null,
            IDataDecorator[] decorators = null,
            IReceiverMapper receiverMapper = null,
            ISenderConfiguration senderConfiguration = null,
            IConfiguration configuration = null,
            IHttpClient httpClient = null,
            IMailSenderService mailSenderService = null,
            bool? async = null)
        {
            m_queue = queue ?? new InMemoryMailQueue();

            IConfiguration configuration1 = configuration ?? new DefaultConfiguration();

            m_rendererFactory = rendererFactory ?? (t => new HandlebarsRenderer(t));
            m_decorators = decorators ?? new IDataDecorator[]
            {
                new RestResolvingDecorator(
                    httpClient ?? new JsonHttpClient(),
                    dataStore)
            };
            m_receiverMapper = receiverMapper ?? new DefaultReceiverMapper();
            m_senderConfiguration = senderConfiguration ??
                new DefaultSenderConfiguration(
                    configuration1);

            m_asyncActive = async.HasValue ? async.Value : StringToBoolUtil.Interpret(configuration1.GetValue(APP_KEY_ASYNCACTIVE));

            if (!m_asyncActive && mailSenderService == null)
            {
                m_mailSenderService = new MailSenderService(m_queue);
            }
            else
            {
                m_mailSenderService = mailSenderService;
            }
        }
Exemplo n.º 13
0
        public MailGeneratorService(
            IMailQueue queue     = null,
            IDataStore dataStore = null,
            Func <Template, IRenderer> rendererFactory = null,
            IDataDecorator[] decorators              = null,
            IReceiverMapper receiverMapper           = null,
            ISenderConfiguration senderConfiguration = null,
            IConfiguration configuration             = null,
            IHttpClient httpClient = null,
            IMailSenderService mailSenderService = null,
            bool?async = null)
        {
            m_queue = queue ?? new InMemoryMailQueue();

            IConfiguration configuration1 = configuration ?? new DefaultConfiguration();

            m_rendererFactory = rendererFactory ?? (t => new HandlebarsRenderer(t));
            m_decorators      = decorators ?? new IDataDecorator[]
            {
                new RestResolvingDecorator(
                    httpClient ?? new JsonHttpClient(),
                    dataStore)
            };
            m_receiverMapper      = receiverMapper ?? new DefaultReceiverMapper();
            m_senderConfiguration = senderConfiguration ??
                                    new DefaultSenderConfiguration(
                configuration1);

            m_asyncActive = async.HasValue ? async.Value : StringToBoolUtil.Interpret(configuration1.GetValue(APP_KEY_ASYNCACTIVE));

            if (!m_asyncActive && mailSenderService == null)
            {
                m_mailSenderService = new MailSenderService(m_queue);
            }
            else
            {
                m_mailSenderService = mailSenderService;
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// The resolve for.
        /// </summary>
        /// <param name="configuration">
        /// The configuration.
        /// </param>
        /// <returns>
        /// The <see cref="Producer"/>.
        /// </returns>
        public Producer ResolveFor(ISenderConfiguration configuration)
        {
            Producer producer = this.TryResolverFor(configuration.Label);

            if (producer == null)
            {
                using (RabbitChannel channel = this._bus.OpenChannel())
                {
                    var topologyBuilder = new TopologyBuilder(channel);
                    var builder         = new RouteResolverBuilder(this._bus.Endpoint, topologyBuilder, configuration);
                    Maybe <Func <IRouteResolverBuilder, IRouteResolver> > routeResolverBuilder = configuration.Options.GetRouteResolverBuilder();

                    Assumes.True(routeResolverBuilder.HasValue, "RouteResolverBuilder must be set for [{0}]", configuration.Label);

                    IRouteResolver routeResolver = routeResolverBuilder.Value(builder);

                    producer         = new Producer(this._bus, configuration.Label, routeResolver, configuration.Options.IsConfirmationRequired());
                    producer.Failed += p =>
                    {
                        {
                            // lock (_producers)
                            p.Dispose();
                            this._producers.Remove(p.Label);
                        }
                    };

                    // lock (_producers)
                    this._producers.Add(configuration.Label, producer);
                }

                if (configuration.RequiresCallback)
                {
                    producer.UseCallbackListener(this._bus.ListenerRegistry.ResolveFor(configuration.CallbackConfiguration));
                }
            }

            return(producer);
        }
Exemplo n.º 15
0
        /// <summary>
        /// The resolve for.
        /// </summary>
        /// <param name="configuration">
        /// The configuration.
        /// </param>
        /// <returns>
        /// The <see cref="Producer"/>.
        /// </returns>
        public Producer ResolveFor(ISenderConfiguration configuration)
        {
            Producer producer = this.TryResolverFor(configuration.Label);
            if (producer == null)
            {
                using (RabbitChannel channel = this._bus.OpenChannel())
                {
                    var topologyBuilder = new TopologyBuilder(channel);
                    var builder = new RouteResolverBuilder(this._bus.Endpoint, topologyBuilder, configuration);
                    Maybe<Func<IRouteResolverBuilder, IRouteResolver>> routeResolverBuilder = configuration.Options.GetRouteResolverBuilder();

                    Assumes.True(routeResolverBuilder.HasValue, "RouteResolverBuilder must be set for [{0}]", configuration.Label);

                    IRouteResolver routeResolver = routeResolverBuilder.Value(builder);

                    producer = new Producer(this._bus, configuration.Label, routeResolver, configuration.Options.IsConfirmationRequired());
                    producer.Failed += p =>
                        {
                            {
                                // lock (_producers)
                                p.Dispose();
                                this._producers.Remove(p.Label);
                            }
                        };

                    // lock (_producers)
                    this._producers.Add(configuration.Label, producer);
                }

                if (configuration.RequiresCallback)
                {
                    producer.UseCallbackListener(this._bus.ListenerRegistry.ResolveFor(configuration.CallbackConfiguration));
                }
            }

            return producer;
        }
Exemplo n.º 16
0
 /// <summary>
 /// »нициализирует новый экземпл¤р класса <see cref="RouteResolverBuilder"/>.
 /// </summary>
 /// <param name="endpoint">
 /// The endpoint.
 /// </param>
 /// <param name="topology">
 /// The topology.
 /// </param>
 /// <param name="sender">
 /// The sender.
 /// </param>
 public RouteResolverBuilder(IEndpoint endpoint, ITopologyBuilder topology, ISenderConfiguration sender)
 {
     this.Endpoint = endpoint;
     this.Topology = topology;
     this.Sender   = sender;
 }
Exemplo n.º 17
0
 public SendCompleteEventArgs(ISenderConfiguration senderConfiguration, Exception exception)
 {
     _senderConfiguration = senderConfiguration;
     _exception = exception;
     Level = OutputLevel.Error;
 }
 /// <summary>
 /// Создает конечную точку для ответов с настройками по умолчанию
 /// </summary>
 /// <param name="senderConfiguration">Настройки отправителя.</param>
 /// <returns>Конечная точка подписки на сообщения.</returns>
 public ISubscriptionEndpoint UseDefaultTempReplyEndpoint(ISenderConfiguration senderConfiguration)
 {
     return this.Topology.BuildTempReplyEndpoint(this.Endpoint, senderConfiguration.Label);
 }
Exemplo n.º 19
0
 public InfluxDataSender(ISenderConfiguration senderConfiguration)
 {
     _senderConfiguration = senderConfiguration;
     _dropOnFail = false;
     _client = new Lazy<IInfluxDbAgent>(() => new InfluxDbAgent(senderConfiguration.Properties.Url, senderConfiguration.Properties.DatabaseName, senderConfiguration.Properties.UserName, senderConfiguration.Properties.Password));
 }
Exemplo n.º 20
0
 /// <summary>
 /// Инициализирует новый экземпляр класса <see cref="RabbitSender"/>.
 /// </summary>
 /// <param name="endpoint">Конечная точка, для которой создается отправитель.</param>
 /// <param name="configuration">Конфигурация отправителя сообщений.</param>
 /// <param name="producerRegistry">Реестр поставщиков сообщений.</param>
 /// <param name="filters">Фильтры сообщений.</param>
 public RabbitSender(IEndpoint endpoint, ISenderConfiguration configuration, ProducerRegistry producerRegistry, IEnumerable <IMessageExchangeFilter> filters)
     : base(endpoint, configuration, filters)
 {
     this.producerRegistry = producerRegistry;
 }
Exemplo n.º 21
0
 public bool Supports(ISenderConfiguration configuration) => TemplateType.Equals(configuration.TemplateType, StringComparison.InvariantCultureIgnoreCase);
 public SendCompleteEventArgs(ISenderConfiguration senderConfiguration, string message, int count, OutputLevel outputLevel)
 {
     _senderConfiguration = senderConfiguration;
     _message             = message;
     Level = outputLevel;
 }
 public SendCompleteEventArgs(ISenderConfiguration senderConfiguration, Exception exception)
 {
     _senderConfiguration = senderConfiguration;
     _exception           = exception;
     Level = OutputLevel.Error;
 }
Exemplo n.º 24
0
 protected AbstractSender(IEndpoint endpoint, ISenderConfiguration configuration, IEnumerable <IMessageExchangeFilter> filters, IDictionary <Type, IMessageExchangeFilterDecorator> filterDecorators)
     : this(endpoint, configuration, filters)
 {
     this.filterDecorators = filterDecorators;
 }
Exemplo n.º 25
0
 /// <summary>
 /// Инициализирует новый экземпляр класса <see cref="RabbitSender"/>.
 /// </summary>
 /// <param name="endpoint">Конечная точка, для которой создается отправитель.</param>
 /// <param name="configuration">Конфигурация отправителя сообщений.</param>
 /// <param name="producerRegistry">Реестр поставщиков сообщений.</param>
 /// <param name="filters">Фильтры сообщений.</param>
 public RabbitSender(IEndpoint endpoint, ISenderConfiguration configuration, ProducerRegistry producerRegistry, IEnumerable<IMessageExchangeFilter> filters)
     : base(endpoint, configuration, filters)
 {
     this.producerRegistry = producerRegistry;
 }
Exemplo n.º 26
0
 /// <summary>
 /// Инициализирует новый экземпляр класса <see cref="RouteResolverBuilder"/>.
 /// </summary>
 /// <param name="endpoint">
 /// The endpoint.
 /// </param>
 /// <param name="topology">
 /// The topology.
 /// </param>
 /// <param name="sender">
 /// The sender.
 /// </param>
 public RouteResolverBuilder(IEndpoint endpoint, ITopologyBuilder topology, ISenderConfiguration sender)
 {
     this.Endpoint = endpoint;
     this.Topology = topology;
     this.Sender = sender;
 }
Exemplo n.º 27
0
 public SendCompleteEventArgs(ISenderConfiguration senderConfiguration, string message, int count, OutputLevel outputLevel)
 {
     _senderConfiguration = senderConfiguration;
     _message = message;
     Level = outputLevel;
 }
Exemplo n.º 28
0
 public InfluxDataSender(ISenderConfiguration senderConfiguration)
 {
     _senderConfiguration = senderConfiguration;
     _dropOnFail          = false;
     _client = new Lazy <IInfluxDbAgent>(() => new InfluxDbAgent(senderConfiguration.Properties.Url, senderConfiguration.Properties.DatabaseName, senderConfiguration.Properties.UserName, senderConfiguration.Properties.Password));
 }
 /// <summary>
 /// Создает конечную точку для ответов с настройками по умолчанию
 /// </summary>
 /// <param name="senderConfiguration">Настройки отправителя.</param>
 /// <returns>Конечная точка подписки на сообщения.</returns>
 public ISubscriptionEndpoint UseDefaultTempReplyEndpoint(ISenderConfiguration senderConfiguration)
 {
     return(this.Topology.BuildTempReplyEndpoint(this.Endpoint, senderConfiguration.Label));
 }
Exemplo n.º 30
0
 public TestSender(Func <MessageExchange, Task <MessageExchange> > internalSend, IEndpoint endpoint, ISenderConfiguration configuration, IEnumerable <IMessageExchangeFilter> filters)
     : base(endpoint, configuration, filters)
 {
     this.internalSend = internalSend;
 }