public void EmailComposer_Build_HasEmptyTo_ShouldThrowException()
        {
            EmailComposer composer = new EmailComposer();

            Assert.ThrowsException <ArgumentNullException>(
                () => composer.SetFrom("*****@*****.**").SetSubject("Hello world").SetBody("Test").Build());
        }
        public void EmailComposer_Build_HasEmptyFrom_ShouldThrowException()
        {
            EmailComposer composer = new EmailComposer();

            Assert.ThrowsException <ArgumentNullException>(
                () => composer.Build());
        }
示例#3
0
        public async Task Smtp_SendTemplateMail_SimulateDependencyInjection_ShouldSend()
        {
            SmtpCredentials credentials = new SmtpCredentials("smtp.mailtrap.io", "587", "false", "true", "d3538ae47a016d", "d4add3690c408c");

            EmailComposer <TestMailModel> composer = new EmailComposer <TestMailModel>();
            EmailRequest <TestMailModel>  request  = composer
                                                     .SetModel(new TestMailModel {
                Email = "*****@*****.**", Name = "Guy Gadbois"
            })
                                                     .SetSubject("Hello world")
                                                     .SetFrom("*****@*****.**")
                                                     .SetTo("*****@*****.**")
                                                     .SetCc("*****@*****.**")
                                                     .SetBcc("*****@*****.**")
                                                     .Build();

            IMailer mailer = new SmtpMailer(credentials);

            IMailBodyBuilder builder = new MailBodyBuilder(
                new ScribanCompiler(),
                new AppDirectoryTemplateProvider("Templates", ".sbnhtml"),
                new ViewModelTemplateResolver());

            EmailRequest populatedRequest = await builder.BuildAsync(request);

            await mailer.SendMailAsync(populatedRequest);
        }
        public void EmailComposer_Build_HasEmptySubject_ShouldThrowException()
        {
            EmailComposer composer = new EmailComposer();

            Assert.ThrowsException <ArgumentNullException>(
                () => composer.SetFrom("*****@*****.**").Build());
        }
示例#5
0
        public void Write(DataMessage message, XsltTransformation transformation)
        {
            if (message == null || message.Parameters == null || string.IsNullOrEmpty(message.Parameters["EventType"]))
            {
                return;
            }
            messageId = message.Id;


            eventCode = int.Parse(message.Parameters["EventType"]);

            var emailSubscriptions = repository.GetSubscriptions(eventCode, protocolType, message.Id);

            transformation.Load(Resources.EmailTemplate);

            foreach (var emailSubscription in emailSubscriptions)
            {
                Log <PartnerEmailSink> .Info($"Sending email for Message: {message.Id} to {emailSubscription.Email}");

                var attributes = emailSubscription.GeTranformableAttributes();
                attributes.Add("ISIN", message.Parameters["ISIN"]);
                EmailComposer.SendEmail("Product Update",
                                        transformation.Transform(message.Content, attributes),
                                        new List <string> {
                    emailSubscription.Email
                });

                partnerIds.Add(emailSubscription.Id);
            }
        }
        public async Task <UserServiceResponse> RegisterUserAsync(UserRegistration user)
        {
            var response = new UserServiceResponse();

            var existingUser = await this._accountRepository.FindUserByEmailAsync(emailAddress : user.EmailAddress).ConfigureAwait(continueOnCapturedContext: false);

            if (existingUser != null)
            {
                return(response);
            }

            var result = await this._accountRepository.CreateUserAsync(user : user)
                         .ConfigureAwait(continueOnCapturedContext: true);

            if (!result.Succeeded)
            {
                return(response);
            }

            response.IsValidUser = true;

            existingUser = await this._accountRepository.FindUserByEmailAsync(emailAddress : user.EmailAddress)
                           .ConfigureAwait(continueOnCapturedContext: false);

            var emailMessage = EmailComposer.ComposeEmail(existingUser.UserName, existingUser.VerificationCode);

            EmailSender.SendEmail(@"*****@*****.**", existingUser.Email, @"testuser44", emailMessage);

            return(response);
        }
示例#7
0
        private static async Task SendConfirmationMail(string from, string fromPassword, string customerMail, string customerName)
        {
            // Construct the e-mail model
            EmailComposer <WelcomeMailModel> composer = new EmailComposer <WelcomeMailModel>();
            EmailRequest <WelcomeMailModel>  request  = composer
                                                        .SetModel(new WelcomeMailModel {
                Email = customerMail, Name = customerName
            })
                                                        .SetSubject("Welcome to the company!")
                                                        .SetFrom("*****@*****.**")
                                                        .SetTo(customerMail)
                                                        .Build();

            // Creating the body using the following components:
            // * Use Scriban as the template syntax
            // * Store templates in the project under the 'Templates' application directory
            // * Map e-mail templates by the mail model name (WelcomeMailModel -> Welcome.sbnhtml)
            IMailBodyBuilder builder = new MailBodyBuilder(
                new ScribanCompiler(),
                new AppDirectoryTemplateProvider("Templates", ".sbnhtml"),
                new ViewModelTemplateResolver());

            EmailRequest populatedRequest = await builder.BuildAsync(request);

            // When using a gmail account: https://stackoverflow.com/a/25215834/1842261
            SmtpCredentials credentials = new("smtp.gmail.com", "587", "false", "true", from, fromPassword);
            IMailer         mailer      = new SmtpMailer(credentials);
            await mailer.SendMailAsync(populatedRequest);
        }
示例#8
0
        public async Task <APIResponse> NewPassword([FromBody] NewPasswordModel model)
        {
            // validate
            if (BaseValidableModel.IsInvalid(model, out var errFields))
            {
                return(APIResponse.BadRequest(errFields));
            }

            var user       = (DAL.Models.Identity.User)null;
            var audience   = GetCurrentAudience();
            var agent      = GetUserAgentInfo();
            var userLocale = GetUserLocale();

            // check token
            if (!await Core.Tokens.JWT.IsValid(
                    appConfig: AppConfig,
                    jwtToken: model.Token,
                    expectedAudience: JwtAudience.Cabinet,
                    expectedArea: JwtArea.RestorePassword,
                    validStamp: async(jwt, id) => {
                user = await UserManager.FindByNameAsync(id);
                return("");
            }
                    ) || user == null)
            {
                return(APIResponse.BadRequest(nameof(model.Token), "Invalid token"));
            }

            await UserManager.RemovePasswordAsync(user);

            await UserManager.AddPasswordAsync(user, model.Password);

            if (audience != null)
            {
                UserAccount.GenerateJwtSalt(user, audience.Value);
                await DbContext.SaveChangesAsync();
            }

            // notification
            await EmailComposer.FromTemplate(await TemplateProvider.GetEmailTemplate(EmailTemplate.PasswordChanged, userLocale))
            .Initiator(agent.Ip, agent.Agent, DateTime.UtcNow)
            .Send(user.Email, user.UserName, EmailQueue)
            ;

            // activity
            var userActivity = CoreLogic.User.CreateUserActivity(
                user: user,
                type: Common.UserActivityType.Password,
                comment: "Password changed",
                ip: agent.Ip,
                agent: agent.Agent,
                locale: userLocale
                );

            DbContext.UserActivity.Add(userActivity);
            await DbContext.SaveChangesAsync();

            return(APIResponse.Success());
        }
示例#9
0
        public void Unsubscribe(string key)
        {
            var    provider     = new SubscriptionProvider(_subscriptionRepositoryFactory());
            string email        = provider.Unsubscribe(key);
            var    emailMessage = EmailComposer.GetUnsubscribenMail(email);

            EmailSender.SendEmail(emailMessage);
        }
示例#10
0
        public void ConfirmSubscription(string key)
        {
            var provider = new SubscriptionProvider(_subscriptionRepositoryFactory());
            SubscriptionResponse response = provider.Confirm(key);
            var mail = EmailComposer.GetSubscriptionConfirmedMail(response);

            EmailSender.SendEmail(mail);
        }
示例#11
0
        public void Subscribe(SubscriptionInfo subscription)
        {
            var provider = new SubscriptionProvider(_subscriptionRepositoryFactory());
            SubscriptionResponse response = provider.Add(subscription);
            var emailMessage = EmailComposer.GetConfirmSubscriptionMail(response);

            EmailSender.SendEmail(emailMessage);
        }
示例#12
0
        public void ShouldBeAbleToGetNamedEmailBody()
        {
            string        methodName = nameof(ShouldBeAbleToGetNamedEmailBody);
            EmailComposer composer   = SetNamedFormatComposerAndTestTemplate(methodName);
            object        data       = new { Monkey = "Corn", Banana = "Potato" };
            string        body       = composer.GetEmailBody(_testTemplateName, data);

            Expect.AreEqual(_namedFormatContent.NamedFormat(data), body);
        }
        public void CreateRequestMail_ReturnsRequestMail()
        {
            var         composer    = new EmailComposer(GetHolidayApplication());
            MailMessage requestMail = composer.CreateRequestMail();

            Assert.AreEqual(_requester.GetEmail(), requestMail.From);
            Assert.AreEqual(_manager.GetEmail(), requestMail.To);
            Assert.AreEqual("Holiday Request", requestMail.Subject, true);
        }
示例#14
0
        public void ShouldBeAbleToGetEmailBody()
        {
            string        methodName = nameof(ShouldBeAbleToGetEmailBody);
            EmailComposer composer   = SetStringFormatComposerAndTestTemplate(methodName);

            string body = composer.GetEmailBody(_testTemplateName, "Monkey");

            Expect.AreEqual(_stringFormatContent._Format("Monkey"), body);
        }
示例#15
0
        static void Main(string[] args)
        {
            var rootObject       = new RootObject();
            var checkedGamesData = new Dictionary <string, string>();
            var changedGamesData = new Dictionary <string, string>();

            var mail = new EmailComposer();

            mail.InitializeOutlookComposer();

            var outputHandler = new OutputHandler();

            Console.SetOut(outputHandler);

            InitializePaths();
            UpdateTrackedGameData(ref checkedGamesData, ref changedGamesData);
            UpdateTrackedGameSystemData(checkedGamesData);

            try
            {
                using (StreamReader r = new StreamReader(Path.Combine(dataDirectory, "main_data.json")))
                {
                    var json = r.ReadToEnd();
                    rootObject = JsonConvert.DeserializeObject <RootObject>(json);
                    if (rootObject.Usernames is null)
                    {
                        Console.WriteLine("The list of usernames in the 'main_data.json' file is empty.");
                    }
                    else
                    {
                        UpdateTrackedUserData(rootObject, ref checkedGamesData, changedGamesData);
                    }
                }
            }
            catch (FileNotFoundException)
            {
                //FileNotFoundHandler.AbortProgramToDueMissingCriticalFile("main_data.json", dataDirectory);
            }

            WriteRecentChanges(outputHandler, rootObject);
            rootObject.LastAccess = DateTime.Now;
            rootObject.SaveProperties(Path.Combine(dataDirectory, "main_data.json"));
            try
            {
                mail.SendEmail($"RA Scraping Results, " +
                               $"{rootObject.LastAccess.ToString("yyyy/MM/dd, H:mm tt")}",
                               outputHandler.Output.ToString());
            }
            catch (SmtpException)
            {
                File.WriteAllText(
                    Path.Combine(dataDirectory,
                                 $"error_{rootObject.LastAccess.ToString("yyyy-MM-dd  H,mm tt")}.txt"),
                    outputHandler.Output.ToString());
            }
        }
示例#16
0
        public void ShouldSetEmailTemplateInSpecifiedDirectory()
        {
            string        methodName = nameof(ShouldSetEmailTemplateInSpecifiedDirectory);
            EmailComposer composer   = SetStringFormatComposerAndTestTemplate(methodName);

            string   templatePath = Path.Combine(composer.TemplateDirectory.FullName, "TestTemplate.json");
            FileInfo templateFile = new FileInfo(templatePath);

            Expect.IsTrue(templateFile.Exists, "template wasn't written");
        }
        public void CreateRejectionMail_ReturnsRejectedMail()
        {
            var         composer    = new EmailComposer(GetHolidayApplication());
            MailMessage requestMail = composer.CreateRejectionMail();

            Assert.AreEqual(_manager.GetEmail(), requestMail.From);
            Assert.AreEqual(_requester.GetEmail(), requestMail.To);
            Assert.IsTrue(requestMail.Subject.StartsWith("[rejected]",
                                                         StringComparison.InvariantCultureIgnoreCase));
        }
示例#18
0
        protected override async Task OnUpdate()
        {
            _dbContext.DetachEverything();

            var rows = await
                           (from r in _dbContext.EthSending where r.Status == EthereumOperationStatus.Initial select r)
                       .Include(_ => _.User)
                       .Include(_ => _.RelFinHistory)
                       .AsTracking()
                       .Take(_rowsPerRound)
                       .ToArrayAsync(CancellationToken)
            ;

            if (IsCancelled() || rows.Length == 0)
            {
                return;
            }

            var ethAmount = await _ethReader.GetEtherBalance(await _ethWriter.GetEthSender());

            foreach (var r in rows)
            {
                if (IsCancelled() || ethAmount < r.Amount.ToEther())
                {
                    return;
                }

                try {
                    r.Status = EthereumOperationStatus.BlockchainInit;
                    _dbContext.SaveChanges();

                    var tx = await _ethWriter.SendEth(r.Address, r.Amount.ToEther());

                    r.Status        = EthereumOperationStatus.BlockchainConfirm;
                    r.Transaction   = tx;
                    r.TimeNextCheck = DateTime.UtcNow.AddSeconds(60);

                    ethAmount -= r.Amount.ToEther();

                    try {
                        // notification
                        await EmailComposer.FromTemplate(await _templateProvider.GetEmailTemplate(EmailTemplate.ExchangeEthTransferred, Locale.En))
                        .ReplaceBodyTag("REQUEST_ID", r.Id.ToString())
                        .ReplaceBodyTag("ETHERSCAN_LINK", _appConfig.Services.Ethereum.EtherscanTxView + tx)
                        .ReplaceBodyTag("DETAILS_SOURCE", r.RelFinHistory?.SourceAmount ?? "?" + " GOLD")
                        .ReplaceBodyTag("DETAILS_ESTIMATED", r.RelFinHistory?.DestinationAmount ?? "?" + " ETH")
                        .ReplaceBodyTag("DETAILS_ADDRESS", TextFormatter.MaskBlockchainAddress(r.Address))
                        .Send(r.User.Email, r.User.UserName, _notificationQueue)
                        ;
                    } catch { }
                } catch (Exception e) {
                    Logger.Error(e, $"Failed to process #{r.Id}");
                }
            }
        }
示例#19
0
        public async Task <APIResponse> ChangePassword([FromBody] ChangePasswordModel model)
        {
            // validate
            if (BaseValidableModel.IsInvalid(model, out var errFields))
            {
                return(APIResponse.BadRequest(errFields));
            }

            var user = await GetUserFromDb();

            var agent      = GetUserAgentInfo();
            var userLocale = GetUserLocale();

            // first check tfa
            if (user.TwoFactorEnabled && !Core.Tokens.GoogleAuthenticator.Validate(model.TfaCode, user.TfaSecret))
            {
                return(APIResponse.BadRequest(nameof(model.TfaCode), "Invalid 2fa code"));
            }

            // check current password
            if (await UserManager.HasPasswordAsync(user) && (model.Current == null || !await UserManager.CheckPasswordAsync(user, model.Current)))
            {
                return(APIResponse.BadRequest(nameof(model.Current), "Invalid current password"));
            }

            // set new password
            await UserManager.RemovePasswordAsync(user);

            await UserManager.AddPasswordAsync(user, model.New);

            // notification
            await EmailComposer.FromTemplate(await TemplateProvider.GetEmailTemplate(EmailTemplate.PasswordChanged, userLocale))
            .Initiator(agent.Ip, agent.Agent, DateTime.UtcNow)
            .Send(user.Email, user.UserName, EmailQueue)
            ;

            // activity
            var userActivity = CoreLogic.User.CreateUserActivity(
                user: user,
                type: Common.UserActivityType.Password,
                comment: "Password changed",
                ip: agent.Ip,
                agent: agent.Agent,
                locale: userLocale
                );

            DbContext.UserActivity.Add(userActivity);
            await DbContext.SaveChangesAsync();

            return(APIResponse.Success(
                       new ChangePasswordView()
            {
            }
                       ));
        }
示例#20
0
        public void Sendgrid_SendMail_KeyIsEmpty_ShouldThrowException()
        {
            EmailComposer <TestMailModel> composer = new EmailComposer <TestMailModel>();
            EmailRequest <TestMailModel>  request  = composer
                                                     .SetModel(new TestMailModel {
                Email = "*****@*****.**", Name = "Guy Gadbois"
            })
                                                     .SetSubject("Hello world")
                                                     .SetFrom("*****@*****.**")
                                                     .SetTo("*****@*****.**")
                                                     .Build();

            Assert.ThrowsException <ArgumentNullException>(() => new SendGridMailer(""));
        }
示例#21
0
        protected internal virtual void InitializePasswordResetEmail()
        {
            if (!EmailComposer.TemplateExists(PasswordResetEmailName))
            {
                string content = @"<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Transitional//EN"" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"">
<html xmlns = ""http://www.w3.org/1999/xhtml"">  
   <head>
    <meta http - equiv = ""Content-Type"" content = ""text/html; charset=UTF-8"" />       
    <title>{Title}</title>
    <meta name = ""viewport"" content = ""width=device-width, initial-scale=1.0"" />
    </head>
    <body style=""margin: 0; padding: 0;"">
     <table border=""0"" cellpadding=""15"" cellspacing=""0"" width=""100%"">
      <tr>
       <td>
        Hi {UserName},
       </td>
      </tr>
      <tr>
       <td>
        Someone recently requested a password reset for {ApplicationName}.  If this was you click the link below to reset your password.
       </td>
      </tr>
      <tr>
       <td>
        <a href=""{PasswordResetUrl}"">{PasswordResetUrl}</a>
       </td>
      </tr>
      <tr>
       <td>
        If you are unable to click on the link, copy and paste the above link into a browser address bar.
       </td>
      </tr>
      <tr>
       <td>
        If you did not request a password reset for {ApplicationName} you can disregard this email.
       </td>
      </tr>
      <tr>
       <td>
        Thanks,<br>
        The {ApplicationName} team
       </td>
      </tr>
     </table>
    </body>
</html>";
                EmailComposer.SetEmailTemplate(PasswordResetEmailName, content, true);
            }
        }
示例#22
0
        public void Sendgrid_SendMail_KeyIsNotEmpty_ShouldConstruct()
        {
            EmailComposer <TestMailModel> composer = new EmailComposer <TestMailModel>();
            EmailRequest <TestMailModel>  request  = composer
                                                     .SetModel(new TestMailModel {
                Email = "*****@*****.**", Name = "Guy Gadbois"
            })
                                                     .SetSubject("Hello world")
                                                     .SetFrom("*****@*****.**")
                                                     .SetTo("*****@*****.**")
                                                     .Build();

            IMailer mailer = new SendGridMailer("MySGKey");
        }
示例#23
0
        /// <summary>
        /// Sends the mail.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="request">The request.</param>
        /// <returns></returns>
        public async Task SendMailAsync <T>(EmailRequest <T> request)
            where T : class
        {
            EmailComposer composer    = new EmailComposer();
            EmailRequest  mailRequest = composer
                                        .SetSubject(request.Subject)
                                        .SetBody(request.Body)
                                        .SetFrom(request.From)
                                        .SetTo(request.To?.ToArray())
                                        .SetCc(request.Cc?.ToArray())
                                        .SetBcc(request.Bcc?.ToArray())
                                        .Build();

            await base.SendMailAsync(mailRequest).ConfigureAwait(false);
        }
        public void CreateApprovalMail_ReturnsApprovedMail()
        {
            var         composer    = new EmailComposer(GetHolidayApplication());
            MailMessage requestMail = composer.CreateApprovalMail();

            Assert.AreEqual(_manager.GetEmail(), requestMail.From);
            Assert.AreEqual(_requester.GetEmail(), requestMail.CC.First());
            Assert.IsTrue(requestMail.Subject.StartsWith("[approved]",
                                                         StringComparison.InvariantCultureIgnoreCase));

            string hrEmailUser    = ConfigurationManager.AppSettings["hrMail"];
            string hrEmailAddress = string.Format("{0}@{1}", hrEmailUser,
                                                  ConfigurationManager.AppSettings["companyHost"]);
            var expectedHrMail = new MailAddress(hrEmailAddress, hrEmailUser);

            Assert.AreEqual(expectedHrMail, requestMail.To);
        }
示例#25
0
        public void ShouldBeAbleToComposeEmail()
        {
            string        methodName = nameof(ShouldBeAbleToComposeEmail);
            EmailComposer composer   = SetStringFormatComposerAndTestTemplate(methodName);

            string subject = "This is the Subject";
            Email  email   = composer.Compose(subject, _testTemplateName, "Baloney");

            Expect.IsNotNullOrEmpty(email.Config.Subject);
            Expect.IsNotNullOrEmpty(email.Config.Body);

            Expect.AreEqual(subject, email.Config.Subject);

            string body = _stringFormatContent._Format("Baloney");

            Expect.AreEqual(body, email.Config.Body);
        }
示例#26
0
        public void Graph_SendMail_ShouldSend()
        {
            GraphCredentials credentials = new GraphCredentials("clientId", "tenantId", "secret", "from");

            EmailComposer <TestMailModel> composer = new EmailComposer <TestMailModel>();
            EmailRequest <TestMailModel>  request  = composer
                                                     .SetModel(new TestMailModel {
                Email = "*****@*****.**", Name = "Guy Gadbois"
            })
                                                     .SetSubject("Hello world")
                                                     .SetFrom("*****@*****.**")
                                                     .SetTo("*****@*****.**")
                                                     .Build();

            Mock <IMailer> mock = new Mock <IMailer>();

            mock.Setup(foo => foo.SendMailAsync(request)).Returns(Task.CompletedTask);
        }
示例#27
0
        public void ShouldBeAbleToComposeNamedEmail()
        {
            string        methodName = nameof(ShouldBeAbleToComposeNamedEmail);
            EmailComposer composer   = SetNamedFormatComposerAndTestTemplate(methodName);

            string subject = "This is the Subject";
            object data    = new { Monkey = "Baloney", Banana = "Bananas" };
            Email  email   = composer.Compose(subject, _testTemplateName, data);

            Expect.IsNotNullOrEmpty(email.Config.Subject);
            Expect.IsNotNullOrEmpty(email.Config.Body);

            Expect.AreEqual(subject, email.Config.Subject);

            string body = _namedFormatContent.NamedFormat(data);

            Expect.AreEqual(body, email.Config.Body);
        }
示例#28
0
        public void Startup()
        {
            this.template = new EmailTemplate
            {
                Id         = 1,
                Code       = "test",
                Title      = "title",
                Subject    = "#$AppName#",
                IsSystem   = true,
                From       = "#$UserEmail#",
                Notes      = "Just a note",
                Message    = "#$UserName#",
                Parameters = new List <TemplateParameter>()
            };

            var param = new TemplateParameter {
                Id = 10, Title = "Custom", Notes = "Template note", Template = this.template
            };

            this.template.Parameters.Add(param);

            var config = new BBWTConfig {
                App = new AppConfig {
                    Name = "Test Application"
                }
            };
            var user = new User {
                Name = "*****@*****.**", FirstName = "John", Surname = "Green"
            };

            var templateService   = new Mock <IEmailTemplateService>();
            var configService     = new Mock <IConfigService>();
            var membershipService = new Mock <IMembershipService>();

            templateService.Setup(s => s.GetTemplateByCode("test")).Returns(this.template);
            membershipService.Setup(s => s.GetCurrentUser()).Returns(user);
            configService.Setup(s => s.Settings).Returns(config);

            this.composer = new EmailComposer(templateService.Object, configService.Object, membershipService.Object);
        }
示例#29
0
        private void SetEmailComposer(UserManager mgr, ILogger logger)
        {
            Type emailComposerType        = Type.GetType(EmailComposerType);
            Type defaultEmailComposerType = typeof(NamedFormatEmailComposer);

            if (emailComposerType == null)
            {
                emailComposerType = defaultEmailComposerType;
                if (!SuppressMessages)
                {
                    logger.AddEntry("Specified EmailComposerType was not found, will use {0} instead: {1}", LogEventType.Warning, typeof(NamedFormatEmailComposer).Name, EmailComposerType);
                }
            }

            EmailComposer composer = emailComposerType.Construct <EmailComposer>();

            composer.TemplateDirectory = new DirectoryInfo(EmailTemplateDirectoryPath);
            mgr.EmailComposer          = composer;

            mgr.InitializeConfirmationEmail();
            mgr.InitializePasswordResetEmail();
        }
示例#30
0
        public void NotifySubscribers()
        {
            var provider = new SubscriptionProvider(_subscriptionRepositoryFactory());

            provider.DeleteExpiredSubscriptions();

            List <SubscriptionInfo> subscriptions = provider.GetConfirmed();

            DateRange dateRange = new DateRange {
                From = DateTime.Now, To = DateTime.Now.AddDays(3)
            };

            var weatherProvider = new WeatherProvider(_sources);

            foreach (SubscriptionInfo subscription in subscriptions)
            {
                List <DateTime> rainDates = new List <DateTime>();
                Location        coords    = new Location {
                    Latitude = subscription.Latitude, Longitude = subscription.Longitude
                };
                List <Weather> weatherForecast = weatherProvider.GetWeather(dateRange, coords);
                foreach (Weather weather in weatherForecast)
                {
                    if (weather.Precipitation == Precipitation.Rain)
                    {
                        rainDates.Add(weather.Date);
                    }
                }
                if (rainDates.Count > 0)
                {
                    var emailMessage = EmailComposer.GetNotificationMail(subscription, rainDates);
                    EmailSender.SendEmail(emailMessage);
                    provider.UpdateNotifyDate(subscription);
                }
            }
        }