Пример #1
0
        public void Dependency_injection_generic_host()
        {
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddOptions();
            var viewEngine         = new Mock <IRazorViewEngine>();
            var tempDataProvider   = new Mock <ITempDataProvider>();
            var hostingEnvironment = new Mock <Microsoft.Extensions.Hosting.IHostEnvironment>();
            var logger             = new Mock <ILogger <EmailService> >();
            var logger2            = new Mock <ILogger <TemplateService> >();

            serviceCollection.AddSingleton(logger.Object);
            serviceCollection.AddSingleton(logger2.Object);
            serviceCollection.AddSingleton(viewEngine.Object);
            serviceCollection.AddSingleton(tempDataProvider.Object);
            serviceCollection.AddSingleton <Microsoft.Extensions.Hosting.IHostEnvironment>(hostingEnvironment.Object);


            serviceCollection.Configure <EmailServiceOptions>(o =>
            {
                o.CreateSmtpClient = () => throw new FactExcetpionForSmtpCreation();
            });

            serviceCollection.AddPostal();

            var services     = serviceCollection.BuildServiceProvider();
            var emailService = services.GetRequiredService <IEmailService>();

            Assert.ThrowsAsync <FactExcetpionForSmtpCreation>(() => emailService.SendAsync(new Email("testView")));
            EmailServiceOptions emailOptionField = GetInstanceField(typeof(EmailService), emailService, "options") as EmailServiceOptions;

            Assert.Throws <FactExcetpionForSmtpCreation>(() => emailOptionField.CreateSmtpClient());
        }
Пример #2
0
        public async Task CreateMessage_returns_MailMessage_created_by_parser()
        {
            var html     = @"Content-Type: text/html
To: [email protected]
From: [email protected]
Subject: Test Subject

<p>Hello, World!</p>";
            var email    = new Email("Test");
            var renderer = new Mock <IEmailViewRender>();

            renderer.Setup(r => r.RenderAsync(email)).Returns(Task.FromResult(html));
            var parser       = new Mock <IEmailParser>();
            var emailOptions = new EmailServiceOptions();

            emailOptions.CreateSmtpClient = () => null;
            var options = new Mock <IOptions <EmailServiceOptions> >();

            options.SetupGet(o => o.Value).Returns(emailOptions);
            var logger              = new Mock <ILogger <EmailService> >();
            var service             = new EmailService(renderer.Object, parser.Object, options.Object, logger.Object);
            var expectedMailMessage = new MailMessage();

            parser.Setup(p => p.ParseAsync(It.IsAny <string>(), email)).Returns(Task.FromResult(expectedMailMessage));

            var actualMailMessage = await service.CreateMailMessageAsync(email);

            actualMailMessage.ShouldBeOfType <MailMessage>();

            parser.Verify();
            renderer.Verify();
            options.Verify();
        }
Пример #3
0
        public MessageService(IOptions <EmailServiceOptions> emailServiceOptions)
        {
            _emailServiceOptions = emailServiceOptions.Value;

            // TODO
            // throwIfinvalid options method implementation
        }
        public static void AddEmailService(this IServiceCollection services, Action <EmailServiceOptions> setupEmailService)
        {
            var emailServiceOptions = new EmailServiceOptions();

            setupEmailService(emailServiceOptions);
            services.AddSingleton(emailServiceOptions);
            services.AddTransient <IEmailService, EmailService>();
            services.AddTransient <EmailClientFactory>();
        }
Пример #5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            services.Configure <SSRNMGlobal>(Configuration.GetSection("Paths"));
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddAuthentication(options =>
            {
                options.DefaultScheme = "ClientCertificateAuthentication";
            })
            .AddDrtAuthentication()
            .AddClientCertificateAuthentication(options =>
                                                ClientCertificateAuthenticationOptions.CreateForOnlyDoDRoots());

            MapperFactory.Init();
            services.AddAutoMapper(typeof(DtoMappingProfile));



            services.AddControllers();
            services.AddHttpContextAccessor();



            services.AddDbContext <SSRNMFSSNContext>(options =>
            {
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"));
            });

            services.AddScoped <DbContext>();
            services.AddScoped <SSRNMFSSNContext>();
            services.AddScoped <ReportRepository>();
            services.AddScoped <ReportDomain>();
            services.AddScoped <IUserRepository, UserRepository>();
            services.AddScoped <UserDomain>();
            //services.AddDataProtection();


            services.AddTransient <EmailService>(options =>
            {
                EmailServiceOptions eoptions = new EmailServiceOptions();
                Configuration.GetSection("EmailService").Bind(eoptions);
                var emailService = new EmailService(eoptions);
                return(emailService);
            });
        }
Пример #6
0
        public void Dependency_injection_smtpOtions1()
        {
            var configBuilder = new ConfigurationBuilder();

            configBuilder.AddInMemoryCollection(new Dictionary <string, string>()
            {
                { "Host", "abc" },
                { "Port", "12345" },
                { "FromAddress", "qwerty" },
                { "UserName", "zxcvbn" },
                { "Password", "asdfgh" }
            });
            var _configuration    = configBuilder.Build();
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddOptions();
            var viewEngine         = new Mock <IRazorViewEngine>();
            var tempDataProvider   = new Mock <ITempDataProvider>();
            var hostingEnvironment = new Mock <IWebHostEnvironment>();
            var logger             = new Mock <ILogger <EmailService> >();
            var logger2            = new Mock <ILogger <TemplateService> >();

            serviceCollection.AddSingleton(logger.Object);
            serviceCollection.AddSingleton(logger2.Object); serviceCollection.AddSingleton(viewEngine.Object);
            serviceCollection.AddSingleton(viewEngine.Object);
            serviceCollection.AddSingleton(tempDataProvider.Object);
            serviceCollection.AddSingleton <IWebHostEnvironment>(hostingEnvironment.Object);
            serviceCollection.AddSingleton <Microsoft.Extensions.Hosting.IHostEnvironment>(hostingEnvironment.Object);


            serviceCollection.Configure <EmailServiceOptions>(_configuration);
            serviceCollection.AddPostal();

            var services     = serviceCollection.BuildServiceProvider();
            var emailService = services.GetRequiredService <IEmailService>();

            var emailOption = services.GetRequiredService <IOptions <EmailServiceOptions> >().Value;

            EmailServiceOptions emailOptionField = GetInstanceField(typeof(EmailService), emailService, "options") as EmailServiceOptions;

            emailOption.Host.ShouldBe("abc");
            emailOption.Port.ShouldBe(12345);
            emailOption.FromAddress.ShouldBe("qwerty");
            emailOption.UserName.ShouldBe("zxcvbn");
            emailOption.Password.ShouldBe("asdfgh");

            emailOptionField.Host.ShouldBe("abc");
            emailOptionField.Port.ShouldBe(12345);
            emailOptionField.FromAddress.ShouldBe("qwerty");
            emailOptionField.UserName.ShouldBe("zxcvbn");
            emailOptionField.Password.ShouldBe("asdfgh");
        }
        public static IServiceCollection AddEmailService(this IServiceCollection collection, Action <EmailServiceOptions> config = null)
        {
            var option = new EmailServiceOptions();

            if (config != null)
            {
                config(option);
            }

            collection.AddTransient <IEmailService, EmailService>(x => new EmailService(option, x.GetRequiredService <ILoggerFactory>()));

            return(collection);
        }
        public static IServiceCollection AddEmailService(this IServiceCollection collection, Action<EmailServiceOptions> config = null)
        {
            var option = new EmailServiceOptions();

            if (config != null)
            {
                config(option);
            }

            collection.AddTransient<IEmailService, EmailService>(x => new EmailService(option, x.GetRequiredService<ILoggerFactory>()));

            return collection;
        }
        public IActionResult Send([FromBody] EmailSendModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    var modelErrors = ModelState
                                      .Values
                                      .SelectMany(v => v.Errors)
                                      .Select(er => er.ErrorMessage)
                                      .Aggregate((aggregatedValue, nextValue) =>
                                                 aggregatedValue += " " + nextValue);
                    return(StatusCode(
                               StatusCodes.Status500InternalServerError,
                               new { success = false, message = modelErrors }));
                }

                var emailServiceOptions = new EmailServiceOptions
                {
                    FromEmail              = model.Email,
                    FromName               = model.Name,
                    To                     = _to,
                    Subject                = _subject,
                    TextFormat             = TextFormat.Html,
                    Body                   = model.Message,
                    AuthenticationLogin    = _emailLogin,
                    AuthenticationPassword = _emailPassword,
                    Host                   = _host,
                    Port                   = _port,
                    UseSSL                 = _useSSL
                };

                var emailService = new EmailService(emailServiceOptions);
                var sendResult   = emailService.Send();

                if (sendResult.Success)
                {
                    return(Ok(new { success = true, message = sendResult.Message }));
                }
                return(StatusCode(StatusCodes.Status500InternalServerError,
                                  new { success = false, message = sendResult.Message }));
            }
            catch (Exception exception)
            {
                return(StatusCode(
                           StatusCodes.Status500InternalServerError,
                           new { success = false, message = exception.Message }));
            }
        }
Пример #10
0
        public void SendAync_returns_a_Task_and_sends_email()
        {
            var html = @"Content-Type: text/html
To: [email protected]
From: [email protected]
Subject: Test Subject

<p>Hello, World!</p>";
            var dir  = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());

            Directory.CreateDirectory(dir);
            try
            {
                using (var smtp = new SmtpClient())
                {
                    smtp.DeliveryMethod          = SmtpDeliveryMethod.SpecifiedPickupDirectory;
                    smtp.PickupDirectoryLocation = dir;
                    smtp.Host = "localhost"; // HACK: required by SmtpClient, but not actually used!

                    var email    = new Email("Test");
                    var renderer = new Mock <IEmailViewRender>();
                    renderer.Setup(r => r.RenderAsync(email)).Returns(Task.FromResult(html));
                    var emailOptions = new EmailServiceOptions();
                    emailOptions.CreateSmtpClient = () => smtp;
                    var options = new Mock <IOptions <EmailServiceOptions> >();
                    options.SetupGet(o => o.Value).Returns(emailOptions);
                    var parser  = new Mock <IEmailParser>();
                    var logger  = new Mock <ILogger <EmailService> >();
                    var service = new EmailService(renderer.Object, parser.Object, options.Object, logger.Object);
                    parser.Setup(p => p.ParseAsync(It.IsAny <string>(), It.IsAny <Email>()))
                    .Returns(Task.FromResult(new MailMessage("*****@*****.**", "*****@*****.**")));

                    var sending = service.SendAsync(email);
                    sending.Wait();

                    Directory.GetFiles(dir).Length.ShouldBe(1);
                    parser.Verify();
                    renderer.Verify();
                }
            }
            finally
            {
                Directory.Delete(dir, true);
            }
        }
Пример #11
0
        public void Dependency_injection_smtpOtions2()
        {
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddOptions();
            var viewEngine         = new Mock <IRazorViewEngine>();
            var tempDataProvider   = new Mock <ITempDataProvider>();
            var hostingEnvironment = new Mock <IWebHostEnvironment>();
            var logger             = new Mock <ILogger <EmailService> >();
            var logger2            = new Mock <ILogger <TemplateService> >();

            serviceCollection.AddSingleton(logger.Object);
            serviceCollection.AddSingleton(logger2.Object);
            serviceCollection.AddSingleton(viewEngine.Object);
            serviceCollection.AddSingleton(tempDataProvider.Object);
            serviceCollection.AddSingleton <IWebHostEnvironment>(hostingEnvironment.Object);
            serviceCollection.AddSingleton <Microsoft.Extensions.Hosting.IHostEnvironment>(hostingEnvironment.Object);


            serviceCollection.Configure <EmailServiceOptions>(o =>
            {
                o.Host             = "abc";
                o.Port             = 12345;
                o.FromAddress      = "qwerty";
                o.UserName         = "******";
                o.Password         = "******";
                o.CreateSmtpClient = () => new FactExcetpionForSmtpClient();
            });

            serviceCollection.AddPostal();

            var services     = serviceCollection.BuildServiceProvider();
            var emailService = services.GetRequiredService <IEmailService>();

            EmailServiceOptions emailOptionField = GetInstanceField(typeof(EmailService), emailService, "options") as EmailServiceOptions;

            emailOptionField.Host.ShouldBe("abc");
            emailOptionField.Port.ShouldBe(12345);
            emailOptionField.FromAddress.ShouldBe("qwerty");
            emailOptionField.UserName.ShouldBe("zxcvbn");
            emailOptionField.Password.ShouldBe("asdfgh");

            emailOptionField.CreateSmtpClient().ShouldBeOfType <FactExcetpionForSmtpClient>();
        }
 public SendGridEmailService(IOptions <EmailServiceOptions> emailServiceOptions, ILogger <EmailService> logger)
 {
     _emailServiceOptions = emailServiceOptions.Value;
     _logger = logger;
 }
Пример #13
0
 public EmailService(IOptions <EmailServiceOptions> emailServiceOptions)
 {
     _emailServiceOptions = emailServiceOptions.Value;
 }
 public EmailService(EmailServiceOptions options)
 {
 }
Пример #15
0
 public FluentEmailProvider(IFluentEmail email, IOptions <EmailServiceOptions> options, ILogger <FluentEmailProvider> logger)
 {
     _email   = email;
     _logger  = logger;
     _options = options.Value;
 }
Пример #16
0
 public EmailService(
     EmailServiceOptions options,
     ILoggerFactory factory)
 {
     _logger = factory.CreateLogger(nameof(EmailService));
 }
Пример #17
0
 public UserEmailService(IEmailService emailService, EmailServiceOptions options)
 {
     _emailService = emailService;
     _options      = options;
 }
Пример #18
0
 public HomeController(IEmailService emailService,
                       IOptions <EmailServiceOptions> o)
 {
     _emailService        = emailService;
     _emailServiceOptions = o.Value;
 }
Пример #19
0
 public EmailService(
     EmailServiceOptions options,
     ILoggerFactory factory)
 {
     _logger = factory.CreateLogger(nameof(EmailService));
 }
Пример #20
0
 public EmailService(EmailServiceOptions options)
 {
     _options = options;
 }
 public EmailContext(EmailServiceOptions options)
 {
 }
Пример #22
0
 public EmailService(IOptions <EmailServiceOptions> options, ILogger <EmailService> logger)
 {
     _options = options.Value;
     _logger  = logger;
 }
Пример #23
0
 public EmailSenderService(IOptions <EmailServiceOptions> options)
 {
     _options = options.Value;
 }
Пример #24
0
 public EmailController(IOptions <EmailServiceOptions> emailSenderOptions)
 {
     this.options = emailSenderOptions.Value;
 }
Пример #25
0
 public EmailSender(IOptions <EmailServiceOptions> options, ITemplateBuilder templateBuilder, ILogger <EmailSender> logger)
 {
     _options         = options?.Value ?? throw new ArgumentNullException(nameof(EmailServiceOptions));
     _templateBuilder = templateBuilder ?? throw new ArgumentNullException(nameof(ITemplateBuilder));
     _logger          = logger;
 }
 public EmailSender(IHostingEnvironment env, IOptions <EmailServiceOptions> emailServiceOptions)
 {
     _env = env;
     _emailServiceOptions = emailServiceOptions.Value;
 }
Пример #27
0
 public EmailProvider(ISendGridClient sendGridClient, IOptions <EmailServiceOptions> options, ILogger <EmailProvider> logger)
 {
     _sendGridClient = sendGridClient;
     _logger         = logger;
     _options        = options.Value;
 }
Пример #28
0
 public EmailService(ILogger <EmailService> logger, IOptions <EmailServiceOptions> emailNotifierOptions)
 {
     _logger = logger;
     _emailNotifierOptions = emailNotifierOptions.Value;
 }
Пример #29
0
 public EmailService(IOptions <EmailServiceOptions> options)
 {
     this.options = options.Value;
 }