Пример #1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();

            services.AddDbContext <ExamContext>(x => x.UseSqlServer(Configuration.GetConnectionString("defCon")));
            services.AddIdentity <User, Role>()
            .AddEntityFrameworkStores <ExamContext>().AddDefaultTokenProviders().AddTokenProvider <EmailConfirmationTokenProvider <User> >("emailconfirmation");

            var mapperConfig = new MapperConfiguration(mc =>
            {
                mc.AddProfile(new MapperConfig());
            });
            IMapper mapper = mapperConfig.CreateMapper();

            services.AddSingleton(mapper);

            var option = new SendGridOptions();

            Configuration.GetSection("SendGridOptions").Bind(option);
            services.AddTransient <SendGridOptions>(x => option);
            //services.AddTransient(typeof(SendGridOptions));

            services.AddTransient <IEmailSender, EmailSender>();
            services.Configure <EmailConfirmationProviderOption>(op => op.TokenLifespan = TimeSpan.FromHours(2));

            services.AddAuthentication().AddCookie(op => op.LoginPath = "/Login");
        }
        public void ApplyConfigurationSection_CreatesExpectedOptions()
        {
            var options = new SendGridOptions();
            var dict    = new Dictionary <string, string>();
            var builder = new ConfigurationBuilder();

            builder.AddInMemoryCollection(dict);
            var config = builder.Build();

            SendGridHelpers.ApplyConfiguration(config, options);
            Assert.Null(options.FromAddress);
            Assert.Null(options.ToAddress);

            dict = new Dictionary <string, string>
            {
                { "to", "Testing1 <*****@*****.**>" },
                { "from", "Testing2 <*****@*****.**>" },
            };
            builder = new ConfigurationBuilder();
            builder.AddInMemoryCollection(dict);
            config = builder.Build();

            SendGridHelpers.ApplyConfiguration(config, options);

            Assert.Equal("*****@*****.**", options.ToAddress.Email);
            Assert.Equal("Testing1", options.ToAddress.Name);
            Assert.Equal("*****@*****.**", options.FromAddress.Email);
            Assert.Equal("Testing2", options.FromAddress.Name);
        }
Пример #3
0
 public SendGridEmailService(HttpClient httpClient, IFileService fileService, SendGridOptions sendGridOptions, EmailOptions emailOptions)
 {
     _httpClient      = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
     _fileService     = fileService ?? throw new ArgumentNullException(nameof(fileService));
     _sendGridOptions = sendGridOptions ?? throw new ArgumentNullException(nameof(sendGridOptions));
     _emailOptions    = emailOptions ?? throw new ArgumentNullException(nameof(emailOptions));
 }
Пример #4
0
 public AppUsersService(ApplicationDbContext dbContext, IOptions <SendGridOptions> sendGridOptions,
                        IAsyncEmailQueue emailQueue)
 {
     _sendGridOptions = sendGridOptions.Value;
     _dbContext       = dbContext;
     _emailQueue      = emailQueue;
 }
 public SendUserOrderCreatedEmailNotificationHandler(
     IMediator mediator,
     IOptions <SendGridOptions> sendGridOptions)
 {
     this.mediator        = mediator;
     this.sendGridOptions = sendGridOptions.Value;
 }
Пример #6
0
 public EmailService(IOptions <SendGridOptions> sendGridOptions,
                     IEmailTemplatePicker emailTemplatePicker)
 {
     _emailTemplatePicker  = emailTemplatePicker;
     _sendGridOptions      = sendGridOptions.Value;
     Email.DefaultSender   = new SendGridSender(_sendGridOptions.ApiKey);
     Email.DefaultRenderer = new RazorRenderer();
 }
Пример #7
0
 public EmailService(
     IOptions <EmailOptions> emailOptions,
     IOptions <SendGridOptions> sendGridOptions
     )
 {
     _emailOptions    = emailOptions.Value;
     _sendGridOptions = sendGridOptions.Value;
 }
Пример #8
0
 public EmailSvc(IOptions <SendGridOptions> sendGridOptions, IOptions <SmtpOptions> smtpOptions,
                 ICommonFunction commonFunction, IWebHostEnvironment env)
 {
     _env             = env;
     _commonFunction  = commonFunction;
     _sendGridOptions = sendGridOptions.Value;
     _smtpOptions     = smtpOptions.Value;
 }
Пример #9
0
 public SendEmailNotificationHandler(
     ISendGridClient sendGridClient,
     IOptions <SendGridOptions> sendGridOptions,
     ILogger <SendEmailNotificationHandler> logger)
 {
     this.sendGridClient  = sendGridClient;
     this.sendGridOptions = sendGridOptions.Value;
     this.logger          = logger;
 }
Пример #10
0
 public EmailSvc(IOptions <SendGridOptions> sendGridOptions,
                 IFunctionalSvc functionalSvc,
                 IOptions <SmtpOptions> smtpOptions, IHostingEnvironment hostingEnvironment)
 {
     _sendGridOptions    = sendGridOptions.Value;
     _smtpOptions        = smtpOptions.Value;
     _hostingEnvironment = hostingEnvironment;
     _functionalSvc      = functionalSvc;
 }
Пример #11
0
 public SendSupplierInvitationEmailNotificationHandler(
     IMediator mediator,
     IOptions <SendGridOptions> sendGridOptions,
     IOptions <ClientOptions> clientOptions)
 {
     this.mediator        = mediator;
     this.sendGridOptions = sendGridOptions.Value;
     this.clientOptions   = clientOptions.Value;
 }
Пример #12
0
        public SendGridSender(IOptions <SendGridOptions> sendGridOptions)
        {
            _sendGridOptions = sendGridOptions.Value;

            _sendGridClientIntance = new Lazy <SendGridClient>(() =>
            {
                return(new SendGridClient(_sendGridOptions.ApiKey));
            });
        }
        public static IServiceCollection AddSendGrid(this IServiceCollection services,
                                                     SendGridOptions options)
        {
            Guard.Null(nameof(services), services);
            Guard.Null(nameof(options), options);

            services.TryAddSingleton(options);
            services.TryAddSingleton <IEmailService, SendGridEmailService>();

            return(services);
        }
Пример #14
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Admin, "post", Route = null)] HttpRequest req,
            ILogger log, ExecutionContext context)
        {
            string requestInfo  = null;
            string errorContext = null;

            try
            {
                errorContext = "inspecting request";

                // generate key for a product
                var json = await req.ReadAsStringAsync();

                requestInfo = json;
                var createKey = JsonConvert.DeserializeObject <Shared.Models.CreateKey>(json);
                var key       = new LicenseKey()
                {
                    Email   = createKey.Email,
                    Product = createKey.Product,
                    Key     = new StringIdBuilder()
                              .Add(4, StringIdRanges.Upper | StringIdRanges.Numeric)
                              .Add("-")
                              .Add(4, StringIdRanges.Upper | StringIdRanges.Numeric)
                              .Add("-")
                              .Add(4, StringIdRanges.Upper | StringIdRanges.Numeric)
                              .Build()
                };

                var config = context.GetConfig();

                // save to storage account
                errorContext = "saving key";
                var storageOptions = new StorageAccountOptions();
                config.Bind("StorageAccount", storageOptions);
                var keyStore = new KeyStore(storageOptions);
                await keyStore.SaveKeyAsync(key);

                // send to user
                errorContext = "sending key to user";
                var sendGridOptions = new SendGridOptions();
                config.GetSection("SendGrid").Bind(sendGridOptions);
                await SendConfirmationEmailAsync(key, sendGridOptions);

                log.LogInformation(JsonConvert.SerializeObject(key));
                return(new OkObjectResult(key));
            }
            catch (Exception exc)
            {
                log.LogError(exc, $"{exc.Message} while {errorContext}: {requestInfo}");
                return(new BadRequestObjectResult(exc.Message));
            }
        }
Пример #15
0
        /// <summary>
        /// Constructor of Email Service.
        /// </summary>
        /// <param name="sendGridOptions">The configuration.</param>
        /// <param name="mailOptions">The options.</param>
        /// <param name="logger">The logger.</param>
        public MailService(
            IOptions <SendGridOptions> sendGridOptions,
            IOptions <MailOptions> mailOptions,
            ILogger logger)
        {
            _mailOptions     = mailOptions.Value;
            _sendGridOptions = sendGridOptions.Value;
            _logger          = logger;

            Argument.IsNotNullOrEmpty(_mailOptions.EmailAddress);
            Argument.IsNotNullOrEmpty(_mailOptions.Sender);
            Argument.IsNotNullOrEmpty(_sendGridOptions.Key);
        }
Пример #16
0
        internal static void DefaultMessageProperties(SendGridMessage mail, SendGridOptions options, SendGridAttribute attribute)
        {
            // Apply message defaulting
            if (mail.From == null)
            {
                if (!string.IsNullOrEmpty(attribute.From))
                {
                    EmailAddress from = null;
                    if (!TryParseAddress(attribute.From, out from))
                    {
                        throw new ArgumentException("Invalid 'From' address specified");
                    }
                    mail.From = from;
                }
                else if (options.FromAddress != null)
                {
                    mail.From = options.FromAddress;
                }
            }

            if (!IsToValid(mail))
            {
                if (!string.IsNullOrEmpty(attribute.To))
                {
                    EmailAddress to = null;
                    if (!TryParseAddress(attribute.To, out to))
                    {
                        throw new ArgumentException("Invalid 'To' address specified");
                    }

                    mail.AddTo(to);
                }
                else if (options.ToAddress != null)
                {
                    mail.AddTo(options.ToAddress);
                }
            }

            if (string.IsNullOrEmpty(mail.Subject) &&
                !string.IsNullOrEmpty(attribute.Subject))
            {
                mail.Subject = attribute.Subject;
            }

            if ((mail.Contents == null || mail.Contents.Count == 0) &&
                !string.IsNullOrEmpty(attribute.Text))
            {
                mail.AddContent("text/plain", attribute.Text);
            }
        }
Пример #17
0
        internal static void ApplyConfiguration(IConfiguration config, SendGridOptions options)
        {
            if (config == null)
            {
                return;
            }

            config.Bind(options);

            string to   = config.GetValue <string>("to");
            string from = config.GetValue <string>("from");

            options.ToAddress   = SendGridHelpers.Apply(options.ToAddress, to);
            options.FromAddress = SendGridHelpers.Apply(options.FromAddress, from);
        }
Пример #18
0
        private async static Task SendConfirmationEmailAsync(LicenseKey key, SendGridOptions options)
        {
            var client = new SendGridClient(options.ApiKey);
            var from   = new EmailAddress(options.SenderEmail, options.SenderName);
            var to     = new EmailAddress(key.Email);

            string stringContent = $"Thank you for your purchase of {key.Product}!\r\n\r\nYour license key is below:\r\n\r\n{key.Key}";
            string htmlContent   = Markdown.ToHtml(stringContent);

            var message = MailHelper.CreateSingleEmailToMultipleRecipients(from,
                                                                           new EmailAddress[] { to, from }.ToList(),
                                                                           "Your license key from aosoftware.net", stringContent, htmlContent);

            await client.SendEmailAsync(message);
        }
        public void DefaultMessageProperties_CreatesExpectedMessage()
        {
            SendGridAttribute attribute = new SendGridAttribute();
            SendGridOptions   options   = new SendGridOptions
            {
                ApiKey      = "12345",
                FromAddress = new EmailAddress("*****@*****.**", "Test2"),
                ToAddress   = new EmailAddress("*****@*****.**", "Test")
            };

            SendGridMessage message = new SendGridMessage();

            message.Subject = "TestSubject";
            message.AddContent("text/plain", "TestText");

            SendGridHelpers.DefaultMessageProperties(message, options, attribute);

            Assert.Same(options.FromAddress, options.FromAddress);
            Assert.Equal("*****@*****.**", message.Personalizations.Single().Tos.Single().Email);
            Assert.Equal("TestSubject", message.Subject);
            Assert.Equal("TestText", message.Contents.Single().Value);
        }
Пример #20
0
        /// <summary>
        /// Helper function.
        /// </summary>
        private static void ValidateOptions(SendGridOptions opt)
        {
            // Scream for missing yet required stuff
            if (string.IsNullOrWhiteSpace(opt?.ApiKey))
            {
                throw new InvalidOperationException(
                          $"Email is enabled, therefore a SendGrid API Key must be in a configuration provider under the key '{SectionName}:{nameof(SendGridOptions.ApiKey)}', you can get a free key at https://sendgrid.com/.");
            }

            bool webhooksEnabled = opt?.CallbacksEnabled ?? false;

            if (webhooksEnabled)
            {
                if (string.IsNullOrWhiteSpace(opt?.VerificationKey))
                {
                    throw new InvalidOperationException(
                              $"{SectionName}:{nameof(SendGridOptions.CallbacksEnabled)} = true, therefore the webhook callback verification key must be in a configuration provider under the key '{SectionName}:{nameof(SendGridOptions.VerificationKey)}'.");
                }

                // Add the public key?
            }
        }
        public UsersService(IHostingEnvironment env,
                            IOptions <MongoDBOptions> options,
                            IOptions <SendGridOptions> sendGridOptions,
                            IOptions <ProjectGeneralsOptions> projectGeneralsOptions,
                            EmailService emailService,
                            ILoggerFactory loggerFactory)
        {
            _env             = env;
            _mongoDBOptions  = options.Value;
            _sendGridOptions = sendGridOptions.Value;
            _projectGenerals = projectGeneralsOptions.Value;
            _logger          = loggerFactory.CreateLogger <UsersService>();
            _emailService    = emailService;

            //if (this._env.IsDevelopment())
            //{
            //  MongoUrl murl = new MongoUrl(_mongoDBOptions.Url);
            //  MongoClientSettings mcs = MongoClientSettings.FromUrl(murl);
            //  mcs.ClusterConfigurator = c =>
            //  {
            //    c.Subscribe<CommandStartedEvent>(e =>
            //    {
            //      this._logger.LogInformation($"{e.CommandName} - {e.Command.ToJson()}");
            //    });
            //    //c.Subscribe<CommandSucceededEvent>(this.CommandExecutedHandler);
            //  };
            //  _client = new MongoClient(mcs);
            //}
            _client = new MongoClient(_mongoDBOptions.Url);

            _db = _client.GetDatabase(_mongoDBOptions.DbName);
            _usersCollection = _db.GetCollection <User>("users");

            //Create index not supported in MongoDB API at the moment
            //var indexOptions = new CreateIndexOptions() { Unique = true};
            //_usersCollection.Indexes.CreateOne(new IndexKeysDefinitionBuilder<User>().Ascending("Email"), indexOptions);
        }
        public IActionResult UpdateSengridOptions([FromBody] SendGridOptions options)
        {
            try
            {
                // Checking to see id key was not updated
                // we dont want the encrypted key from input to be updated
                var protectorProvider = _provider.GetService <IDataProtectionProvider>();
                var protector         = protectorProvider.CreateProtector(_dataProtectionKeys.ApplicationUserKey);
                var decryptedKey      = protector.Unprotect(options.SendGridKey);
                options.SendGridKey = decryptedKey;
            }
            catch (Exception ex)
            {
                Log.Error("An error occurred decrypting sendgrid key {Error} {StackTrace} {InnerException} {Source}",
                          ex.Message, ex.StackTrace, ex.InnerException, ex.Source);
            }
            var resultError = _writableSvcSendGridOptions.Update((opt) =>
            {
                opt.FromEmail    = options.FromEmail;
                opt.FromFullName = options.FromFullName;
                opt.SendGridKey  = options.SendGridKey;
                opt.SendGridUser = options.SendGridUser;
                opt.IsDefault    = options.IsDefault;
            });

            if (!resultError)
            {
                if (options.IsDefault)
                {
                    _writableSvcSmtpOptions.Update((optSmtp) => { optSmtp.IsDefault = false; });
                }
                return(Ok(new { success = true }));
            }

            return(BadRequest(new { success = false }));
        }
Пример #23
0
        public EmailSenderFactory(IConfiguration configuration, IServiceProvider serviceProvider)
        {
            var emailType = configuration["EmailSender:EmailSenderType"].ToLower();

            if (emailType == "pickup")
            {
                var options = new PickFolderSmtpOptions();
                configuration.GetSection("EmailSender").Bind(options);
                _emailSender = new PickFolderEmailSender(options);
            }
            else if (emailType == "smtp")
            {
                var options = new SmtpOptions();
                configuration.GetSection("EmailSender").Bind(options);
                _emailSender = new SmtpEmailSender(options);
            }
            else
            {
                var options = new SendGridOptions();
                configuration.GetSection("EmailSender").Bind(options);
                var logger = ActivatorUtilities.GetServiceOrCreateInstance <ILogger <SendGridEmailSender> >(serviceProvider);
                _emailSender = new SendGridEmailSender(options, logger);
            }
        }
Пример #24
0
 public SendGridMessageAsyncCollector(SendGridOptions options, SendGridAttribute attribute, ISendGridClient sendGrid)
 {
     _options   = options;
     _attribute = attribute;
     _sendGrid  = sendGrid;
 }
Пример #25
0
 public SendGridService(IOptions <SendGridOptions> options)
 {
     SendGridOptions = options.Value;
 }
Пример #26
0
 public EmailSender(IOptions <SendGridOptions> sendGridOptions)
 {
     _sendGridSettings = sendGridOptions.Value;
 }
Пример #27
0
 public EmailSender(IOptions <SendGridOptions> options)
 {
     this.options = options.Value;
 }
Пример #28
0
 public ApplicationEmailSender(IOptions <SendGridOptions> sendGridOptionsSnapshot)
 {
     _sendGridOptions = sendGridOptionsSnapshot.Value;
 }
Пример #29
0
 public EmailService(IOptions <SendGridOptions> optionsAccessor)
 {
     _options = optionsAccessor.Value;
 }
 public SendGridEmailWorkerService(IOptions <NotificationOptions> notificationOptions)
 {
     this._sendGridOptions = notificationOptions.Value.SendGrid;
 }