예제 #1
0
        // ON EVENTS SUBSCRIBERS SECTION
        //---------------------------------------------------------------------

        #region  On events subscribers

        private void OnInitializeView()
        {
            try
            {
                _senderConfig = _senderConfigManager.Get();

                View.Host     = _senderConfig.Host;
                View.Port     = _senderConfig.Port;
                View.Login    = _senderConfig.SenderLogin;
                View.Password = _senderConfig.SenderPassword;

                if (_senderConfig.To.Length == 0)
                {
                    View.Error = "Can't load sender receivers";
                }
                else
                {
                    View.Receiver = _senderConfig.To[UserDefineReceiverIndex];
                }
            }
            catch (RepositoryLoadException ex)
            {
                _log.Error(ex.ToString());
                View.Error = "Не удалось загрузить настройки SMTP-клиента :" +
                             Environment.NewLine +
                             ex.Message;
            }
        }
예제 #2
0
        /// <summary>
        /// Считывает конфигурацию из app.config и записывает в <see cref="Conformation"/>.
        /// </summary>
        public static void Init()
        {
            // Подготовка объекта содержащего в себе ноду из файла app.config "GisServicesConfig".
            GisServiceConfiguration section = (GisServiceConfiguration)ConfigurationManager.GetSection("GisServicesConfig");

            // Подготовка объекта содержащего в себе ноду из файла app.config "signingConfig".
            SigningConfiguration sign = (SigningConfiguration)ConfigurationManager.GetSection("signingConfig");

            // Подготовка объекта содержащего в себе ноду из файла app.config "Sender".
            SenderConfiguration sender = (SenderConfiguration)ConfigurationManager.GetSection("Sender");

            // Подготовка объекта содержащего в себе ноду из файла app.config "General".
            GeneralConfiguration general = (GeneralConfiguration)ConfigurationManager.GetSection("General");

            // Заполнение структуры сведениями из конфиг файла.
            Сonformation conf = new Сonformation
            {
                login    = section.Login,
                password = section.Password,
                certificateThumbprint = sign.CertificateThumbprint,
                certificatePassword   = sign.CertificatePassword,

                RIRCorgPPAGUID = section.RIRCorgPPAGUID,
                baseUrl        = section.BaseUrl,
                //schemaVersion         = section.SchemaVersion, TODO удалить если всё норм. ТЕперь берём из базы.
                soapConfiguration = section.SoapConfiguration,
                IsTest            = Convert.ToBoolean(section.IsTest),
                sendTo            = sender.SendTo,
                timeInterval      = Convert.ToInt32(general.TimeInterval) * 60000,
                amountAttempt     = Convert.ToInt32(general.AmountAttempt)
            };

            conformation = conf;
        }
예제 #3
0
        public static IServiceCollection AddJaeger(this IServiceCollection services)
        {
            services.AddSingleton <ITracer>(serviceProvider =>
            {
                var loggerFactory = serviceProvider.GetRequiredService <ILoggerFactory>();

                var senderConfig = new SenderConfiguration(loggerFactory)
                                   .WithAgentHost(Environment.GetEnvironmentVariable("JAEGER_AGENT_HOST"))
                                   .WithAgentPort(Convert.ToInt32(Environment.GetEnvironmentVariable("JAEGER_AGENT_PORT")));

                SenderConfiguration.DefaultSenderResolver = new SenderResolver(loggerFactory)
                                                            .RegisterSenderFactory <ThriftSenderFactory>();

                var config = Configuration.FromEnv(loggerFactory);

                var samplerConfiguration = new SamplerConfiguration(loggerFactory)
                                           .WithType(ConstSampler.Type)
                                           .WithParam(1);

                var reporterConfiguration = new ReporterConfiguration(loggerFactory)
                                            .WithSender(senderConfig)
                                            .WithLogSpans(true);

                var tracer = config
                             .WithSampler(samplerConfiguration)
                             .WithReporter(reporterConfiguration)
                             .GetTracer();

                GlobalTracer.Register(tracer);

                return(tracer);
            });

            return(services);
        }
예제 #4
0
        private void LoadSenderConfiguration()
        {
            try
            {
                _senderConfig = _senderConfigManager.Get();

                View.SenderHost     = _senderConfig.Host;
                View.SenderPort     = _senderConfig.Port;
                View.SenderLogin    = _senderConfig.SenderLogin;
                View.SenderPassword = _senderConfig.SenderPassword;

                if (_senderConfig.To.Length == 0)
                {
                    View.Error = "Can't load sender receivers";
                }
                else
                {
                    View.SenderReceiver = _senderConfig.To[UserDefineReceiverIndex];
                }
            }
            catch (RepositoryLoadException ex)
            {
                _log.Error(ex.ToString());
                View.Error = "Error on sender configuration load :" +
                             Environment.NewLine +
                             ex.Message;
            }
        }
예제 #5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddSingleton <ITracer>(serviceProvider =>
            {
                string serviceName = Assembly.GetEntryAssembly().GetName().Name;

                ILoggerFactory loggerFactory = serviceProvider.GetRequiredService <ILoggerFactory>();

                var senderConfig = new SenderConfiguration(loggerFactory)
                                   .WithAgentHost("jaeger-agent")
                                   .WithAgentPort(5778)
                                   .WithEndpoint("http://collector:14268/api/traces");

                var reporter = new RemoteReporter.Builder().WithLoggerFactory(loggerFactory).WithSender(senderConfig.GetSender()).Build();

                ISampler sampler = new ConstSampler(sample: true);

                ITracer tracer = new Tracer.Builder(serviceName)
                                 .WithLoggerFactory(loggerFactory)
                                 .WithReporter(reporter)
                                 .WithSampler(sampler)
                                 .Build();

                GlobalTracer.Register(tracer);

                return(tracer);
            });

            services.AddOpenTracing();
        }
            /// <summary>
            /// Attempts to create a new <see cref="ReporterConfiguration"/> based on an IConfiguration.
            /// </summary>
            public static ReporterConfiguration FromIConfiguration(ILoggerFactory loggerFactory, IConfiguration configuration)
            {
                ILogger logger = loggerFactory.CreateLogger <Configuration>();

                return(new ReporterConfiguration(loggerFactory)
                       .WithLogSpans(GetPropertyAsBool(JaegerReporterLogSpans, logger, configuration).GetValueOrDefault(false))
                       .WithFlushInterval(GetPropertyAsTimeSpan(JaegerReporterFlushInterval, logger, configuration))
                       .WithMaxQueueSize(GetPropertyAsInt(JaegerReporterMaxQueueSize, logger, configuration))
                       .WithSender(SenderConfiguration.FromIConfiguration(loggerFactory, configuration)));
            }
예제 #7
0
        public SenderFactory(IOptions <SenderConfiguration> options)
        {
            _options = options.Value;

            _map = new Dictionary <string, ISender>()
            {
                { "email", new SendGridSender() },
                { "sms", new TwillioSender() },
                { "fcm", new FCMSender() }
            };
        }
 private SenderConfigurationTableEntity(string partitionKey, SenderConfiguration source)
     : base(partitionKey, source.Id.ToString())
 {
     Id                = source.Id;
     Name              = source.Name;
     ToEmail           = source.ToEmail;
     DefaultFromEmail  = source.DefaultFromEmail;
     AllowEmptySubject = source.AllowEmptySubject;
     AllowEmptyBody    = source.AllowEmptyBody;
     Template          = source.Template;
     TemplateType      = source.TemplateType;
 }
예제 #9
0
        /// <summary>
        /// The route.
        /// </summary>
        /// <param name="label">
        /// The label.
        /// </param>
        /// <returns>
        /// The <see cref="ISenderConfigurator"/>.
        /// </returns>
        /// <exception cref="ArgumentException">
        /// Raises an error if a sender for <paramref name="label"/> has already been registered
        /// </exception>
        public ISenderConfigurator Route(MessageLabel label)
        {
            if (this.HasRegisteredProducerFor(label))
            {
                throw new ArgumentException($"Sender for label [{label}] already registered.", nameof(label));
            }

            var configuration = new SenderConfiguration(label, this.SenderDefaults, this.ReceiverDefaults);

            this.senderConfigurations.Add(configuration);
            return(configuration);
        }
예제 #10
0
        public void Validate_WithBrokenRule_ShouldThrowInvalidSenderRequestException()
        {
            var configuration = new SenderConfiguration
            {
                AllowEmptySubject = false,
            };

            var request = new SenderRequest
            {
                Subject = null,
            };

            Assert.Throws <InvalidSenderRequestException>(() => _validator.Validate(configuration, request));
        }
예제 #11
0
        public void HasBody_ShouldNotReturnErrorMessage(bool allowEmptyBody, string?body)
        {
            var configuration = new SenderConfiguration
            {
                AllowEmptyBody = allowEmptyBody,
            };

            var request = new SenderRequest
            {
                Body = body,
            };

            var messages = _validator.HasBody(configuration, request);

            Assert.Empty(messages);
        }
예제 #12
0
        public void HasSubject_ShouldReturnErrorMessage(bool allowEmptySubject, string?subject)
        {
            var configuration = new SenderConfiguration
            {
                AllowEmptySubject = allowEmptySubject,
            };

            var request = new SenderRequest
            {
                Subject = subject,
            };

            var messages = _validator.HasSubject(configuration, request);

            Assert.NotEmpty(messages);
        }
예제 #13
0
        /// <summary>
        /// The route.
        /// </summary>
        /// <param name="label">
        /// The label.
        /// </param>
        /// <returns>
        /// The <see cref="ISenderConfigurator"/>.
        /// </returns>
        /// <exception cref="ArgumentException">
        /// Raises an error if a sender for <paramref name="label"/> has already been registered
        /// </exception>
        public ISenderConfigurator Route(MessageLabel label)
        {
            if (this.HasRegisteredProducerFor(label))
            {
                throw new ArgumentException($"Sender for label [{label}] already registered.", nameof(label));
            }

            var provider         = this.SenderDefaults.GetConnectionStringProvider();
            var connectionString = provider?.GetConnectionString(label);

            if (!string.IsNullOrEmpty(connectionString))
            {
                this.SenderDefaults.ConnectionString = connectionString;
            }

            var configuration = new SenderConfiguration(label, this.SenderDefaults, this.ReceiverDefaults);

            this.senderConfigurations.Add(configuration);
            return(configuration);
        }
예제 #14
0
        public Task Send_SendGridClientReturnsNonSuccessResponse_ShouldThrowMessageSendFailedException()
        {
            var senderConfiguration = new SenderConfiguration
            {
                Id               = Guid.NewGuid(),
                ToEmail          = "*****@*****.**",
                DefaultFromEmail = "*****@*****.**",
                Name             = "Test",
            };

            var message  = new HttpResponseMessage();
            var headers  = message.Headers;
            var content  = new StringContent("{ errors: [] }");
            var response = new Response(System.Net.HttpStatusCode.Unauthorized, content, headers);

            _mockSenderConfigurationRepository.Setup(s => s.Retrieve(It.IsAny <Guid>())).ReturnsAsync(senderConfiguration);
            _mockSendGridClient.Setup(s => s.SendEmailAsync(It.IsAny <SendGridMessage>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(response);

            return(Assert.ThrowsAsync <MessageSendFailedException>(() => _sender.Send(new SenderRequest())));
        }
            public virtual IReporter GetReporter(IMetrics metrics)
            {
                if (SenderConfig == null)
                {
                    SenderConfig = new SenderConfiguration(_loggerFactory);
                }

                IReporter reporter = new RemoteReporter.Builder()
                                     .WithLoggerFactory(_loggerFactory)
                                     .WithMetrics(metrics)
                                     .WithSender(SenderConfig.GetSender())
                                     .WithFlushInterval(FlushInterval.GetValueOrDefault(RemoteReporter.DefaultFlushInterval))
                                     .WithMaxQueueSize(MaxQueueSize.GetValueOrDefault(RemoteReporter.DefaultMaxQueueSize))
                                     .Build();

                if (LogSpans)
                {
                    IReporter loggingReporter = new LoggingReporter(_loggerFactory);
                    reporter = new CompositeReporter(reporter, loggingReporter);
                }
                return(reporter);
            }
예제 #16
0
        public async Task Send_ShouldSendEmailAsync_OnSendGridClient()
        {
            var senderConfiguration = new SenderConfiguration
            {
                Id               = Guid.NewGuid(),
                ToEmail          = "*****@*****.**",
                DefaultFromEmail = "*****@*****.**",
                Name             = "Test",
            };

            var message  = new HttpResponseMessage();
            var headers  = message.Headers;
            var content  = new StringContent(string.Empty);
            var response = new Response(System.Net.HttpStatusCode.OK, content, headers);

            _mockSenderConfigurationRepository.Setup(s => s.Retrieve(It.IsAny <Guid>())).ReturnsAsync(senderConfiguration);
            _mockSendGridClient.Setup(s => s.SendEmailAsync(It.IsAny <SendGridMessage>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(response);

            await _sender.Send(new SenderRequest());

            _mockSendGridClient.Verify(s => s.SendEmailAsync(It.IsAny <SendGridMessage>(), It.IsAny <CancellationToken>()), Times.Once);
        }
 public ReporterConfiguration WithSender(SenderConfiguration senderConfiguration)
 {
     SenderConfig = senderConfiguration;
     return(this);
 }
예제 #18
0
 public ReporterConfiguration(ILoggerFactory loggerFactory)
 {
     _loggerFactory = loggerFactory;
     SenderConfig   = new SenderConfiguration(loggerFactory);
 }
 public static SenderConfigurationTableEntity Create(string partitionKey, SenderConfiguration source) =>
 new SenderConfigurationTableEntity(partitionKey, source);
예제 #20
0
 public void SetConfig(SenderConfiguration senderConfiguration)
 {
     _option = senderConfiguration.SendGrid;
 }
예제 #21
0
 public void SetConfig(SenderConfiguration senderConfiguration)
 {
     _option = senderConfiguration.Twillio;
 }
예제 #22
0
 public void SetConfig(SenderConfiguration senderConfiguration)
 {
     _config = senderConfiguration.FirebaseMessaging;
 }
예제 #23
0
 public SenderContext(SenderConfiguration configuration, SenderHooks hooks)
 {
     this.configuration = configuration;
     this.hooks         = hooks;
     this.collection    = new SenderCollection();
 }