internal static SendGridConfiguration CreateConfiguration(JObject metadata) { SendGridConfiguration sendGridConfig = new SendGridConfiguration(); JObject configSection = (JObject)metadata.GetValue("sendGrid", StringComparison.OrdinalIgnoreCase); JToken value = null; if (configSection != null) { EmailAddress mailAddress = null; if (configSection.TryGetValue("from", StringComparison.OrdinalIgnoreCase, out value) && TryParseAddress((string)value, out mailAddress)) { sendGridConfig.FromAddress = mailAddress; } if (configSection.TryGetValue("to", StringComparison.OrdinalIgnoreCase, out value) && TryParseAddress((string)value, out mailAddress)) { sendGridConfig.ToAddress = mailAddress; } } return(sendGridConfig); }
public EmailSenderManager(IConfiguration configuration) { _configuration = configuration; _emailConfiguration = new EmailConfiguration(); _emailConfiguration.FromEmailAddress = _configuration["AppEmailConfig:FromEmailAddress"].ToString(); _emailConfiguration.FromEmailAddressDisplayName = _configuration["AppEmailConfig:FromEmailAddressDisplayName"].ToString(); _emailConfiguration.Password = _configuration["AppEmailConfig:PasswordKey"].ToString(); _emailConfiguration.Host = _configuration["AppEmailConfig:HostKey"].ToString(); _emailConfiguration.Port = Int32.Parse(_configuration["AppEmailConfig:PortKey"]); _emailConfiguration.Ssl = Boolean.Parse(_configuration["AppEmailConfig:SslKey"]); _emailConfiguration.TestEmailAddress = _configuration["AppEmailConfig:TestEmailAddress"].ToString(); _log.Debug("EmailSenderManager - EmailConfiguration - FromEmailAddress: " + _emailConfiguration.FromEmailAddress); _log.Debug("EmailSenderManager - EmailConfiguration - Password: "******"AppEmailConfig:SendGridFromEmailAddress"].ToString(); _sendGridConfiguration.DisplayName = _configuration["AppEmailConfig:SendGridFromEmailAddressDisplayName"].ToString(); _sendGridConfiguration.ApiKey = _configuration["AppEmailConfig:SendGridApiKey"].ToString(); _log.Debug("EmailSenderManager - SendGridConfiguration - FromEmailAddress: " + _sendGridConfiguration.FromEmailAddress); _contactUsConfiguration = new ContactUsConfiguration(); _contactUsConfiguration.EmailAddress = _configuration["AppContactUsConfig:EmailAddress"].ToString(); _contactUsConfiguration.EmailAddressDisplayName = _configuration["AppContactUsConfig:EmailAddressDisplayName"].ToString(); _contactUsConfiguration.PhoneNumber = _configuration["AppContactUsConfig:PhoneNumber"].ToString(); _contactUsConfiguration.PhoneNumberDisplayName = _configuration["AppContactUsConfig:PhoneNumberDisplayName"].ToString(); _log.Debug("EmailSenderManager - ContactUsConfiguration - EmailAddress: " + _contactUsConfiguration.EmailAddress); _log.Debug("EmailSenderManager - ContactUsConfiguration - PhoneNumber: " + _contactUsConfiguration.PhoneNumber); }
public void Binding_UsesNameResolver() { ParameterInfo parameter = GetType().GetMethod("TestMethod", BindingFlags.Static | BindingFlags.NonPublic).GetParameters().First(); SendGridAttribute attribute = new SendGridAttribute { To = "%param1%", From = "%param2%", Subject = "%param3%", Text = "%param4%" }; SendGridConfiguration config = new SendGridConfiguration { ApiKey = "12345" }; Dictionary <string, Type> contract = new Dictionary <string, Type>(); BindingProviderContext context = new BindingProviderContext(parameter, contract, CancellationToken.None); var nameResolver = new TestNameResolver(); nameResolver.Values.Add("param1", "*****@*****.**"); nameResolver.Values.Add("param2", "*****@*****.**"); nameResolver.Values.Add("param3", "Value3"); nameResolver.Values.Add("param4", "Value4"); SendGridBinding binding = new SendGridBinding(parameter, attribute, config, nameResolver, context); Dictionary <string, object> bindingData = new Dictionary <string, object>(); SendGridMessage message = binding.CreateDefaultMessage(bindingData); Assert.Equal("*****@*****.**", message.To.Single().Address); Assert.Equal("*****@*****.**", message.From.Address); Assert.Equal("Value3", message.Subject); Assert.Equal("Value4", message.Text); }
public static void Main(string[] args) { JobHostConfiguration config = new JobHostConfiguration(); FilesConfiguration filesConfig = new FilesConfiguration(); // See https://github.com/Azure/azure-webjobs-sdk/wiki/Running-Locally for details // on how to set up your local environment if (config.IsDevelopment) { config.UseDevelopmentSettings(); filesConfig.RootPath = @"c:\temp\files"; } config.UseFiles(filesConfig); config.UseTimers(); config.UseSample(); config.UseEasyTables(); config.UseCore(); config.UseDocumentDB(); config.UseNotificationHubs(); var sendGridConfiguration = new SendGridConfiguration() { ToAddress = "*****@*****.**", FromAddress = new MailAddress("*****@*****.**", "WebJobs Extensions Samples") }; config.UseSendGrid(sendGridConfiguration); ConfigureTraceMonitor(config, sendGridConfiguration); EnsureSampleDirectoriesExist(filesConfig.RootPath); WebHooksConfiguration webHooksConfig = new WebHooksConfiguration(); webHooksConfig.UseReceiver <GitHubWebHookReceiver>(); config.UseWebHooks(webHooksConfig); JobHost host = new JobHost(config); // Add or remove types from this list to choose which functions will // be indexed by the JobHost. config.TypeLocator = new SamplesTypeLocator( typeof(ErrorMonitoringSamples), typeof(FileSamples), typeof(MiscellaneousSamples), typeof(SampleSamples), typeof(SendGridSamples), typeof(TableSamples), typeof(TimerSamples), typeof(WebHookSamples)); host.Call(typeof(MiscellaneousSamples).GetMethod("ExecutionContext")); host.Call(typeof(FileSamples).GetMethod("ReadWrite")); host.Call(typeof(SampleSamples).GetMethod("Sample_BindToStream")); host.Call(typeof(SampleSamples).GetMethod("Sample_BindToString")); host.Call(typeof(TableSamples).GetMethod("CustomBinding")); host.RunAndBlock(); }
protected EmailBatchTypeHandlerBase(ILogger logger, IReadableDataSource dataSource, EmailBatch emailBatch, SendGridConfiguration sendGridConfiguration) { _logger = logger; _dataSource = dataSource; _sendGridConfiguration = sendGridConfiguration; EmailBatch = emailBatch; }
public EmailService(ISmtpHelper smtpHelper, IOptions <SmtpConfiguration> smtpConfiguration, IOptions <SendGridConfiguration> sendGridConfiguration) { _smtpHelper = smtpHelper; _smtpConfiguration = smtpConfiguration.Value; _sendGridConfiguration = sendGridConfiguration.Value; }
public static void Main(string[] args) { JobHostConfiguration config = new JobHostConfiguration(); FilesConfiguration filesConfig = new FilesConfiguration(); // See https://github.com/Azure/azure-webjobs-sdk/wiki/Running-Locally for details // on how to set up your local environment if (config.IsDevelopment) { config.UseDevelopmentSettings(); filesConfig.RootPath = @"c:\temp\files"; } config.UseFiles(filesConfig); config.UseTimers(); config.UseSample(); config.UseMobileApps(); config.UseTwilioSms(); config.UseCore(); config.UseCosmosDB(); var sendGridConfiguration = new SendGridConfiguration() { ToAddress = new EmailAddress("*****@*****.**", "WebJobs Extensions Samples"), FromAddress = new EmailAddress("*****@*****.**", "WebJobs Extensions Samples") }; config.UseSendGrid(sendGridConfiguration); ConfigureTraceMonitor(config, sendGridConfiguration); EnsureSampleDirectoriesExist(filesConfig.RootPath); JobHost host = new JobHost(config); // Add or remove types from this list to choose which functions will // be indexed by the JobHost. // To run some of the other samples included, add their types to this list config.TypeLocator = new SamplesTypeLocator( typeof(ErrorMonitoringSamples), typeof(FileSamples), typeof(MiscellaneousSamples), typeof(SampleSamples), typeof(TableSamples), typeof(TimerSamples)); // Some direct invocations to demonstrate various binding scenarios host.Call(typeof(MiscellaneousSamples).GetMethod("ExecutionContext")); host.Call(typeof(FileSamples).GetMethod("ReadWrite")); host.Call(typeof(SampleSamples).GetMethod("Sample_BindToStream")); host.Call(typeof(SampleSamples).GetMethod("Sample_BindToString")); host.Call(typeof(TableSamples).GetMethod("CustomBinding")); host.RunAndBlock(); }
internal static void DefaultMessageProperties(Mail mail, SendGridConfiguration config, SendGridAttribute attribute) { // Apply message defaulting if (mail.From == null) { if (!string.IsNullOrEmpty(attribute.From)) { Email from = null; if (!TryParseAddress(attribute.From, out from)) { throw new ArgumentException("Invalid 'From' address specified"); } mail.From = from; } else if (config.FromAddress != null) { mail.From = config.FromAddress; } } if (mail.Personalization == null || mail.Personalization.Count == 0) { if (!string.IsNullOrEmpty(attribute.To)) { Email to = null; if (!TryParseAddress(attribute.To, out to)) { throw new ArgumentException("Invalid 'To' address specified"); } Personalization personalization = new Personalization(); personalization.AddTo(to); mail.AddPersonalization(personalization); } else if (config.ToAddress != null) { Personalization personalization = new Personalization(); personalization.AddTo(config.ToAddress); mail.AddPersonalization(personalization); } } 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(new Content("text/plain", attribute.Text)); } }
public SendGridEmailSender( [NotNull] IOptions <SendGridConfiguration> sendGridConfiguration, ILogger <SendGridEmailSender> logger ) { if (sendGridConfiguration.Value == null) { throw new SendGridEmailSenderException("sendGridConfiguration.Value is empty."); } _sendGridConfiguration = sendGridConfiguration.Value; _logger = logger; }
public static void Main(string[] args) { JobHostConfiguration config = new JobHostConfiguration(); config.Tracing.ConsoleLevel = TraceLevel.Verbose; // Set to a short polling interval to facilitate local // debugging. You wouldn't want to run prod this way. config.Queues.MaxPollingInterval = TimeSpan.FromSeconds(2); FilesConfiguration filesConfig = new FilesConfiguration(); if (string.IsNullOrEmpty(filesConfig.RootPath)) { // when running locally, set this to a valid directory filesConfig.RootPath = @"c:\temp\files"; } EnsureSampleDirectoriesExist(filesConfig.RootPath); config.UseFiles(filesConfig); config.UseTimers(); config.UseSample(); config.UseCore(); var sendGridConfiguration = new SendGridConfiguration() { ToAddress = "*****@*****.**", FromAddress = new MailAddress("*****@*****.**", "WebJobs Extensions Samples") }; config.UseSendGrid(sendGridConfiguration); ConfigureTraceMonitor(config, sendGridConfiguration); WebHooksConfiguration webHooksConfig = new WebHooksConfiguration(); webHooksConfig.UseReceiver<GitHubWebHookReceiver>(); config.UseWebHooks(webHooksConfig); JobHost host = new JobHost(config); host.Call(typeof(MiscellaneousSamples).GetMethod("ExecutionContext")); host.Call(typeof(FileSamples).GetMethod("ReadWrite")); host.Call(typeof(SampleSamples).GetMethod("Sample_BindToStream")); host.Call(typeof(SampleSamples).GetMethod("Sample_BindToString")); host.Call(typeof(TableSamples).GetMethod("CustomBinding")); // When running in Azure Web Apps, a JobHost will gracefully shut itself // down, ensuring that all listeners are stopped, etc. For this sample, // we want to ensure that same behavior when the console app window is // closed. This ensures that Singleton locks that are taken are released // immediately, etc. ShutdownHandler.Register(() => { host.Stop(); }); host.RunAndBlock(); }
public ErrorNotifier(SendGridConfiguration sendGridConfig) { if (sendGridConfig == null) { throw new ArgumentNullException(nameof(sendGridConfig)); } _sendGridConfig = sendGridConfig; _sendGrid = new SendGridClient(sendGridConfig.ApiKey); // pull our IFTTT notification URL from app settings (since it contains a secret key) var nameResolver = new DefaultNameResolver(); _webNotificationUri = nameResolver.Resolve(NotificationUriSettingName); }
/// <summary> /// Enables use of the SendGrid extensions /// </summary> /// <param name="config">The <see cref="JobHostConfiguration"/> to configure.</param> /// <param name="sendGridConfig">The <see cref="SendGridConfiguration"/> to use.</param> public static void UseSendGrid(this JobHostConfiguration config, SendGridConfiguration sendGridConfig = null) { if (config == null) { throw new ArgumentNullException("config"); } if (sendGridConfig == null) { sendGridConfig = new SendGridConfiguration(); } config.RegisterExtensionConfigProvider(sendGridConfig); }
internal static void DefaultMessageProperties(SendGridMessage message, SendGridConfiguration config, SendGridAttribute attribute) { // Apply message defaulting if (message.From == null) { if (!string.IsNullOrEmpty(attribute.From)) { MailAddress from = null; if (!TryParseAddress(attribute.From, out from)) { throw new ArgumentException("Invalid 'From' address specified"); } message.From = from; } else if (config.FromAddress != null) { message.From = config.FromAddress; } } if (message.To == null || message.To.Length == 0) { if (!string.IsNullOrEmpty(attribute.To)) { MailAddress to = null; if (!TryParseAddress(attribute.To, out to)) { throw new ArgumentException("Invalid 'To' address specified"); } message.To = new MailAddress[] { to }; } else if (config.ToAddress != null) { message.To = new MailAddress[] { config.ToAddress }; } } if (string.IsNullOrEmpty(message.Subject) && !string.IsNullOrEmpty(attribute.Subject)) { message.Subject = attribute.Subject; } if (string.IsNullOrEmpty(message.Text) && !string.IsNullOrEmpty(attribute.Text)) { message.Text = attribute.Text; } }
private async Task RunTestAsync(string testName, ISendGridClientFactory factory, object argument = null, string configApiKey = null, bool includeDefaultApiKey = true) { Type testType = typeof(SendGridEndToEndFunctions); ExplicitTypeLocator locator = new ExplicitTypeLocator(testType); JobHostConfiguration config = new JobHostConfiguration { TypeLocator = locator, }; ILoggerFactory loggerFactory = new LoggerFactory(); loggerFactory.AddProvider(_loggerProvider); config.LoggerFactory = loggerFactory; var arguments = new Dictionary <string, object>(); arguments.Add("triggerData", argument); var sendGridConfig = new SendGridConfiguration { ApiKey = configApiKey, ClientFactory = factory, ToAddress = new EmailAddress("*****@*****.**"), FromAddress = new EmailAddress("*****@*****.**") }; var resolver = new TestNameResolver(); resolver.Values.Add("MyKey1", AttributeApiKey1); resolver.Values.Add("MyKey2", AttributeApiKey2); if (includeDefaultApiKey) { resolver.Values.Add(SendGridConfiguration.AzureWebJobsSendGridApiKeyName, DefaultApiKey); } config.NameResolver = resolver; config.UseSendGrid(sendGridConfig); JobHost host = new JobHost(config); await host.StartAsync(); await host.CallAsync(testType.GetMethod(testName), arguments); await host.StopAsync(); }
public ErrorNotifier(SendGridConfiguration sendGridConfig) { if (sendGridConfig == null) { throw new ArgumentNullException("sendGridConfig"); } _sendGridConfig = sendGridConfig; _sendGrid = new Web(sendGridConfig.ApiKey); // pull our IFTTT notification URL from app settings (since it contains a secret key) _webNotificationUri = ConfigurationManager.AppSettings.Get(NotificationUriSettingName); if (string.IsNullOrEmpty(_webNotificationUri)) { _webNotificationUri = Environment.GetEnvironmentVariable(NotificationUriSettingName); } }
private static SendGridConfiguration CreateConfiguration(JObject config) { var ctx = new ExtensionConfigContext { Config = new JobHostConfiguration() { HostConfigMetadata = config }, Trace = new TestTraceWriter(TraceLevel.Verbose) }; SendGridConfiguration result = new SendGridConfiguration(); result.Initialize(ctx); return(result); }
public ContactController(ILogger <ContactController> logger, ContactInfoContext context, IOptions <SendGridConfiguration> emailOptions, IConfiguration configuration) { _logger = logger; _context = context; _emailConfiguration = emailOptions.Value; _apiKey = _emailConfiguration.ApiKey; _to = new EmailAddress(_emailConfiguration.To); _from = new EmailAddress(_emailConfiguration.Sender); _ackTemplateId = _emailConfiguration.AckTemplateId; _webProxy = new WebProxy(_emailConfiguration.WebProxy, true); _client = new SendGridClient(_webProxy, _apiKey); if (configuration["Environment"].ToLower().Equals("dev")) { _client = new SendGridClient(_apiKey); } }
public void CreateDefaultMessage_CreatesExpectedMessage() { ParameterInfo parameter = GetType().GetMethod("TestMethod", BindingFlags.Static | BindingFlags.NonPublic).GetParameters().First(); SendGridAttribute attribute = new SendGridAttribute { To = "{Param1}", Subject = "Test {Param2}", Text = "Test {Param3}" }; SendGridConfiguration config = new SendGridConfiguration { ApiKey = "12345", FromAddress = new MailAddress("*****@*****.**", "Test2"), ToAddress = "*****@*****.**" }; Dictionary <string, Type> contract = new Dictionary <string, Type>(); contract.Add("Param1", typeof(string)); contract.Add("Param2", typeof(string)); contract.Add("Param3", typeof(string)); BindingProviderContext context = new BindingProviderContext(parameter, contract, CancellationToken.None); var nameResolver = new TestNameResolver(); SendGridBinding binding = new SendGridBinding(parameter, attribute, config, nameResolver, context); Dictionary <string, object> bindingData = new Dictionary <string, object>(); bindingData.Add("Param1", "*****@*****.**"); bindingData.Add("Param2", "Value2"); bindingData.Add("Param3", "Value3"); SendGridMessage message = binding.CreateDefaultMessage(bindingData); Assert.Same(config.FromAddress, message.From); Assert.Equal("*****@*****.**", message.To.Single().Address); Assert.Equal("Test Value2", message.Subject); Assert.Equal("Test Value3", message.Text); // If no To value specified, verify it is defaulted from config attribute = new SendGridAttribute { Subject = "Test {Param2}", Text = "Test {Param3}" }; binding = new SendGridBinding(parameter, attribute, config, nameResolver, context); message = binding.CreateDefaultMessage(bindingData); Assert.Equal("*****@*****.**", message.To.Single().Address); }
/// <summary> /// Set up monitoring + notifications for WebJob errors. This shows how to set things up /// manually on startup. You can also use <see cref="ErrorTriggerAttribute"/> to designate /// error handler functions. /// </summary> private static void ConfigureTraceMonitor(JobHostConfiguration config, SendGridConfiguration sendGridConfiguration) { var notifier = new ErrorNotifier(sendGridConfiguration); var traceMonitor = new TraceMonitor() .Filter(new SlidingWindowTraceFilter(TimeSpan.FromMinutes(5), 3)) .Filter(p => { FunctionInvocationException functionException = p.Exception as FunctionInvocationException; return p.Level == TraceLevel.Error && functionException != null && functionException.MethodName == "ExtensionsSample.FileSamples.ImportFile"; }, "ImportFile Job Failed") .Subscribe(notifier.WebNotify, notifier.EmailNotify) .Throttle(TimeSpan.FromMinutes(30)); config.Tracing.Tracers.Add(traceMonitor); }
/// <summary> /// Set up monitoring + notifications for WebJob errors. This shows how to set things up /// manually on startup. You can also use <see cref="ErrorTriggerAttribute"/> to designate /// error handler functions. /// </summary> private static void ConfigureTraceMonitor(JobHostConfiguration config, SendGridConfiguration sendGridConfiguration) { var notifier = new ErrorNotifier(sendGridConfiguration); var traceMonitor = new TraceMonitor() .Filter(new SlidingWindowTraceFilter(TimeSpan.FromMinutes(5), 3)) .Filter(p => { FunctionInvocationException functionException = p.Exception as FunctionInvocationException; return(p.Level == TraceLevel.Error && functionException != null && functionException.MethodName == "ExtensionsSample.FileSamples.ImportFile"); }, "ImportFile Job Failed") .Subscribe(notifier.WebNotify, notifier.EmailNotify) .Throttle(TimeSpan.FromMinutes(30)); config.Tracing.Tracers.Add(traceMonitor); }
public async Task <EmailSentResult> SendEmailMessageBySendGridAsync(List <EmailMessage> emailMessageList, string userId) { SendGridConfiguration sendGridConfiguration = GetSendGridConfiguration(); EmailSentResult emailSentResult = new EmailSentResult() { Success = false }; var emailMessage = emailMessageList.FirstOrDefault(); string receiverEmailList = String.Join(", ", emailMessageList); try { var apiKey = sendGridConfiguration.ApiKey; var client = new SendGridClient(apiKey); var sendGridMessage = new SendGridMessage() { From = new EmailAddress(sendGridConfiguration.FromEmailAddress, sendGridConfiguration.DisplayName), Subject = emailMessage.Subject, //PlainTextContent = string.Empty, HtmlContent = emailMessage.Body }; foreach (var item in emailMessageList) { sendGridMessage.AddTo(new EmailAddress(item.ReceiverEmail, item.ReceiverName)); } var response = await client.SendEmailAsync(sendGridMessage); if (response.StatusCode == HttpStatusCode.Accepted) { emailSentResult.Success = true; emailSentResult.Id = userId; log.Info("EmailSenderManager - SendEmailMessageBySendGridAsync - StatusCode: " + response.StatusCode + " - Email send successfully by SendGrid for user id: " + userId + " email list: " + receiverEmailList); } } catch (Exception ex) { emailSentResult.Ex = ex; log.Error(Log4NetMessageHelper.FormateMessageForException(ex, "SendEmailMessageBySendGridAsync", receiverEmailList)); } return(emailSentResult); }
public EmailSenderManager(IConfiguration configuration) { _configuration = configuration; _emailConfiguration = new EmailConfiguration(); _emailConfiguration.FromEmailAddress = _configuration["AppEmailConfig:FromEmailAddressKey"]?.ToString(); _emailConfiguration.DisplayName = _configuration["AppEmailConfig:DisplayNameKey"]?.ToString(); _emailConfiguration.Password = _configuration["AppEmailConfig:PasswordKey"]?.ToString(); _emailConfiguration.Host = _configuration["AppEmailConfig:HostKey"]?.ToString(); _emailConfiguration.Port = Int32.Parse(_configuration["AppEmailConfig:PortKey"]); _emailConfiguration.Ssl = Boolean.Parse(_configuration["AppEmailConfig:SslKey"]); log.Debug("EmailSenderManager - EmailConfiguration - Username: "******"EmailSenderManager - EmailConfiguration - Password: "******"AppEmailConfig:SendGridFromEmailAddressKey"]?.ToString(); _sendGridConfiguration.DisplayName = _configuration["AppEmailConfig:SendGridDisplayNameKey"]?.ToString(); _sendGridConfiguration.ApiKey = _configuration["AppEmailConfig:SendGridApiKey"]?.ToString(); log.Debug("EmailSenderManager - SendGridConfiguration - SendGrid"); }
public static void Main(string[] args) { JobHostConfiguration config = new JobHostConfiguration(); FilesConfiguration filesConfig = new FilesConfiguration(); // See https://github.com/Azure/azure-webjobs-sdk/wiki/Running-Locally for details // on how to set up your local environment if (config.IsDevelopment) { config.UseDevelopmentSettings(); filesConfig.RootPath = @"c:\temp\files"; } config.UseFiles(filesConfig); config.UseTimers(); config.UseSample(); config.UseCore(); var sendGridConfiguration = new SendGridConfiguration() { ToAddress = "*****@*****.**", FromAddress = new MailAddress("*****@*****.**", "WebJobs Extensions Samples") }; config.UseSendGrid(sendGridConfiguration); ConfigureTraceMonitor(config, sendGridConfiguration); EnsureSampleDirectoriesExist(filesConfig.RootPath); WebHooksConfiguration webHooksConfig = new WebHooksConfiguration(); webHooksConfig.UseReceiver<GitHubWebHookReceiver>(); config.UseWebHooks(webHooksConfig); JobHost host = new JobHost(config); host.Call(typeof(MiscellaneousSamples).GetMethod("ExecutionContext")); host.Call(typeof(FileSamples).GetMethod("ReadWrite")); host.Call(typeof(SampleSamples).GetMethod("Sample_BindToStream")); host.Call(typeof(SampleSamples).GetMethod("Sample_BindToString")); host.Call(typeof(TableSamples).GetMethod("CustomBinding")); host.RunAndBlock(); }
public void DefaultMessageProperties_CreatesExpectedMessage() { SendGridAttribute attribute = new SendGridAttribute(); SendGridConfiguration config = new SendGridConfiguration { ApiKey = "12345", FromAddress = new MailAddress("*****@*****.**", "Test2"), ToAddress = new MailAddress("*****@*****.**", "Test") }; SendGridMessage message = new SendGridMessage { Subject = "TestSubject", Text = "TestText" }; SendGridHelpers.DefaultMessageProperties(message, config, attribute); Assert.Same(config.FromAddress, config.FromAddress); Assert.Equal("*****@*****.**", message.To.Single().Address); Assert.Equal("TestSubject", message.Subject); Assert.Equal("TestText", message.Text); }
public void DefaultMessageProperties_CreatesExpectedMessage() { SendGridAttribute attribute = new SendGridAttribute(); SendGridConfiguration config = new SendGridConfiguration { 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, config, attribute); Assert.Same(config.FromAddress, config.FromAddress); Assert.Equal("*****@*****.**", message.Personalizations.Single().Tos.Single().Email); Assert.Equal("TestSubject", message.Subject); Assert.Equal("TestText", message.Contents.Single().Value); }
public SendGridClient(IHttpClient httpClient, IOptions <EmailConfiguration> config) { _httpClient = httpClient; _config = config.Value.SendGrid; }
public SendGridEmailSender(ILogger <SendGridEmailSender> logger, SendGridConfiguration configuration, ISendGridClient client) { _logger = logger; _configuration = configuration; _client = client; }
public SendGridMailAsyncCollector(SendGridConfiguration config, SendGridAttribute attribute, ISendGridClient sendGrid) { _config = config; _attribute = attribute; _sendGrid = sendGrid; }
public EmailSender(IOptions <SendGridConfiguration> options) { this.options = options.Value; }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { var authenticationConfiguration = new AuthenticationConfiguration() { LoginUrl = Configuration.GetValue <string>("authentication:loginUrl"), LogoutUrl = Configuration.GetValue <string>("authentication:logoutUrl"), CookieName = Configuration.GetValue <string>("authentication:cookieName"), Key = Configuration.GetValue <string>("authentication:key"), KeyPassword = Configuration.GetValue <string>("authentication:keyPassword") }; services.AddSingleton(authenticationConfiguration); var emailConfiguration = new EmailConfiguration() { FromEmailAddress = Configuration.GetValue <string>("email:fromEmailAddress"), FromEmailName = Configuration.GetValue <string>("email:fromEmailName"), EmailVerificationUrl = Configuration.GetValue <string>("email:emailVerificationUrl"), }; services.AddSingleton(emailConfiguration); var sendGridConfiguration = new SendGridConfiguration() { ApiKey = Configuration.GetValue <string>("sendGrid:apiKey"), }; services.AddSingleton(sendGridConfiguration); DatabaseMigrator.MigrateDatabase(Configuration.GetDatabaseConnectionString()); services.AddDbContext <CloakedDaggerDbContext>(options => { options.UseNpgsql(Configuration.GetDatabaseConnectionString()); }); services.AddTransient <IUserRepository, UserRepository>(); services.AddTransient <IRoleRepository, RoleRepository>(); services.AddTransient <IUserRoleRepository, UserRoleRepository>(); services.AddTransient <IUserRegistrationKeyRepository, UserRegistrationKeyRepository>(); services.AddTransient <IUserRegistrationKeyUseRepository, UserRegistrationKeyUseRepository>(); services.AddTransient <IUserEmailVerificationRequestRepository, UserEmailVerificationRequestRepository>(); services.AddTransient <IResourceRepository, ResourceRepository>(); services.AddTransient <IResourceScopeRepository, ResourceScopeRepository>(); services.AddTransient <IScopeRepository, ScopeRepository>(); services.AddTransient <IClientRepository, ClientRepository>(); services.AddTransient <IClientEventRepository, ClientEventRepository>(); services.AddTransient <IPersistedGrantRepository, PersistedGrantRepository>(); services.AddTransient <ILoginService, LoginService>(); services.AddTransient <IUserService, UserService>(); services.AddTransient <IUserRegistrationKeyService, UserRegistrationKeyService>(); services.AddTransient <IResourceService, ResourceService>(); services.AddTransient <IResourceScopeService, ResourceScopeService>(); services.AddTransient <IClientService, ClientService>(); services.AddTransient <IPasswordHasher, ArgonPasswordHasher>(); //Email Stuff services.AddTransient <IEmailSender, SendGridEmailSender>(); services.AddTransient <IEmailService, EmailService>(); var entityMapperConfig = new MapperConfiguration(config => { config.CreateMap <ResourceScopeEntity, ResourceScopeViewModel>() .ForMember(vm => vm.Name, cfg => cfg.MapFrom(rs => rs.ScopeEntity.Name) ) .ForMember(vm => vm.Description, cfg => cfg.MapFrom(rs => rs.ScopeEntity.Description) ); config.CreateMap <ResourceEntity, ResourceViewModel>(); config.CreateMap <UserRegistrationKeyEntity, UserRegistrationKeyViewModel>(); }); var entityMapper = new Mapper(entityMapperConfig); services.AddSingleton <IMapper>(entityMapper); services.AddControllers() .AddNewtonsoftJson(options => { options.SerializerSettings.Converters.Add(new JsonDateEpochConverter()); options.SerializerSettings.Converters.Add( new MapperJsonConverter <ResourceEntity, ResourceViewModel>(entityMapper)); options.SerializerSettings.Converters.Add(new MapperJsonConverter <ResourceScopeEntity, ResourceScopeViewModel>(entityMapper)); options.SerializerSettings.Converters.Add(new MapperJsonConverter <UserRegistrationKeyEntity, UserRegistrationKeyViewModel>(entityMapper)); }); services.AddSingleton(Log.Logger); // Identity Server / OAuth2 var isBuilder = services.AddIdentityServer(options => { options.UserInteraction.LoginUrl = authenticationConfiguration.LoginUrl; }) .AddClientStore <ClientStoreAdapter>() .AddResourceStore <ResourceStoreAdapter>() .AddPersistedGrantStore <PersistedGrantStoreAdapter>() .AddProfileService <ProfileServiceAdapter>(); if (string.IsNullOrWhiteSpace(authenticationConfiguration.Key)) { isBuilder.AddDeveloperSigningCredential(); } else { isBuilder.AddSigningCredential(LoadAuthenticationSigningKey(authenticationConfiguration)); } // Add this after we configure Identity Server, otherwise it overrides the settings or at least the // OnRedirectToLogin handler services.AddAuthentication(CloakedDaggerAuthenticationSchemes.Default) .AddCookie(CloakedDaggerAuthenticationSchemes.Default, options => { options.LogoutPath = authenticationConfiguration.LogoutUrl; options.Cookie.Name = authenticationConfiguration.CookieName; options.Events.OnRedirectToLogin = context => { // Don't want it to redirect to a different URL when not logged in, just return a 401 context.Response.StatusCode = (int)HttpStatusCode.Unauthorized; return(Task.CompletedTask); }; options.Events.OnRedirectToAccessDenied = context => { context.Response.StatusCode = (int)HttpStatusCode.Forbidden; return(Task.CompletedTask); }; }) .AddCookie(CloakedDaggerAuthenticationSchemes.Partial, options => { options.LogoutPath = authenticationConfiguration.LogoutUrl; options.Cookie.Name = $"{authenticationConfiguration.CookieName}__{CloakedDaggerAuthenticationSchemes.Partial}"; options.Events.OnRedirectToLogin = context => { // Don't want it to redirect to a different URL when not logged in, just return a 401 context.Response.StatusCode = (int)HttpStatusCode.Unauthorized; return(Task.CompletedTask); }; options.Events.OnRedirectToAccessDenied = context => { context.Response.StatusCode = (int)HttpStatusCode.Forbidden; return(Task.CompletedTask); }; }); }
public SendGridEmail(SendGridConfiguration configuration) { _configuration = configuration; }
public SendMailMessageDispatcher(SendGridConfiguration configuration, IMessageDispatchNotifier notifier) : base(notifier) { this.configuration = configuration; }
public EmailNotificationStrategy(IOptions <SendGridConfiguration> options) { _options = options.Value; _client = new SendGridClient(_options.ApiKey); }
public SendGridExtensionConfig(SendGridConfiguration sendGridConfig) { _sendGridConfig = sendGridConfig; }