public RestResponse SendEmailWithMailgun(EmailRequestModel emailDetails)
        {
            try
            {
                // Rest client
                var client = new RestClient(ConfigurationManager.AppSettings["MailgunUrl"].ToString())
                {
                    Authenticator = new HttpBasicAuthenticator("api", ConfigurationManager.AppSettings["MailgunAuthenticator"].ToString())
                };

                // Request object for Rest call
                var request = new RestRequest()
                {
                    Resource = "{domain}/messages",
                    Method   = Method.POST
                };
                request.AddParameter("domain", ConfigurationManager.AppSettings["MailgunDomain"].ToString(), ParameterType.UrlSegment);
                request.AddParameter("from", "Hypothesis Technical Assessment <" + ConfigurationManager.AppSettings["MailgunFrom"].ToString() + ">");
                request.AddParameter("to", emailDetails.Email);
                request.AddParameter("cc", ConfigurationManager.AppSettings["CCEmail"].ToString());
                request.AddParameter("subject", ConfigurationManager.AppSettings["MailSubject"].ToString());
                request.AddParameter("text", string.Format(ConfigurationManager.AppSettings["EmailText"].ToString(), emailDetails.Name));
                return((RestResponse)client.Execute(request));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #2
0
        public async Task PostEmail([FromBody] EmailRequestModel model)
        {
            var user = await _userService.GetUserByPrincipalAsync(User);

            if (user == null)
            {
                throw new UnauthorizedAccessException();
            }

            if (user.UsesKeyConnector)
            {
                throw new BadRequestException("You cannot change your email when using Key Connector.");
            }

            var result = await _userService.ChangeEmailAsync(user, model.MasterPasswordHash, model.NewEmail,
                                                             model.NewMasterPasswordHash, model.Token, model.Key);

            if (result.Succeeded)
            {
                return;
            }

            foreach (var error in result.Errors)
            {
                ModelState.AddModelError(string.Empty, error.Description);
            }

            await Task.Delay(2000);

            throw new BadRequestException(ModelState);
        }
Beispiel #3
0
        private AmazonSimpleEmailServiceClient PrepareEmailClient(EmailRequestModel model, SesEmailConfig config)
        {
            // Choose the AWS region of the Amazon SES endpoint you want to connect to. Note that your sandbox
            // status, sending limits, and Amazon SES identity-related settings are specific to a given
            // AWS region, so be sure to select an AWS region in which you set up Amazon SES. Here, we are using
            // the US West (Oregon) region. Examples of other regions that Amazon SES supports are USEast1
            // and EUWest1. For a complete list, see http://docs.aws.amazon.com/ses/latest/DeveloperGuide/regions.html
            Amazon.RegionEndpoint REGION = Amazon.RegionEndpoint.USEast1;

            // Instantiate an Amazon SES client, which will make the service call.
            AmazonSimpleEmailServiceClient client = new AmazonSimpleEmailServiceClient(config.AWSAccessKey, config.AWSSecretKey, REGION);

            client.BeforeRequestEvent += delegate(object sender, RequestEventArgs e)
            {
                WebServiceRequestEventArgs args    = e as WebServiceRequestEventArgs;
                SendEmailRequest           request = args.Request as SendEmailRequest;

                //$"Sending email {model.Subject} to {model.ToAddresses}".Log();
            };

            client.ExceptionEvent += delegate(object sender, ExceptionEventArgs e)
            {
                Console.WriteLine($"Sent email {model.Subject} error: {e.ToString()}");
            };

            client.AfterResponseEvent += delegate(object sender, ResponseEventArgs e)
            {
                WebServiceResponseEventArgs args     = e as WebServiceResponseEventArgs;
                SendEmailResponse           response = args.Response as SendEmailResponse;

                //$"Sent email {model.Subject} to {model.ToAddresses} {response.HttpStatusCode} {response.MessageId}".Log();
            };

            return(client);
        }
Beispiel #4
0
        public async Task Run(Database dc, Workflow wf, ActivityInWorkflow activity, ActivityInWorkflow preActivity)
        {
            var configuration       = (IConfiguration)AppDomain.CurrentDomain.GetData("Configuration");
            EmailRequestModel model = new EmailRequestModel();

            model.Subject     = activity.GetOptionValue("Subject");
            model.ToAddresses = activity.GetOptionValue("ToAddresses");
            model.Body        = activity.GetOptionValue("Body");
            model.Template    = activity.GetOptionValue("Template");
            model.Bcc         = activity.GetOptionValue("Bcc");
            model.Cc          = activity.GetOptionValue("Cc");

            if (!String.IsNullOrEmpty(model.Template))
            {
                var engine = new RazorLightEngineBuilder()
                             .UseFilesystemProject(AppDomain.CurrentDomain.GetData("ContentRootPath").ToString() + "\\App_Data")
                             .UseMemoryCachingProvider()
                             .Build();

                model.Body = await engine.CompileRenderAsync(model.Template, activity.Input.Data);
            }

            var ses = new SesEmailConfig
            {
                VerifiedEmail = configuration.GetSection("AWS:SESVerifiedEmail").Value,
                AWSSecretKey  = configuration.GetSection("AWS:AWSSecretKey").Value,
                AWSAccessKey  = configuration.GetSection("AWS:AWSAccessKey").Value
            };

            activity.Output.Data = await Send(model, ses);
        }
Beispiel #5
0
        private SendEmailRequest PrepareEmailRequest(EmailRequestModel model, String from)
        {
            // Construct an object to contain the recipient address.
            Destination destination = new Destination();

            destination.ToAddresses = model.ToAddresses.Split(',').Select(x => x.Trim()).ToList();
            if (!String.IsNullOrEmpty(model.Bcc))
            {
                destination.BccAddresses = model.Bcc.Split(',').Select(x => x.Trim()).ToList();
            }

            if (!String.IsNullOrEmpty(model.Cc))
            {
                destination.CcAddresses = model.Cc.Split(',').Select(x => x.Trim()).ToList();
            }

            // Create the subject and body of the message.
            Content subject = new Content(model.Subject);

            Body body = new Body();

            body.Html = new Content(model.Body);

            // Create a message with the specified subject and body.
            Message message = new Message(subject, body);

            // Assemble the email.
            return(new SendEmailRequest(from, destination, message));
        }
        public void Send_EmailResultModel_ShouldBeReturnResultWithIsSendedFalse()
        {
            // Arrange
            var emailService = new EmailService();
            var requestModel = new EmailRequestModel
            {
                EmailAccount = new EmailAccountModel
                {
                    HiddenEmail           = "*****@*****.**",
                    EmailFrom             = "*****@*****.**",
                    InputPort             = 80,
                    OutputHost            = "*****@*****.**",
                    Password              = "******",
                    UseDefaultCredentials = 1,
                    InputEnableSSL        = 1,
                    OutputPort            = 80
                },
                EmailTo  = "*****@*****.**",
                TextBody = "Body",
                Subject  = "Subject",
                UserName = "******"
            };

            // Act
            var result = emailService.Send(requestModel);

            // Assert
            Assert.False(result.IsSended);
        }
        public void sendContactRequestEmail(EmailRequestModel crModel)
        {
            string renderedHTML = EmailService.RenderRazorViewToString("~/Views/TestEmail/Index.cshtml", crModel);
            //email payload
            var ActivateCrEmail = new SendMessageRequest(new EmailMessage
            {
                To =
                    new List <EmailAddress> {
                    new EmailAddress {
                        Email = crModel.Email, Name = "Bringpro"
                    }
                },
                FromEmail = ConfigService.MandrillFromEmail,
                Html      = renderedHTML,
                Subject   = "Your bringpro input has been successfully submitted!"
            });
            //sets api key to api key stored in config file - makes easily changeable
            var api = new MandrillApi(ConfigService.MandrillApiKey);

            //Mandrill Requires functions to be set as async.
            //This line of code lets us run void functions asynchronously
            //Purpose - to match interface signatures with sendgrid interface
            //Will be in ALL Mandrill Functions
            Task.Run(async() => await api.SendMessage(ActivateCrEmail));
        }
        public void SendEmailTestForEmptyEmailId()
        {
            // Mock Manager layer and  stub the business method
            var mockManager = new Mock <IEmailManager>();

            // Arrange
            var requestModel = new EmailRequestModel()
            {
                Name  = "Sanket",
                Email = ""
            };

            // Create controller instance
            var api = new EmailController(mockManager.Object)
            {
                Request = new HttpRequestMessage()
                {
                    Properties = { { HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration() } }
                }
            };

            // Act
            var responseObj = api.SendEmail(requestModel);
            var statusCode  = responseObj?.StatusCode;

            // Assert
            Assert.AreEqual(statusCode, HttpStatusCode.BadRequest);
        }
Beispiel #9
0
        public void SendEmailSendGridTest()
        {
            // Mock Utility layer and  stub the business method
            var mockUtility = new Mock <IEmailUtility>();

            mockUtility.Setup(x => x.SendEmailWithMailgun(It.IsAny <EmailRequestModel>())).Returns((new RestResponse()
            {
                StatusCode = HttpStatusCode.BadRequest
            }));
            mockUtility.Setup(x => x.SendEmailWithSendGrid(It.IsAny <EmailRequestModel>()));

            // Arrange
            var emailModel = new EmailRequestModel()
            {
                Name  = "Sanket Chaudhary",
                Email = "*****@*****.**"
            };

            // Create business class instance
            var manager = new EmailManager(mockUtility.Object);

            // Act
            var responseObj = manager.SendEmail(emailModel);

            // Assert
            Assert.AreEqual(responseObj, true);
        }
Beispiel #10
0
        public PlatformApiCollection Codecademy([FromBody] EmailRequestModel emailRequest)
        {
            string value = emailRequest.Email;

            bool exists = false, timedOut = false, driverOld = false;

            var webDriverWaitUntilTimeout = new TimeSpan(0, 0, 5);

            DateTime TestedAt             = DateTime.Now;

            if (value == null)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.UnsupportedMediaType, String.Format("Request Body Error! Empty key/value pair or wrong content type, please use x-www-form-urlencoded.")));
            }

            var driver = new PhantomJSDriver(GetPhantomJSDriverService(driverOld));

            driver.Navigate().GoToUrl("https://www.codecademy.com/");

            WebDriverWait wait = new WebDriverWait(driver, webDriverWaitUntilTimeout);

            try
            {
                var username = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.Name("user[username]")));
                username.SendKeys(RandomString(15));

                var user_email = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.Name("user[email]")));
                user_email.SendKeys(value);

                var user_password = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.Name("user[password]")));
                user_password.SendKeys(RandomString(15));

                var error = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.CssSelector("ul[class^='fieldErrors']")));

                if (error.Text.Contains("Email is already taken"))
                {
                    driver.Quit();
                    exists = true;
                }
            }
            catch (Exception ex)
            {
                if (ex is WebDriverException)
                {
                    timedOut = true;
                }

                driver.Quit();
                exists = false;
            }

            PlatformApiCollection PAC = new PlatformApiCollection
            {
                Platforms = GetPlatformModel("Codecademy", value, exists, TestedAt, GetPoints(exists, 4), timedOut)
            };

            CalculateTotalPoints(exists, value, "Codecademy", GetPoints(exists, 4));

            return(PAC);
        }
Beispiel #11
0
        public PlatformApiCollection StackOverflowChecker([FromBody] EmailRequestModel emailRequest)
        {
            string value = emailRequest.Email;

            bool exists = false, timedOut = false, driverOld = true;

            var webDriverWaitUntilTimeout = new TimeSpan(0, 0, 15);

            DateTime TestedAt             = DateTime.Now;

            if (value == null)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.UnsupportedMediaType, String.Format("Request Body Error! Empty key/value pair or wrong content type, please use x-www-form-urlencoded.")));
            }

            var driver = new PhantomJSDriver(GetPhantomJSDriverService(driverOld));

            driver.Navigate().GoToUrl("https://stackoverflow.com/users/signup");

            WebDriverWait wait = new WebDriverWait(driver, webDriverWaitUntilTimeout);

            try
            {
                var user_email = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.CssSelector("#email")));
                user_email.SendKeys(value);

                var user_password = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.CssSelector("#password")));
                user_password.SendKeys("FakePassw0rD1@");

                var submit_button = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.CssSelector("#submit-button")));
                submit_button.Click();

                var error = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.CssSelector("#mainbar-full > div:nth-child(2) > div > div")));

                if ((error.Text.Contains("The email address you have used is already registered.")))
                {
                    driver.Quit();
                    exists = true;
                }
            }
            catch (Exception ex)
            {
                if (ex is WebDriverException)
                {
                    timedOut = false;

                    driver.Quit();
                    exists = false;
                }
            }

            PlatformApiCollection PAC = new PlatformApiCollection
            {
                Platforms = GetPlatformModel("StackOverflow", value, exists, TestedAt, GetPoints(exists, 2), timedOut)
            };

            CalculateTotalPoints(exists, value, "Stack Overflow", GetPoints(exists, 2));

            return(PAC);
        }
        /// <summary>
        /// Method to send Emails using thrird party email services
        /// </summary>
        /// <param name="emailDetails">Email details</param>
        /// <returns></returns>
        public bool SendEmail(EmailRequestModel emailDetails)
        {
            RestResponse responseFromMailgun;
            bool         responseReceivedFromMailgun = false;
            bool         isSuccess = false;

            try
            {
                // Call SendEmailWithMailgun() method to send email
                responseFromMailgun = _emailUtility.SendEmailWithMailgun(emailDetails);

                // Set below flag to true if we recieve any response from Mailgun service
                responseReceivedFromMailgun = true;

                // If Mailgun service fails send email using SendGrid service
                if (responseFromMailgun.StatusCode != HttpStatusCode.OK)
                {
                    _emailUtility.SendEmailWithSendGrid(emailDetails);
                }

                isSuccess = true;
            }
            catch (Exception ex) {
                // If exception occurs while calling Mailgun service, send email using SendGrid service
                if (!responseReceivedFromMailgun)
                {
                    _emailUtility.SendEmailWithSendGrid(emailDetails);
                    isSuccess = true;
                }

                isSuccess = false;
            }

            return(isSuccess);
        }
Beispiel #13
0
        private IEmail GetEmailModelProperties(EmailRequestModel model)
        {
            var emailModel   = new EmailTypeFactory().Create(model.Type);
            var properties   = emailModel.GetType().GetProperties();
            var emailContent = new Dictionary <string, string>(model.Properties, StringComparer.OrdinalIgnoreCase);

            foreach (var property in properties)
            {
                var propertyValue = emailContent[property.Name];
                if (property.PropertyType.IsEnum)
                {
                    try
                    {
                        property.SetValue(emailModel, Enum.Parse(property.PropertyType, propertyValue.ToString()));
                    }
                    catch (Exception ex)
                    {
                        throw new DemoException(ex.Message, HttpStatusCode.BadRequest);
                    }
                }
                else
                {
                    property.SetValue(emailModel, propertyValue);
                }
            }

            return(emailModel);
        }
Beispiel #14
0
        public async Task PutEmail([FromBody] EmailRequestModel model)
        {
            var user = await _userService.GetUserByPrincipalAsync(User);

            // NOTE: It is assumed that the eventual repository call will make sure the updated
            // ciphers belong to user making this call. Therefore, no check is done here.
            var ciphers = model.Data.Ciphers.Select(c => c.ToCipher(user.Id));
            var folders = model.Data.Folders.Select(c => c.ToFolder(user.Id));

            var result = await _userService.ChangeEmailAsync(
                user,
                model.MasterPasswordHash,
                model.NewEmail,
                model.NewMasterPasswordHash,
                model.Token,
                ciphers,
                folders,
                model.Data.PrivateKey);

            if (result.Succeeded)
            {
                return;
            }

            foreach (var error in result.Errors)
            {
                ModelState.AddModelError(string.Empty, error.Description);
            }

            await Task.Delay(2000);

            throw new BadRequestException(ModelState);
        }
        public void SendEmailTest()
        {
            // Mock Manager layer and  stub the business method
            var mockManager = new Mock <IEmailManager>();

            mockManager.Setup(x => x.SendEmail(It.IsAny <EmailRequestModel>())).Returns((true));

            // Arrange
            var requestModel = new EmailRequestModel()
            {
                Name  = "Sanket Chaudhary",
                Email = "*****@*****.**"
            };

            // Create controller instance
            var api = new EmailController(mockManager.Object)
            {
                Request = new HttpRequestMessage()
                {
                    Properties = { { HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration() } }
                }
            };

            // Act
            var responseObj   = api.SendEmail(requestModel);
            var responseModel = responseObj?.Content?.ReadAsAsync <bool>()?.Result;

            // Assert
            Assert.AreEqual(responseModel, true);
        }
Beispiel #16
0
        public IActionResult GetToken(EmailRequestModel request)
        {
            var email = _mapper.Map <Email>(request);

            _emailManager.SendEmail(email);

            return(Ok());
        }
Beispiel #17
0
        public PlatformApiCollection MicrosoftChecker([FromBody] EmailRequestModel emailRequest)
        {
            string value = emailRequest.Email;

            bool exists = false, timedOut = false, driverOld = true;

            var webDriverWaitUntilTimeout = new TimeSpan(0, 0, 10);

            DateTime TestedAt             = DateTime.Now;

            if (value == null)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.UnsupportedMediaType, String.Format("Request Body Error! Empty key/value pair or wrong content type, please use x-www-form-urlencoded.")));
            }

            var driver = new PhantomJSDriver(GetPhantomJSDriverService(driverOld));

            driver.Navigate().GoToUrl("https://signup.live.com/signup?wa=wsignin1.0&wtrealm=urn%3afederation%3aMicrosoftOnline&wctx=estsredirect%3d2%26estsrequest%3drQIIAbPSyigpKSi20tdPTE7OL80r0SvPzEvJLy9OrCotStVLzs_Vyy9Kz0wBsaLYgYJJmTk5SYyGRUJcAi8NHT40Gba57pHO3dXv_8dsFiNHTmYZWNMqRj1C5uoHlyYVJxdlFpRk5ucVX2BkfMHI2MXEYmhgbLyJiSXYMcDzBFPzSblbTIL-RemeKeHFbqkpqUWJINWPmHhDi1OL_PNyKkPys1PzJjHz5eSnZ-bFFxelxafl5JcDBYA2FCQml8SXZCZnp5bsYlYxMUpJNLdMMdI1SzQ21DUxNbLUTTQzN9Q1NE82MzQwMzI3T7Y8wLKB8wKLwC0W1tTE4kyjHyyMi1iBHk1Q_1ki7PPJo6VN--j0NV_fnWLVz9COCMwrNc_N1i71jnAKMi2pzMit9M_Rdklxc_JM9Un3Dw_RLijy9_Uo8bQ1tTLcxUlieAAA0&id=&cbcxt=azubill&lw=1&fl=easi2&bk=1468239878&uaid=f04031e931824586bc1b6dba8f4ffc36&cru=https%3a%2f%2flogin.live.com%2flogin.srf%3fwa%3dwsignin1.0%26wtrealm%3durn%253afederation%253aMicrosoftOnline%26wctx%3destsredirect%253d2%2526estsrequest%253drQIIAbPSyigpKSi20tdPTE7OL80r0SvPzEvJLy9OrCotStVLzs_Vyy9Kz0wBsaLYgYJJmTk5SYyGRUJcAi8NHT40Gba57pHO3dXv_8dsFiNHTmYZWNMqRj1C5uoHlyYVJxdlFpRk5ucVX2BkfMHI2MXEYmhgbLyJiSXYMcDzBFPzSblbTIL-RemeKeHFbqkpqUWJINWPmHhDi1OL_PNyKkPys1PzJjHz5eSnZ-bFFxelxafl5JcDBYA2FCQml8SXZCZnp5bsYlYxMUpJNLdMMdI1SzQ21DUxNbLUTTQzN9Q1NE82MzQwMzI3T7Y8wLKB8wKLwC0W1tTE4kyjHyyMi1iBHk1Q_1ki7PPJo6VN--j0NV_fnWLVz9COCMwrNc_N1i71jnAKMi2pzMit9M_Rdklxc_JM9Un3Dw_RLijy9_Uo8bQ1tTLcxUlieAAA0%26id%3d%26cbcxt%3dazubill%26lw%3d1%26fl%3deasi2%26uaid%3df04031e931824586bc1b6dba8f4ffc36%26lc%3d1033&mkt=EN-US&lc=1033&sl=1&lic=1");

            WebDriverWait wait = new WebDriverWait(driver, webDriverWaitUntilTimeout);

            try
            {
                var user_email = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.Id("MemberName")));
                user_email.SendKeys(value);

                var submit_button = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.CssSelector("#iSignupAction")));
                submit_button.Click();

                var error = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.CssSelector("#MemberNameError")));

                if ((error.Text.Contains("is already a Microsoft account.")) || (error.Text.Contains("Try another name or")))
                {
                    driver.Quit();
                    exists = true;
                }
            }
            catch (Exception ex)
            {
                if (ex is WebDriverException)
                {
                    timedOut = true;
                }

                driver.Quit();
                exists = false;
            }

            PlatformApiCollection PAC = new PlatformApiCollection
            {
                Platforms = GetPlatformModel("Microsoft", value, exists, TestedAt, GetPoints(exists, 6), timedOut)
            };

            CalculateTotalPoints(exists, value, "Microsoft", GetPoints(exists, 6));

            return(PAC);
        }
        public EmailResultModel Send(EmailRequestModel input)
        {
            try
            {
                if (input?.EmailAccount == null)
                {
                    //log
                    return(new EmailResultModel
                    {
                        IsSended = false,
                        Message = "Произошла ошибка при отправке сообщения: отсутствуют входные параметры.",
                    });
                }

                MailMessage messageEmail = new MailMessage(input.EmailAccount.EmailFrom, input.EmailTo)
                {
                    Subject    = input.Subject,  // Заголовок (текст, который появляется в push-уведомлениях
                    Body       = input.TextBody, // Тело сообщения
                    IsBodyHtml = false
                };


                if (!string.IsNullOrEmpty(input.EmailAccount.HiddenEmail))
                {
                    messageEmail.Bcc.Add(
                        new MailAddress(input.EmailAccount
                                        .HiddenEmail)); // hiddenEmail добавляет адресат, куда отправлять копию отправленного сообщения.
                }

                // настройка smtp клиента и отправка сообщения.
                using (var smtp = new SmtpClient())
                {
                    smtp.Port = input.EmailAccount.OutputPort;
                    smtp.UseDefaultCredentials = input.EmailAccount.UseDefaultCredentials == 1 ? true : false;
                    smtp.Host        = input.EmailAccount.OutputHost;
                    smtp.EnableSsl   = (TypeEncrypt)input.EmailAccount.OutputEnableSSL == TypeEncrypt.SSL;
                    smtp.Credentials = new NetworkCredential(input.EmailAccount.Login, input.EmailAccount.Password);

                    smtp.Send(messageEmail);
                }

                return(new EmailResultModel
                {
                    IsSended = true,
                    Message = "Сообщение успешно отправлено."
                });
            }
            catch (Exception)
            {
                //log
                return(new EmailResultModel
                {
                    IsSended = false,
                    Message = "Произошла ошибка при отправке сообщения: возникло исключение в системе."
                });
            }
        }
Beispiel #19
0
        public PlatformApiCollection XDAChecker([FromBody] EmailRequestModel emailRequest)
        {
            string value = emailRequest.Email;

            bool exists = false, timedOut = false, driverOld = true;

            var webDriverWaitUntilTimeout = new TimeSpan(0, 0, 10);

            DateTime TestedAt             = DateTime.Now;

            if (value == null)
            {
                throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.UnsupportedMediaType, String.Format("Request Body Error! Empty key/value pair or wrong content type, please use x-www-form-urlencoded.")));
            }

            var driver = new PhantomJSDriver(GetPhantomJSDriverService(driverOld));

            driver.Navigate().GoToUrl("https://forum.xda-developers.com/register.php");

            WebDriverWait wait = new WebDriverWait(driver, webDriverWaitUntilTimeout);

            try
            {
                var username = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.CssSelector("#regusername")));
                username.SendKeys(value);

                var user_password = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.CssSelector("#regpassword")));
                user_password.Click();

                var error = wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.ElementIsVisible(By.CssSelector("#reg_verif_div")));

                if (error.Text.Contains("That username is already in use"))
                {
                    driver.Quit();
                    exists = true;
                }
            }
            catch (Exception ex)
            {
                if (ex is WebDriverException)
                {
                    timedOut = true;
                }

                driver.Quit();
                exists = false;
            }

            PlatformApiCollection PAC = new PlatformApiCollection
            {
                Platforms = GetPlatformModel("XDA Developer", value, exists, TestedAt, GetPoints(exists, 3), timedOut)
            };

            CalculateTotalPoints(exists, value, "XDA Developer", GetPoints(exists, 3));

            return(PAC);
        }
        public void Send_EmailResultModel_ShouldBeReturnResultWithIsSendedFalseAndMessageEmptyParameters()
        {
            // Arrange
            var emailService = new EmailService();
            var requestModel = new EmailRequestModel();

            // Act
            var result = emailService.Send(requestModel);

            // Assert
            Assert.False(result.IsSended);
        }
Beispiel #21
0
        //sends automated email through Contact Request's email address and rendered HTML string.
        public void sendContactRequestEmail(EmailRequestModel crModel)
        {
            string renderedHTML = EmailService.RenderRazorViewToString("~/Views/TestEmail/Index.cshtml", crModel);

            SendGridMessage ActivateCrEmail = new SendGridMessage();

            ActivateCrEmail.AddTo(crModel.Email);
            ActivateCrEmail.From    = new MailAddress("*****@*****.**");
            ActivateCrEmail.Html    = renderedHTML;
            ActivateCrEmail.Subject = "Your BringPro input has been successfully submitted!";
            //ActivateCrEmail.Text = "We appreciate your feedback and will contact you within a few days for support.";
            var sendGridKey = new SendGrid.Web(ConfigService.SendGridWebKey);

            sendGridKey.DeliverAsync(ActivateCrEmail);
        }
Beispiel #22
0
        public static string RenderRazorViewToString(string viewName, EmailRequestModel model)
        {
            var path    = HostingEnvironment.MapPath(viewName);
            var viewRaw = File.ReadAllText(path);

            var key = new NameOnlyTemplateKey("EmailReply", ResolveType.Global, null);

            Engine.Razor.AddTemplate(key, new LoadedTemplateSource(viewRaw));
            StringBuilder sb = new StringBuilder();

            using (StringWriter sw = new StringWriter(sb))
                Engine.Razor.RunCompile(key, sw, null, model);
            {
                return(sb.ToString());
            }
        }
        private async Task SendPasswordResetEmail(string userName, string callbackUrl)
        {
            EmailRequestModel email = new EmailRequestModel()
            {
                Address            = Input.Email,
                PlaceholderContent = new Dictionary <string, string>(),
                TemplateType       = EmailTemplate.ResetPassword,
                SenderName         = "Echipa De Urgenta",
                Subject            = ""
            };

            email.PlaceholderContent.Add("name", userName);
            email.PlaceholderContent.Add("resetPasswordLink", HtmlEncoder.Default.Encode(callbackUrl));

            await _emailSender.SendAsync(email);
        }
        private async Task SendRegistrationEmail(string userName, string callbackUrl)
        {
            EmailRequestModel email = new EmailRequestModel
            {
                Address            = Input.Email,
                PlaceholderContent = new Dictionary <string, string>(),
                TemplateType       = EmailTemplate.AccountConfirmation,
                SenderName         = "Admin De Urgenta",
                Subject            = ""
            };

            email.PlaceholderContent.Add("name", HtmlEncoder.Default.Encode(userName));
            email.PlaceholderContent.Add("confirmationLink", callbackUrl);

            await _emailSender.SendAsync(email);
        }
        public void Send_EmailResultModel_ShouldBeReturnModelFromCatch()
        {
            // Arrange
            var emailService = new EmailService();
            var requestModel = new EmailRequestModel
            {
                EmailAccount = new EmailAccountModel()
            };

            // Act
            var result = emailService.Send(requestModel);

            // Assert
            Assert.False(result.IsSended);
            Assert.Equal(@"Произошла ошибка при отправке сообщения: возникло исключение в системе.", result.Message);
        }
Beispiel #26
0
        private async Task <string> Send(EmailRequestModel model, SesEmailConfig config)
        {
            if (String.IsNullOrEmpty(model.ToAddresses))
            {
                return(String.Empty);
            }

            SendEmailRequest request = PrepareEmailRequest(model, config.VerifiedEmail);

            model.From = request.Source;

            AmazonSimpleEmailServiceClient client = PrepareEmailClient(model, config);

            SendEmailResponse response = await client.SendEmailAsync(request);

            return(response.MessageId);
        }
Beispiel #27
0
        public async Task <IActionResult> Add([FromBody] VmSubscription sub)
        {
            if (!dc.Table <Subscription>().Any(x => x.Email == sub.Email.ToLower()))
            {
                dc.DbTran(() =>
                {
                    dc.Table <Subscription>().Add(new Subscription()
                    {
                        Email    = sub.Email.ToLower(),
                        IsActive = true
                    });
                });

                EmailRequestModel model = new EmailRequestModel();

                model.Subject     = Database.Configuration.GetSection("UserSubscriptionEmail:Subject").Value;
                model.ToAddresses = sub.Email;
                model.Template    = Database.Configuration.GetSection("UserSubscriptionEmail:Template").Value;

                if (engine == null)
                {
                    engine = new RazorLightEngineBuilder()
                             .UseFilesystemProject(Database.ContentRootPath + "\\App_Data")
                             .UseMemoryCachingProvider()
                             .Build();
                }

                var cacheResult = engine.TemplateCache.RetrieveTemplate(model.Template);

                var emailModel = new { Host = Database.Configuration.GetSection("clientHost").Value, Email = sub.Email };

                if (cacheResult.Success)
                {
                    model.Body = await engine.RenderTemplateAsync(cacheResult.Template.TemplatePageFactory(), emailModel);
                }
                else
                {
                    model.Body = await engine.CompileRenderAsync(model.Template, emailModel);
                }

                var    ses     = new AwsSesHelper(Database.Configuration);
                string emailId = await ses.Send(model, Database.Configuration);
            }

            return(Ok());
        }
Beispiel #28
0
        public async Task <IActionResult> SendById(Guid id, [FromBody] EmailRequestModel subjectRequestModel)
        {
            try
            {
                var inviteId = await _inviteControllerService.CreateInvite(id, subjectRequestModel);

                await _emailSender
                .SendEmailAsync(subjectRequestModel.email, "Subject", "Text Message.", "localhost:5000/register/" + inviteId)
                .ConfigureAwait(false);

                return(Ok(inviteId));
            }
            catch (Exception exception)
            {
                return(BadRequest(exception.Message));
            }
        }
Beispiel #29
0
        public bool UsingEmail(EmailRequestModel request)
        {
            if (request.Categories.IsNotSpecified())
            {
                throw new WebApiException(HttpStatusCode.BadRequest, "Incorrect categories");
            }
            if (request.Email.IsNotSpecified())
            {
                throw new WebApiException(HttpStatusCode.BadRequest, "Incorrect email");
            }
            if (request.Name.IsNotSpecified())
            {
                throw new WebApiException(HttpStatusCode.BadRequest, "Incorrect name");
            }

            // ValidateCategories(request.Categories);

            return(m_subscribeRepository.UsingEmail(request));
        }
Beispiel #30
0
 public async Task Handle(SendEmail notification, CancellationToken cancellationToken)
 {
     try
     {
         var email = new EmailRequestModel
         {
             DestinationAddress = notification.DestinationAddress,
             PlaceholderContent = notification.PlaceholderContent,
             TemplateType       = notification.TemplateType,
             SenderName         = notification.SenderName,
             SenderEmail        = notification.SenderEmail,
             Subject            = notification.Subject
         };
         await _emailSender.SendAsync(email, cancellationToken);
     }
     catch (Exception e)
     {
         _logger.LogError(e, "Error sending email");
     }
 }