Ejemplo n.º 1
0
        public void SendAdminEmails_When_executed_x_emails_sent(bool isAthlete, bool isVolunteer, int expected)

        {
            LoadEmails();
            _mockIOrganizationRepository = new Mock <IOrganizationRepository>();
            _worker = new EmailWorker(_mockIOrganizationRepository.Object, _mockEmailRepository.Object);

            _mockIOrganizationRepository.Setup(repository => repository.GetEmails(true, false)).ReturnsAsync(_volunteerList);
            _mockIOrganizationRepository.Setup(repository => repository.GetEmails(false, true)).ReturnsAsync(_athleteList);
            _mockIOrganizationRepository.Setup(repository => repository.GetEmails(true, true)).ReturnsAsync(_jointList);

            const string         fromEmail        = "*****@*****.**";
            const string         subject          = "Sending with SendGrid is Fun";
            const string         plainTextContent = "and easy to do anywhere, even with C#";
            const string         htmlContent      = "<br>Hi {{deacon}}<br><br>&nbsp;&nbsp;&nbsp;&nbsp;Just a reminder you are the Deacon on Duty for {{month}},<br><br>&nbsp;&nbsp;&nbsp;&nbsp;You will responsible to lock up the church on Sundays after worship. If you are not going to be there then it is your responsibility to get another Deacon to close up for you. You are responsible for taking out the trash. Also make sure the offering baskets are out for the next week.<br><br>&nbsp;&nbsp;&nbsp;&nbsp;If you are going to miss more than one Sunday in {{month}} please change with another deacon";
            OrganizationEmailDto message          = new OrganizationEmailDto
            {
                From             = fromEmail,
                HtmlContent      = htmlContent,
                PlainTextContent = plainTextContent,
                Subject          = subject,
                IsVolunteer      = isVolunteer,
                IsAthlete        = isAthlete,
            };

            var actual = _worker.SendAdminEmails(message);

            _mockEmailRepository.Verify(mock => mock.SendEmailString(fromEmail, It.IsAny <string>(), subject, plainTextContent, htmlContent), Times.Exactly(expected));
            Assert.Equal(expected, actual.Result);
        }
Ejemplo n.º 2
0
        public void SendEmailsForSport_WithoutMock(int sportId, int?locationId, int?categoryId, int?teamId, bool?selected, bool?volunteerOnly, int expected)

        {
            IConfiguration config           = new ConfigurationBuilder().AddJsonFile("appsettings.test.json").Build();
            var            connectionString = config["TrainingDatabase"];
            var            options          = new DbContextOptionsBuilder <PwsodbContext>().UseSqlServer(connectionString).Options;

            PwsodbContext context = new PwsodbContext(options);

            var           fromEmail        = config["FromEmail"];
            const string  subject          = "Sending with SendGrid is Fun";
            const string  plainTextContent = "and easy to do anywhere, even with C#";
            const string  htmlContent      = "<br>Hi {{deacon}}<br><br>&nbsp;&nbsp;&nbsp;&nbsp;Just a reminder you are the Deacon on Duty for {{month}},<br><br>&nbsp;&nbsp;&nbsp;&nbsp;You will responsible to lock up the church on Sundays after worship. If you are not going to be there then it is your responsibility to get another Deacon to close up for you. You are responsible for taking out the trash. Also make sure the offering baskets are out for the next week.<br><br>&nbsp;&nbsp;&nbsp;&nbsp;If you are going to miss more than one Sunday in {{month}} please change with another deacon";
            CoachEmailDto message          = new CoachEmailDto
            {
                SportId          = sportId,
                From             = fromEmail,
                HtmlContent      = htmlContent,
                PlainTextContent = plainTextContent,
                Subject          = subject,
                IsVolunteer      = volunteerOnly,
                Selected         = selected,
                ProgramId        = locationId,
                SportTypeId      = categoryId,
                TeamId           = teamId
            };
            ITrainingRepository trainingRepository = new TrainingRepository(context);
            var apiKey = config["ApiKey"];
            IEmailRepository emailRepository = new EmailRepository(apiKey);
            EmailWorker      worker          = new EmailWorker(trainingRepository, emailRepository);


            //var actual = worker.SendEmailsForSport(message);
            //Assert.Equal(expected, actual.Result);
        }
Ejemplo n.º 3
0
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic sportEmail  = JsonConvert.DeserializeObject <CoachEmailDto>(requestBody);


            try
            {
                var apiKey = System.Environment.GetEnvironmentVariable("ApiKey");
                IEmailRepository emailRepository       = new EmailRepository(apiKey);
                var                 connectionString   = System.Environment.GetEnvironmentVariable("SQLAZURECONNSTR_TrainingModel");
                var                 options            = new DbContextOptionsBuilder <PwsodbContext>().UseSqlServer(connectionString).Options;
                PwsodbContext       context            = new PwsodbContext(options);
                ITrainingRepository trainingRepository = new TrainingRepository(context);
                EmailWorker         worker             = new EmailWorker(trainingRepository, emailRepository);
                var                 numOfEmails        = await worker.SendEmailsForSport(sportEmail);

                return((ActionResult) new OkObjectResult(numOfEmails));
            }
            catch (Exception ex)
            {
                return((ActionResult) new BadRequestObjectResult(ex));
            }
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic emailDto    = JsonConvert.DeserializeObject <OrganizationEmailDto>(requestBody);


            try
            {
                var apiKey = System.Environment.GetEnvironmentVariable("ApiKey");
                var isTest = System.Environment.GetEnvironmentVariable("IsTest");
                IEmailRepository emailRepository = new EmailRepository(apiKey);
                var organizationConnectionString = System.Environment.GetEnvironmentVariable("SQLCONNSTR_OrganizationModel");
                var organizationOptions          = new DbContextOptionsBuilder <PwsoContext>().UseSqlServer(organizationConnectionString ?? throw new InvalidOperationException()).Options;
                var organizationContext          = new PwsoContext(organizationOptions);
                IOrganizationRepository organizationRepository = new OrganizationRepository(organizationContext);
                if (isTest == "true")
                {
                    emailDto.IsTesting = true;
                }
                EmailWorker worker      = new EmailWorker(organizationRepository, emailRepository);
                var         numOfEmails = await worker.SendAdminEmails(emailDto);

                return((ActionResult) new OkObjectResult(numOfEmails));
            }
            catch (Exception ex)
            {
                return((ActionResult) new BadRequestObjectResult(ex));
            }
        }
        public IActionResult ChangePlayer([FromBody] PlayerVM model)
        {
            if (model == null || model.Id <= 0)
            {
                return(Ok(0));
            }

            int mistake = 0;
            var player  = _context.Players.SingleOrDefault(p => p.Id == model.Id);

            if (player == null)
            {
                return(Ok(0));
            }
            if (player.Login != model.Login)
            {
                var somePlayer = _context.Players.SingleOrDefault(p => p.Login == model.Login);
                if (somePlayer != null)
                {
                    //This login is already in use!";
                    mistake += -1;
                }
            }

            if (player.Email != model.Email)
            {
                var somePlayer = _context.Players.SingleOrDefault(p => p.Email == model.Email);
                if (somePlayer != null)
                {
                    //This email is already in use!";
                    mistake += -2;
                }
            }

            if (mistake < 0)
            {
                return(Ok(mistake));
            }

            try
            {
                player.Login    = model.Login;
                player.Email    = model.Email;
                player.IsAdmin  = model.IsAdmin;
                player.Password = model.Password;

                if (player.Id == 1)
                {
                    player.IsAdmin = true;
                }

                _context.SaveChanges();

                EmailWorker.SendEmail(model, "Account was successfully changed!");
            }
            catch (Exception) { return(Ok(0)); }
            return(Ok(player.Id));
        }
Ejemplo n.º 6
0
        public void GetEmailsForOrganization_When_executed_create_list_of_SportEmails(bool isAthlete, bool isVolunteer, int expected)

        {
            LoadEmails();
            _mockIOrganizationRepository = new Mock <IOrganizationRepository>();
            _worker = new EmailWorker(_mockIOrganizationRepository.Object, _mockEmailRepository.Object);

            _mockIOrganizationRepository.Setup(repository => repository.GetEmails(true, false)).ReturnsAsync(_volunteerList);
            _mockIOrganizationRepository.Setup(repository => repository.GetEmails(false, true)).ReturnsAsync(_athleteList);
            _mockIOrganizationRepository.Setup(repository => repository.GetEmails(true, true)).ReturnsAsync(_jointList);
            var actual = _worker.GetEmailsForOrganization(isVolunteer, isAthlete);

            Assert.Equal(expected, actual.Result.Count);
        }
        public IActionResult CreatePlayer([FromBody] PlayerVM model)
        {
            if (model == null)
            {
                return(Ok(0));
            }

            int id     = 0;
            var player = _context.Players.SingleOrDefault(p => p.Login == model.Login);

            if (player != null)
            {
                //This login is already in use!";
                id += -1;
            }

            player = null;
            player = _context.Players.SingleOrDefault(p => p.Email == model.Email);
            if (player != null)
            {
                //This email is already in use!";
                id += -2;
            }

            if (id < 0)
            {
                return(Ok(id));
            }

            Player playerToDB;

            try
            {
                playerToDB = new Player()
                {
                    Login    = model.Login,
                    Email    = model.Email,
                    IsAdmin  = model.IsAdmin,
                    Password = model.Password
                };

                _context.Players.Add(playerToDB);
                _context.SaveChanges();

                EmailWorker.SendEmail(model, "Account was successfully registered!");
            }
            catch (Exception) { return(Ok(0)); }
            return(Ok(playerToDB.Id));
        }
        public static async Task <IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            string  requestBody = await new StreamReader(req.Body).ReadToEndAsync();
            dynamic teams       = JsonConvert.DeserializeObject <TournamentDto>(requestBody);


            try
            {
                var apiKey = System.Environment.GetEnvironmentVariable("ApiKey");
                IEmailRepository emailRepository         = new EmailRepository(apiKey);
                var                  connectionString    = System.Environment.GetEnvironmentVariable("SQLAZURECONNSTR_TrainingModel");
                var                  options             = new DbContextOptionsBuilder <PwsodbContext>().UseSqlServer(connectionString).Options;
                PwsodbContext        context             = new PwsodbContext(options);
                ITrainingRepository  trainingRepository  = new TrainingRepository(context);
                IReferenceRepository referenceRepository = new ReferenceRepository(context);
                ReferenceWorker      refWorker           = new ReferenceWorker(referenceRepository);
                EmailWorker          emailWorker         = new EmailWorker(trainingRepository, emailRepository);
                var                  accountSid          = System.Environment.GetEnvironmentVariable("AccountSid");
                var                  authToken           = System.Environment.GetEnvironmentVariable("AuthToken");
                var                  fromPhone           = System.Environment.GetEnvironmentVariable("FromPhone");
                ISmsRepository       smsRepository       = new SmsRepository(accountSid, authToken, fromPhone);
                var                  textWorker          = new TextWorker(trainingRepository, smsRepository);

                foreach (var team in teams.Teams)
                {
                    var emailMessage = refWorker.ChampionshipEmailPreparation(team);
                    var textMessage  = refWorker.ChampionshipTextPreparation(team);
                    var numOfEmails  = await emailWorker.SendEmailsForSport(emailMessage);

                    var numOfSms = await textWorker.SendSmsForSport(textMessage);
                }

                return((ActionResult) new OkObjectResult(1));
            }
            catch (Exception ex)
            {
                return((ActionResult) new BadRequestObjectResult(ex));
            }
        }
Ejemplo n.º 9
0
        public async Task <ActionResult> ForgotPassword(string mail)
        {
            if (string.IsNullOrEmpty(mail) == false)
            {
                var user = await userRepository.GetUserByEmailAsync(mail);

                if (user != null)
                {
                    try
                    {
                        EmailWorker       emailWorker = new EmailWorker();
                        BuildingEmailBody body        = new BuildingEmailBody();
                        string            htmlBody    = body.ForForgotPassword(this.Server.MapPath("~/Common/Email/HtmlBody/ForgotPassword.html"), "uid=" + user.ID.ToString());
                        await emailWorker.SendEmailAsync(user.Email.Mail, "Восстановление пароля", htmlBody);

                        ViewBag.Success = "Письмо отправлено. В течение минуты оно придет к вам на почту.";

                        letterRepository.CreateLetter(new Domain.Core.Letter
                        {
                            Date         = DateTime.Now,
                            EmailID      = user.EmailID,
                            LetterTypeID = 1 //Password recovery
                        });
                        letterRepository.Save();

                        return(PartialView("_ForgotPasswordPartial"));
                    }
                    catch (Exception ex)
                    {
                        ViewBag.ErrorMessage = "Ошибка при отправке письма.";
                        Log.Error(ex, "Ошибка при отправке почты.");
                        return(PartialView("_ForgotPasswordPartial"));
                    }
                }
            }
            ViewBag.NotExist = "Такой почты не существует";
            return(PartialView("_ForgotPasswordPartial"));
        }
Ejemplo n.º 10
0
        public void UpdateUserSettings(SendInfo newInfo)
        {
            SendInfo existingInfo = factory.GetSendInfoDao().Find(newInfo.UserName);

            bool shouldSendEmail = ShouldSendInitialEmail(existingInfo, newInfo.UserEmail, newInfo.SendEmail.Value);
            bool shouldSendSms   = ShouldSendInitialSms(existingInfo, newInfo.UserPhone, newInfo.SendSms.Value);

            existingInfo.Merge(newInfo);

            var _emailWorker = new EmailWorker();

            if (shouldSendEmail)
            {
                _emailWorker.SendEmailInvite(existingInfo.UserName);
            }

            if (shouldSendSms)
            {
                _emailWorker.SendSmsInvite(existingInfo);
            }

            UpdateUserSettingsImpl(existingInfo);
        }
Ejemplo n.º 11
0
        public async Task <ActionResult> ConfirmEmail_WillSendLetter()
        {
            var userProfile = UserStorage.Get();

            if (userProfile != null)
            {
                try
                {
                    EmailWorker       emailWorker = new EmailWorker();
                    BuildingEmailBody body        = new BuildingEmailBody();
                    string            htmlBody    = body.ForConfirmEmail(this.Server.MapPath("~/Common/Email/HtmlBody/ConfirmEmail.html"), "uid=" + userProfile.ID.ToString(), userProfile.Email.Mail);
                    await emailWorker.SendEmailAsync(userProfile.Email.Mail, "Подтверждение почты1", htmlBody);

                    ViewBag.Success = "Письмо отправлено. В течение минуты оно придет к вам на почту.";

                    letterRepository.CreateLetter(new Domain.Core.Letter
                    {
                        Date         = DateTime.Now,
                        EmailID      = userProfile.EmailID,
                        LetterTypeID = 2 //Confirm email
                    });
                    letterRepository.Save();

                    return(PartialView("_ForgotPasswordPartial"));
                }
                catch (Exception ex)
                {
                    ViewBag.ErrorMessage = "Ошибка при отправке письма.";
                    Log.Error(ex, "Ошибка при отправке почты.");
                    return(PartialView("_ForgotPasswordPartial"));
                }
            }

            ViewBag.NotExist = "Авторизуйтесь";
            return(PartialView("_ForgotPasswordPartial"));
        }
Ejemplo n.º 12
0
 public EmailWorkerTest()
 {
     _mockTrainingRepository = new Mock <ITrainingRepository>();
     _mockEmailRepository    = new Mock <IEmailRepository>();
     _worker = new EmailWorker(_mockTrainingRepository.Object, _mockEmailRepository.Object);
 }