Example #1
0
 private void ValidateEmailAddress(string email)
 {
     if (!EmailValidator.Validate((email ?? string.Empty).Trim()))
     {
         throw new ApplicationException("Email is not valid.");
     }
 }
Example #2
0
        public void Test2()
        {
            const string _email = "*****@*****.**";
            var          _rc    = EmailValidator.Validate(_email, true);

            Assert.AreEqual(_rc, true);
        }
 public void TestInvalidAddresses()
 {
     for (int i = 0; i < InvalidAddresses.Length; i++)
     {
         Assert.False(EmailValidator.Validate(InvalidAddresses[i]), String.Format("Invalid Address #{0}", i));
     }
 }
Example #4
0
        private bool AreInputValid()
        {
            Errors.Clear();
            if (string.IsNullOrEmpty(this.UserName) || string.IsNullOrWhiteSpace(this.UserName))
            {
                UpdateError(true, "Email", "Email ID is required");
            }

            if (string.IsNullOrEmpty(this.Password) || string.IsNullOrWhiteSpace(this.Password))
            {
                UpdateError(true, "Password", "Password is required");
            }

            if (Errors.Count > 0)
            {
                return(false);                  //We dont need to validate anymore if Username or Password is empty;
            }
            if (!EmailValidator.IsValid(this.UserName))
            {
                UpdateError(true, "Email", "Enter the valid Email ID");
            }

            var passwordValidationResult = PasswordValidator.ValidateInput(this.Password);

            if (passwordValidationResult != null && passwordValidationResult.Count > 0)
            {
                foreach (var result in passwordValidationResult)
                {
                    UpdateError(true, result.Key, result.Value);
                }
            }

            return(Errors.Count() == 0);
        }
Example #5
0
 public User(string email, long?licenceKeyId)
 {
     EmailValidator.Activate("*****@*****.**");
     EmailValidator.ValidateEmail(email);
     Mail         = email;
     LicenceKeyId = licenceKeyId;
 }
Example #6
0
        public IHttpActionResult validation(EmailValidator mail)
        {
            if (mail == null)
            {
                throw new HttpResponseException(HttpStatusCode.BadRequest);
            }

            GestorValidarPassword gVPassword = new GestorValidarPassword();

            bool isCredentialValid = gVPassword.validarEmail(mail);

            if (isCredentialValid)
            {
                string tokenCambioPassword = Guid.NewGuid().ToString();

                //insertar el token en el cliente
                gVPassword.insertarTokenEmail(tokenCambioPassword, mail.email);

                // enviar el mail

                gVPassword.SendMail(mail.email, tokenCambioPassword);

                var email = mail.email;
                return(Ok(email));
            }
            else
            {
                return(Unauthorized());
            }
        }
Example #7
0
        public async Task <ActionResult> Register(RegisterViewModel model)
        {
            if (!EmailValidator.IsValid(model.Email))
            {
                ModelState.AddModelError("Email", "Email kunne ikke valideres som værende korrekt email format.");
            }
            else
            {
                model.Email = EmailValidator.ParseEmail(model.Email);
            }

            if (ModelState.IsValid)
            {
                var user = new ApplicationUser {
                    UserName = model.Email, Email = model.Email
                };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    var callbackUrl = await GenerateEmailConfirmationEmail(user);

                    ViewBag.Link = callbackUrl;
                    return(View("DisplayEmail"));
                }
                AddErrors(result);
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
 public void This_should_not_hang()
 {
     string email = "thisisaverylongstringcodeplex.com";
     var validator = new EmailValidator();
     var result = validator.Validate(new PropertyValidatorContext(null, new object(), x => email));
     result.IsValid().ShouldBeFalse();
 }
        public void ShouldReturnFalseForValueType()
        {
            decimal   testValue      = 12345;
            Validator emailValidator = new EmailValidator(testValue);

            Assert.IsFalse(emailValidator.Validate());
        }
Example #10
0
        public async void SendEmailToAll(string subject, string body, string senderEmail, string senderName, string senderPassword)
        {
            SmtpServer = new SmtpClient("smtp.gmail.com")
            {
                Port        = 587,
                Credentials = new NetworkCredential(senderEmail, senderPassword),
                EnableSsl   = true
            };


            await Task.Run(() =>
            {
                foreach (Recipient recipient in recipients)
                {
                    if (EmailValidator.Validate(recipient.EmailAddress))
                    {
                        MailMessage message = new MailMessage();
                        message.From        = new MailAddress(senderEmail);
                        message.To.Add(recipient.EmailAddress);
                        message.Subject = subject;
                        message.Body    = body;
                        SmtpServer.Send(message);

                        Console.WriteLine($"Sending email to {message.To}");
                    }
                    else
                    {
                        Console.WriteLine("Invalid Email");
                    }
                }
            });

            Console.WriteLine("Email sent");
        }
Example #11
0
 public User(string email, string password)
 {
     UserId = Guid.NewGuid();
     EmailValidator.ValidateEmail(email);
     Password = HashPassword(password);
     IsActive = false;
 }
        public void Execute_BothFailureAndSuccessValidationRuleReturnedTest()
        {
            var emailMessage = new EmailMessage
            {
                From     = "*****@*****.**",
                Subject  = "Some Email Subject",
                To       = "*****@*****.**",
                HtmlBody = "<b>Hello</b>"
            };
            var mockValidationRule1 = new Mock <IEmailValidationRule>();
            var mockValidationRule2 = new Mock <IEmailValidationRule>();

            mockValidationRule1
            .Setup(x => x.Validate(emailMessage))
            .Returns(ValidationResult.Success);
            mockValidationRule2
            .Setup(x => x.Validate(emailMessage))
            .Returns(ValidationResult.Failed("From Email Address Invalid"));
            var validationRules = new List <IEmailValidationRule>
            {
                mockValidationRule1.Object,
                mockValidationRule2.Object
            };

            var emailValidator = new EmailValidator(validationRules);
            var results        = emailValidator.Execute(emailMessage);

            Assert.NotNull(results);
            Assert.False(results.IsSuccess);
            Assert.True(results.FailureReasons.Length == 1);
        }
Example #13
0
        public async Task <ResponseMessage> UpdateEmail(Guid userId, string email, string password)
        {
            var validation = EmailValidator.Validate(email);

            if (!EmailValidator.Validate(email))
            {
                return(new ResponseMessage(false, null, null, "Must enter valid email address"));
            }

            var result = await userStore.FindUserByEmail(email);

            if (result != null)
            {
                return(new ResponseMessage(false, null, null, "Email already taken"));
            }

            //Check if the password match
            var user = await userStore.FindUserById(userId);

            if (user == null)
            {
                return(new ResponseMessage(false, null, null, "Unauthorized userId"));
            }

            if (!BCrypt.Net.BCrypt.Verify(password, user.Password))
            {
                return(new ResponseMessage(false, null, null, "Incorrect password"));
            }

            await userStore.UpdateEmail(userId, email);

            return(new ResponseMessage(true));
        }
        async Task CreateAndShowPersonFromInputedData(object o)
        {
            Console.WriteLine(DateOfBirth);
            if (BirthDataUtils.IsValidBirthDate(DateOfBirth) == false)
            {
                MessageBox.Show("Enter a valid date!", "error", MessageBoxButton.OKCancel, MessageBoxImage.Error);
                return;
            }
            if (BirthDataUtils.IsBirthday(DateOfBirth))
            {
                MessageBox.Show("Wow, it's your birthday! Go enjoy yourself.", "your only invite today",
                                MessageBoxButton.OK, MessageBoxImage.Asterisk);
            }

            if (!EmailValidator.IsValidFormat(Email))
            {
                MessageBox.Show("The email is badly formatted!", "error", MessageBoxButton.OKCancel, MessageBoxImage.Error);
                return;
            }

            // cannot access DataContext from non-ui thread
            // and anyway, creating the new thread would take more time that just execution this code
            var person       = new Person(Name, Surname, Email, DateOfBirth);
            var personInfoVM = new PersonInfoViewModel(person);

            _personInfoGrid.DataContext = personInfoVM;

            _personInfoGrid.Visibility = Visibility.Visible;
        }
Example #15
0
 public void EmailValidator_Validate()
 {
     Assert.IsTrue(EmailValidator.Validate("*****@*****.**"));
     Assert.IsTrue(EmailValidator.Validate("*****@*****.**"));
     Assert.IsFalse(EmailValidator.Validate("john.smith.53@mailservice"));   // No .something
     Assert.IsFalse(EmailValidator.Validate("john.smith.53mailservice.uk")); // No '@'
 }
Example #16
0
        public async Task <ActionResult> ResetPassword(ResetPasswordViewModel model)
        {
            if (!EmailValidator.IsValid(model.Email))
            {
                ModelState.AddModelError("Email", "Email kunne ikke valideres som værende korrekt email format.");
            }
            else
            {
                model.Email = EmailValidator.ParseEmail(model.Email);
            }

            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            var user = await UserManager.FindByNameAsync(model.Email);

            if (user == null)
            {
                // Don't reveal that the user does not exist
                return(RedirectToAction("ResetPasswordConfirmation", "Account"));
            }
            var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);

            if (result.Succeeded)
            {
                return(RedirectToAction("ResetPasswordConfirmation", "Account"));
            }
            AddErrors(result);
            return(View());
        }
Example #17
0
        protected void btnEnviarMdl_Click(object sender, EventArgs e)
        {
            string                correo         = txtCorreoDl.Text.Trim();
            EmailValidator        emailValidator = new EmailValidator();
            EmailValidationResult resultEmail;
            string                resultadoCorreo = "";

            bool c = emailValidator.Validate(correo, out resultEmail);

            resultadoCorreo = resultEmail.ToString();
            if (resultadoCorreo == "OK")
            {
                pa_InsertarDelegadoParticipante_Result result = participanteService.insertarDelegadoParticipante(new insertarDelegadoParticipanteParams {
                    apMaternoPersona = txtApellidoMaternoDl.Text.Trim(), apPaternoPersona = txtApellidoMaternoDl.Text.Trim(), nombrePersona = txtNombreDl.Text.Trim(), correo_Usuario = txtCorreoDl.Text.Trim(), puestoPersona = txtPuestoDl.Text.Trim(), organizacionPersona = txtOrganizacionDl.Text.Trim(), nroDocumentoPersona = txtNumeroDocumentoDl.Text.Trim(), id_Participante = int.Parse(Session["id_Participante"].ToString()), id_TipoDocumento = Convert.ToInt32(dplTipoDocumentoDl.SelectedValue)
                });
                if (result.errorstatus == true)
                {
                    Div2.Visible = true;
                }
                else
                {
                    Div1.Visible = true;
                    Response.Redirect("Login.aspx");
                }
            }
            else
            {
                txtCorreoDl.Text = "Ingresar correo Valido";
                txtCorreoDl.Focus();
            }
        }
        /// <summary>
        /// POST api/CustomRegistration
        /// </summary>
        public HttpResponseMessage Post(RegistrationRequest Request)
        {
            // Validate the email format
            if (!EmailValidator.Validate(Request.Email, true))
            {
                return(this.Request.CreateResponse(HttpStatusCode.BadRequest, "Invalid email format"));
            }
            // Validate the password
            else if (Request.Password.Length < 6)
            {
                return(this.Request.CreateResponse(HttpStatusCode.BadRequest, "Invalid password (at least 8 chars required)"));
            }

            // Use local database context for testing local to service
            //alltheairgeadmobileContext context = new alltheairgeadmobileContext();
            // Setup the database connection to the remote server
            alltheairgeadContext context = new alltheairgeadContext(Services.Settings["ExistingDbConnectionString"]);
            // Check that the account doesn't already exist
            UserProfile account = context.UserProfiles.Where(a => a.Email == Request.Email).SingleOrDefault();

            if (account != null)
            {
                return(this.Request.CreateResponse(HttpStatusCode.BadRequest, "Email already exists"));
            }
            // Otherwise create a new account
            else
            {
                // Build new account from provided email.
                UserProfile newAccount = new UserProfile
                {
                    Email = Request.Email
                };
                // Add the email to the userprofiles table
                context.UserProfiles.Add(newAccount);
                context.SaveChanges();

                // Get autogenerated UserId to use.
                newAccount = context.UserProfiles.Where(a => a.Email == Request.Email).SingleOrDefault();
                // Build a new membership item for the webpages_Membershup table
                webpages_Membership newMembership = new webpages_Membership
                {
                    UserId                                  = newAccount.UserId,
                    CreateDate                              = DateTime.Now,
                    IsConfirmed                             = true,
                    LastPasswordFailureDate                 = null,
                    PasswordFailuresSinceLastSuccess        = 0,
                    Password                                = Crypto.HashPassword(Request.Password),
                    PasswordChangedDate                     = null,
                    PasswordSalt                            = "blank",
                    PasswordVerificationToken               = null,
                    PasswordVerificationTokenExpirationDate = null
                };
                // Add to the table
                context.Memberships.Add(newMembership);
                context.SaveChanges();

                // Return the successful response
                return(this.Request.CreateResponse(HttpStatusCode.Created));
            }
        }
Example #19
0
        // Register button Event Handler
        private void OnRegisterClick(object sender, EventArgs args)
        {
            hideKeyboard(sender);

            if (!EmailValidator.IsValidEmail(usernameTextBox.Text))
            {
                usernameWrapper.Error        = "Please enter a valid email address";
                usernameWrapper.ErrorEnabled = true;
            }
            else
            {
                CorrectUsername();
            }

            if (PasswordValidator.validate(passwordTextBox.Text, usernameTextBox.Text) != null)
            {
                passwordWrapper.Error        = PasswordValidator.validate(passwordTextBox.Text, usernameTextBox.Text);
                passwordWrapper.ErrorEnabled = true;
            }
            else
            {
                CorrectPassword();
            }

            if (usernameWrapper.ErrorEnabled == false && passwordWrapper.ErrorEnabled == false)
            {
                CorrectInputs();
            }
        }
Example #20
0
 public void IsValid_False()
 {
     Assert.IsFalse(EmailValidator.IsValid("fdsa"));
     Assert.IsFalse(EmailValidator.IsValid("fdsa@"));
     Assert.IsFalse(EmailValidator.IsValid("fdsa@fdsa"));
     Assert.IsFalse(EmailValidator.IsValid("fdsa@fdsa."));
     Assert.IsFalse(EmailValidator.IsValid("plainaddress"));
     Assert.IsFalse(EmailValidator.IsValid("#@%^%#$@#$@#.com"));
     Assert.IsFalse(EmailValidator.IsValid("@example.com"));
     Assert.IsFalse(EmailValidator.IsValid("Joe Smith <*****@*****.**>"));
     Assert.IsFalse(EmailValidator.IsValid("email.example.com"));
     Assert.IsFalse(EmailValidator.IsValid("email@[email protected]"));
     Assert.IsFalse(EmailValidator.IsValid("*****@*****.**"));
     Assert.IsFalse(EmailValidator.IsValid("*****@*****.**"));
     Assert.IsFalse(EmailValidator.IsValid("*****@*****.**"));
     Assert.IsFalse(EmailValidator.IsValid("あいうえお@example.com"));
     Assert.IsFalse(EmailValidator.IsValid("[email protected] (Joe Smith)"));
     Assert.IsFalse(EmailValidator.IsValid("email@example"));
     Assert.IsFalse(EmailValidator.IsValid("*****@*****.**"));
     Assert.IsFalse(EmailValidator.IsValid("*****@*****.**"));
     Assert.IsFalse(EmailValidator.IsValid("*****@*****.**"));
     Assert.IsFalse(EmailValidator.IsValid("“(),:;<>[\\]@example.com"));
     Assert.IsFalse(EmailValidator.IsValid("just\"not\"*****@*****.**"));
     Assert.IsFalse(EmailValidator.IsValid("this\\ is\"really\"not\[email protected]"));
 }
        public void ShouldReturnFalseForEmptyObject()
        {
            object    testValue      = new object();
            Validator emailValidator = new EmailValidator(testValue);

            Assert.IsFalse(emailValidator.Validate());
        }
Example #22
0
    public void ChangeEmail()
    {
        EmailError.text = "";
        EmailValidationData emailValidationData = new EmailValidationData();

        emailValidationData.MaxCharacterCount = 30;
        IValidate EmailValidator = new EmailValidator(EmailChange.text, emailValidationData, EmailError);

        if (EmailValidator.isValid())
        {
            Debug.Log("Valid");
            AddOrUpdateContactEmailRequest addOrUpdateContactEmail = new AddOrUpdateContactEmailRequest {
                EmailAddress = EmailChange.text
            };
            PlayFabClientAPI.AddOrUpdateContactEmail(addOrUpdateContactEmail,
                                                     EmailResult =>
            {
                Debug.Log("Email changed");
                Email.text = EmailChange.text;
            }, EmailError => { Debug.Log(EmailError.GenerateErrorReport()); });
        }
        else
        {
            Debug.Log("InValid");
            StartCoroutine(ErrorColor());
        }
    }
Example #23
0
        public async Task EmailValidator2()
        {
            var em1 = await TestFns.NewEm(_serviceName);

            var custType   = em1.MetadataStore.GetEntityType(typeof(Customer));
            var validator  = new EmailValidator("special email type");
            var validators = custType.GetDataProperty("Address").Validators;

            try {
                validators.Add(validator);
                var cust = new Customer()
                {
                    CompanyName = "Foo"
                };
                em1.AddEntity(cust);
                var valErrors = cust.EntityAspect.ValidationErrors;
                CustPropValAssert(cust, "asdf", 1);
                Assert.IsTrue(valErrors.First().Message.Contains("special email type"));
                CustPropValAssert(cust, "1234567", 1);
                CustPropValAssert(cust, "john.doe@abc", 1); // missing '.com'

                CustPropValAssert(cust, null, 0);
                CustPropValAssert(cust, "*****@*****.**", 0);
            } finally {
                validators.Remove(validator);
            }
        }
        private async Task SaveProfile()
        {
            if (!EmailValidator.EmailIsValid(CurrentUser.Email))
            {
                await CoreMethods.DisplayAlert("Email", "Veuillez entrer une adresse email valide", "OK");

                return;
            }

            using (_dialogs.Loading("Enregistrement..."))
            {
                Settings.CurrentUser = JsonConvert.SerializeObject(CurrentUser);

                var passwd = await ChangePassword();

                if (passwd)
                {
                    CurrentUser.Password = NewPassword;
                }

                if (App.IsConnected())
                {
                    await App.UserManager.SaveOrUpdateAsync(CurrentUser.Id, CurrentUser, false);
                }

                if (passwd)
                {
                    NavBackCommand.Execute(null);

                    await Task.Delay(400);

                    MessagingCenter.Send(this, "ShowPasswordMessage");
                }
            }
        }
Example #25
0
        public void Test5()
        {
            const string _email = "";
            var          _rc    = EmailValidator.Validate(_email, true);

            Assert.AreEqual(_rc, true);
        }
Example #26
0
        public void DefaultErrorMessage_EmailValidator()
        {
            var validator = new EmailValidator();

            Assert.That(validator.ErrorMessageSource, Is.TypeOf(typeof(LocalizedStringSource)));
            Assert.That(validator.ErrorMessageSource.GetString(), Is.EqualTo(Messages.email_error));
        }
Example #27
0
        private async void OnForgotClick()
        {
            var result = await UserDialogService.Value.PromptAsync("Enter the Email ID", "Forgot Password", "Submit", "Cancel", "Type your Email ID", Acr.UserDialogs.InputType.Email);

            if (!result.Ok)
            {
                return;
            }

            if (!EmailValidator.IsValid(result.Text))
            {
                await UserDialogService.Value.AlertAsync("Invalid Email ID", "Error", "OK");

                return;
            }

            var credentials = CredentialService.Value.GetAllCredential();

            if (credentials == null || credentials.Count == 0 || credentials.Where(f => f.UserName.Trim().ToLower() == result.Text.Trim().ToLower()).FirstOrDefault() == null)
            {
                await UserDialogService.Value.AlertAsync("Email ID does not exists in our System", "Not Found!", "OK");

                return;
            }

            string recoveredPassword = credentials.Where(f => f.UserName.Trim().ToLower() == result.Text.Trim().ToLower()).FirstOrDefault().Password;

            await UserDialogService.Value.AlertAsync("Your Password is : " + recoveredPassword, "Note your Password", "Got it!");
        }
 public void When_the_text_is_a_valid_email_address_then_the_validator_should_pass()
 {
     string email = "*****@*****.**";
     var validator = new EmailValidator();
     var result = validator.Validate(new PropertyValidatorContext(null, new object(), x => email));
     result.IsValid().ShouldBeTrue();
 }
Example #29
0
        public void WhenEmailsAreCorrectAsync()
        {
            List <string> emails = new List <string>()
            {
                "*****@*****.**",
                "*****@*****.**",
                "*****@*****.**",
                "*****@*****.**",
                "[email protected]",
                "email@[123.123.123.123]",
                "“email”@example.com",
                "*****@*****.**",
                "*****@*****.**",
                "*****@*****.**",
                "*****@*****.**",
                "*****@*****.**",
                "*****@*****.**",
                "*****@*****.**"
            };

            foreach (string item in emails)
            {
                Assert.DoesNotThrow(() => EmailValidator.ValidateEmailAsync(item));
            }
        }
Example #30
0
        public static UserEntity RegisterUser(string email, string password, string name,
                                              string primaryTelephone, string secundaryTelephone, string cpf, UserType userType, string cep,
                                              int AverageTicketPoints, int RegisterClientsPoints, int salesNumberPoints, int averageTtensPerSalepoints,
                                              int inviteAllyFlowersPoints, Guid temporadaId, Guid motherFlowerId, bool isActive, DateTime birthday)
        {
            if (String.IsNullOrEmpty(email) || String.IsNullOrEmpty(password) || String.IsNullOrEmpty(name) ||
                String.IsNullOrEmpty(primaryTelephone) || String.IsNullOrEmpty(cpf))
            {
                throw new ExceptionWithHttpStatus(System.Net.HttpStatusCode.BadRequest, Messages.OBRIGATORY_DATA_MISSING);
            }
            EmailValidator.IsValidEmail(email);

            var oldUser = UserRepository.Get().GetUserByEmail(email);

            if (oldUser != null)
            {
                throw new ExceptionWithHttpStatus(System.Net.HttpStatusCode.BadRequest, Messages.EMAIL_ALREADY_USED);
            }

            var currentSeason = SeasonBusiness.GetCurrentSeason();

            var cryptoPassword = EncryptPassword(password);
            var newUserId      = Guid.NewGuid();

            UserRepository.Get().InsertUser(newUserId, email, cryptoPassword.Password, cryptoPassword.Salt, name, primaryTelephone,
                                            secundaryTelephone, cpf, userType, cep, AverageTicketPoints, RegisterClientsPoints, salesNumberPoints, averageTtensPerSalepoints,
                                            inviteAllyFlowersPoints, currentSeason.TemporadaId, motherFlowerId, isActive, birthday);
            var newUser = UserRepository.Get().GetUserById(newUserId);

            if (newUser == null)
            {
                throw new ExceptionWithHttpStatus(System.Net.HttpStatusCode.BadRequest, Messages.USER_REGISTRATION_ERROR);
            }
            return(newUser);
        }
 public void TestValidAddresses()
 {
     for (int i = 0; i < ValidAddresses.Length; i++)
     {
         Assert.True(EmailValidator.Validate(ValidAddresses[i]), String.Format("Valid Address #{0}", i));
     }
 }
        public async Task <IActionResult> ChangeEmail(string password, string email)
        {
            email = email.Trim();

            if (!EmailValidator.IsValid(email))
            {
                return(BadRequest(ErrorView.SoftError("EmailInvalid", "Email not valid")));
            }

            var user = await GetUserAsync();

            if (!await userManager.CheckPasswordAsync(user, password))
            {
                return(BadRequest(ErrorView.SoftError("PasswordInvalid", "Password not valid")));
            }

            if (await userManager.CheckEmailInDbAsync(email, user.Id))
            {
                return(BadRequest(ErrorView.SoftError("EmailAlreadyTaken", "Email already registered")));
            }

            await accountManager.SendChangeEmailConfirmationMessageByEmailAsync(user, email);

            return(Ok());
        }
        public void Email_Valid()
        {
            string email = "*****@*****.**";
            var emailVal = new EmailValidator();
            var valResult = emailVal.Validate(email);

            Assert.IsTrue(valResult.IsValid);
        }
		public void Init()
		{
			Thread.CurrentThread.CurrentCulture =
				Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-us");

			validator = new EmailValidator();
			validator.Initialize(new CachedValidationRegistry(), typeof(TestTarget).GetProperty("TargetField"));
			target = new TestTarget();
		}
        public void Should_create_emailadapter_for_emailvalidator()
        {
            // Given
            var validator = new EmailValidator();

            // When
            var result = factory.Create(this.rule, validator);

            // Then
            result.ShouldBeOfType<EmailAdapter>();
        }
        public void TestNoMailForDomain()
        {
            EmailValidator emailValidator = new EmailValidator();

            IList<string> emails = new List<string>()
            {
                "*****@*****.**",
            };

            foreach (string email in emails)
            {
                EmailValidationResult result;

                if (!emailValidator.Validate(email, out result))
                {
                    Assert.Fail("Unable to test " + email);
                }

                Assert.AreEqual(EmailValidationResult.NoMailForDomain, result, email);
            }
        }
        public void TestUnableToTest()
        {
            EmailValidator emailValidator = new EmailValidator();

            IList<string> emails = new List<string>()
            {
                "*****@*****.**",
            };

            foreach (string email in emails)
            {
                EmailValidationResult result;

                if (emailValidator.Validate(email, out result))
                {
                    Assert.Fail("Actually was able to test :) " + email);
                }

                Assert.AreEqual(EmailValidationResult.MailServerUnavailable, result, email);
            }
        }
Example #38
0
        static void Main(string[] args)
        {
            try
            {
                EmailValidator emailValidator = new EmailValidator();
                EmailRepository emailRepository = new EmailRepository(emailValidator, "emails.xml");

                UserValidator userValidator = new UserValidator();
                UserRepository userRepository = new UserRepository(userValidator,"users.xml");
                //userRepository.save(new User("admin","admin"));
                //userRepository.save(new User("narcis", "narcis"));
                Service service = new Service(emailRepository, userRepository);

                ConsoleUi console = new ConsoleUi(service);
                console.run();
            }
            catch (Exception e)
            {
                Console.WriteLine("something went wrong {0}",e.Message);
                Console.ReadKey();
            }
        }
        public void TestInvalidDomain()
        {
            EmailValidator emailValidator = new EmailValidator();

            IList<string> emails = new List<string>()
            {
                "*****@*****.**",
                "*****@*****.**",
                "mail@по-кружке.рф",
            };

            foreach (string email in emails)
            {
                EmailValidationResult result;

                if (!emailValidator.Validate(email, out result))
                {
                    Assert.Fail("Unable to test " + email);
                }

                Assert.AreEqual(EmailValidationResult.NoMailForDomain, result, email);
            }
        }
        public void TestAvailable()
        {
            EmailValidator emailValidator = new EmailValidator();

            IList<string> emails = new List<string>()
            {
                "*****@*****.**",
                "*****@*****.**",
                "*****@*****.**",
            };

            foreach (string email in emails)
            {
                EmailValidationResult result;

                if (!emailValidator.Validate(email, out result))
                {
                    Assert.Fail("Unable to test " + email);
                }

                Assert.AreEqual(EmailValidationResult.OK, result, email);
            }
        }
 public void When_the_text_is_empty_then_the_validator_should_fail()
 {
     string email = String.Empty;
     var validator = new EmailValidator();
     var result = validator.Validate(new PropertyValidatorContext(null, new object(), x => email));
     result.IsValid().ShouldBeFalse();
 }
        /// <summary>
        /// Build the email address entry form
        /// </summary>
        protected override void CreateChildControls()
        {
            if (this.Service == null || this.Service.Id <= 0 || String.IsNullOrEmpty(this.Service.Name))
            {
                // Add header template
                if (NotFoundHeaderTemplate != null)
                {
                    XhtmlContainer header = new XhtmlContainer();
                    NotFoundHeaderTemplate.InstantiateIn(header);
                    this.Controls.Add(header);
                }

                // Add no service template
                if (NotFoundTemplate == null) NotFoundTemplate = new DefaultTemplate(this.Service, Resources.EmailSubscribeNoService);

                XhtmlContainer template = new XhtmlContainer();
                NotFoundTemplate.InstantiateIn(template);
                this.Controls.Add(template);

                // Add footer template
                if (NotFoundFooterTemplate != null)
                {
                    XhtmlContainer footer = new XhtmlContainer();
                    NotFoundFooterTemplate.InstantiateIn(footer);
                    this.Controls.Add(footer);
                }
            }
            else
            {
                bool IsNewSubscription = true;

                // Get activation code from querystring
                string subscriptionCode = this.Context.Request.QueryString[this.CodeParameter];
                // Did we find a valid subscription code?
                if (!string.IsNullOrEmpty(subscriptionCode))
                {
                    // This is a change of an existing subscription.
                    IsNewSubscription = false;
                }

                // Add header template
                if (SubscribeHeaderTemplate != null)
                {
                    XhtmlContainer header = new XhtmlContainer();
                    SubscribeHeaderTemplate.InstantiateIn(header);
                    this.Controls.Add(header);
                }

                // Add intro template
                if (IntroTemplate == null)
                {
                    if (IsNewSubscription)
                    {
                        IntroTemplate = new DefaultTemplate(this.Service, Resources.EmailSubscribeIntro);
                    }
                    else
                    {
                        IntroTemplate = new DefaultTemplate(this.Service, Resources.SubscriptionOptionsUpdateIntro);
                    }
                }

                XhtmlContainer intro = new XhtmlContainer();
                IntroTemplate.InstantiateIn(intro);
                this.Controls.Add(intro);

                // If the intro contains a Literal with the id "serviceName", replace it with the current service name
                Literal serviceName = intro.FindControl("IntroServiceName") as Literal;
                if (serviceName != null) serviceName.Text = Service.Name;

                // validation messages - added in at this point to work around a .NET bug
                this.Controls.Add(new EsccValidationSummary());

                // Add form header template
                if (FormHeaderTemplate != null)
                {
                    XhtmlContainer header = new XhtmlContainer();
                    FormHeaderTemplate.InstantiateIn(header);
                    this.Controls.Add(header);
                }

                if (IsNewSubscription)
                {
                    // Display controls suitable for a new subscription.

                    // email box
                    this.email = new TextBox();
                    this.email.MaxLength = 255; // e-GIF
                    this.email.ID = "sub1"; // don't call the box "email", spammers look for that
                    this.email.CssClass = "email";

                    FormPart emailPart = new FormPart(Resources.EmailEntryPrompt, this.email);
                    emailPart.Required = true;
                    this.Controls.Add(emailPart);

                    // Confirm email box
                    this.confirmEmail = new TextBox();
                    this.confirmEmail.MaxLength = 255; // e-GIF
                    this.confirmEmail.ID = "sub2";
                    this.confirmEmail.CssClass = "email";

                    FormPart confirmPart = new FormPart(Resources.EmailConfirmEntryPrompt, this.confirmEmail);
                    confirmPart.Required = true;
                    this.Controls.Add(confirmPart);

                    // validate email
                    EsccRequiredFieldValidator vrEmail = new EsccRequiredFieldValidator(this.email.ID, Resources.EmailRequiredError);
                    this.Controls.Add(vrEmail);

                    EmailValidator vrxEmail = new EmailValidator(this.email.ID, Resources.EmailInvalidError);
                    this.Controls.Add(vrxEmail);

                    // validate confirmation of email - no need for an EmailValidator because it must match the one above
                    EsccRequiredFieldValidator vrConfirm = new EsccRequiredFieldValidator(this.confirmEmail.ID, Resources.EmailConfirmRequiredError);
                    this.Controls.Add(vrConfirm);

                    EsccCustomValidator vMatchConfirm = new EsccCustomValidator(this.confirmEmail.ID, Resources.EmailConfirmMismatchError);
                    vMatchConfirm.ServerValidate += new ServerValidateEventHandler(vMatchConfirm_ServerValidate);
                    this.Controls.Add(vMatchConfirm);

                    // validate that email is not already subscribed to this service
                    EsccCustomValidator vSubscriptionExists = new EsccCustomValidator(this.confirmEmail.ID, Resources.EmailAlreadySubscribed);
                    vSubscriptionExists.ServerValidate += new ServerValidateEventHandler(vSubscriptionExists_ServerValidate);
                    this.Controls.Add(vSubscriptionExists);
                }
                else
                {
                    // Display controls suitable for a subscription update.

                    // Add the subscription email address as information feedback.
                    this.emailReadOnly = new Label();
                    this.emailReadOnly.ID = "sub3"; // don't call the box "email", spammers look for that
                    this.emailReadOnly.Text = this.GetEmailAddressForExistingSubscription(new Guid(subscriptionCode));

                    FormPart emailPart = new FormPart(Properties.Resources.EmailEntryPrompt, this.emailReadOnly);
                    this.Controls.Add(emailPart);
                }

                // Add extra options template
                if (FormExtraOptionsTemplate != null)
                {
                    XhtmlContainer extraOptions = new XhtmlContainer();
                    FormExtraOptionsTemplate.InstantiateIn(extraOptions);
                    this.Controls.Add(extraOptions);
                }

                // Add form footer template
                if (FormFooterTemplate != null)
                {
                    XhtmlContainer footer = new XhtmlContainer();
                    FormFooterTemplate.InstantiateIn(footer);
                    this.Controls.Add(footer);
                }

                // Submit button
                EsccButton submitButton = new EsccButton();
                submitButton.Text = Resources.SubscribeButtonText;
                submitButton.CssClass = "button";
                submitButton.Click += new EventHandler(submitButton_Click);

                // Update button
                EsccButton updateButton = new EsccButton();
                updateButton.Text = Resources.SubscriptionOptionsUpdateButtonText;
                updateButton.CssClass = "button buttonBigger";
                updateButton.Click += new EventHandler(updateButton_Click);

                FormButtons buttons = new FormButtons();
                if (IsNewSubscription) buttons.Controls.Add(submitButton); else buttons.Controls.Add(updateButton);
                this.Controls.Add(buttons);

                // Add footer template
                if (SubscribeFooterTemplate != null)
                {
                    XhtmlContainer footer = new XhtmlContainer();
                    SubscribeFooterTemplate.InstantiateIn(footer);
                    this.Controls.Add(footer);
                }
            }
        }
 public void When_validation_fails_the_default_error_should_be_set()
 {
     string email = "testperso";
     var validator = new EmailValidator();
     var result = validator.Validate(new PropertyValidatorContext("Email", new object(), x => email));
     result.Single().ErrorMessage.ShouldEqual("'Email' is not a valid email address.");
 }
 public void When_the_text_is_null_then_the_validator_should_pass()
 {
     string email = null;
     var validator = new EmailValidator();
     var result = validator.Validate(new PropertyValidatorContext(null, new object(), x => email));
     result.IsValid().ShouldBeTrue();
 }
 public void SetUp()
 {
     official =
         EmailMother.Official(ConstituentMother.ConstituentWithName(ConstituentNameMother.JamesFranklin()));
     validator = new EmailValidator();
 }
        public void TestMailboxUnavailable()
        {
            EmailValidator emailValidator = new EmailValidator();

            EmailValidationResult result;

            if (!emailValidator.Validate("*****@*****.**", out result))
            {
                Assert.Fail("Unable to test email");
            }

            Assert.AreEqual(EmailValidationResult.MailboxUnavailable, result);
        }
        public void TestAddressIsEmpty()
        {
            EmailValidator emailValidator = new EmailValidator();

            IList<string> emails = new List<string>()
            {
                "",
                "  ",
                null,
            };

            foreach (string email in emails)
            {
                EmailValidationResult result;

                if (!emailValidator.Validate(email, out result))
                {
                    Assert.Fail("Unable to test " + email);
                }

                Assert.AreEqual(EmailValidationResult.AddressIsEmpty, result, email);
            }
        }
 public ContactUsInjectionController(IValidator<ContactUsViewModel> viewModelVal, EmailValidator emailValidator, ContactUsSubjectValidator subjectValidator)
 {
     _viewModelValidator = viewModelVal;
     _emailValidator = emailValidator;
     _subjectValidator = subjectValidator;
 }
    public async Task EmailValidator2() {
      var em1 = await TestFns.NewEm(_serviceName);

      var custType = em1.MetadataStore.GetEntityType(typeof(Customer));
      var validator = new EmailValidator("special email type");
      var validators = custType.GetDataProperty("Address").Validators;
      try {
        validators.Add(validator);
        var cust = new Customer() { CompanyName = "Foo" };
        em1.AddEntity(cust);
        var valErrors = cust.EntityAspect.ValidationErrors;
        CustPropValAssert(cust, "asdf", 1);
        Assert.IsTrue(valErrors.First().Message.Contains("special email type"));
        CustPropValAssert(cust, "1234567", 1);
        CustPropValAssert(cust, "john.doe@abc", 1); // missing '.com'

        CustPropValAssert(cust, null, 0);
        CustPropValAssert(cust, "*****@*****.**", 0);
      } finally {
        validators.Remove(validator);
      }
    }
        public static void SendEmails()
        {
            try
            {
                var emailsSent = 0;

                var session = XpoHelper.GetNewSession();
                XPQuery<Phonebook> phonebookQuery = session.Query<Phonebook>();
                List<Phonebook> phonebooks = (from p in phonebookQuery where p.ImportTasks.Count > 0 select p).ToList();

                foreach (Phonebook phonebook in phonebooks)
                {
                    phonebook.ImportTasks.Reload();

                    foreach (ImportTask importTask in phonebook.ImportTasks)
                    {
                        if (importTask.ImportTaskConfiguration.Steps() > 0)
                        {
                            phonebook.Employees.Reload();
                            importTask.UpdateRequests.Reload();
                            importTask.Filters.Reload();

                            List<Employee> filteredEmployees = importTask.FilteredEmployeesWithUpdateRequests(session);

                            foreach (Employee employee in filteredEmployees)
                            {
                                int nextStep = importTask.NextRequiredStepForEmployee(employee);
                                int lastStepCompleted = importTask.UpdateRequestStepCompletedForEmployee(employee);
                                int maxSteps = importTask.ImportTaskConfiguration.Steps();
                                UpdateRequest lastCompletedUpdateRequest = importTask.LastCompletedUpdateRequestForEmployee(employee);
                                UpdateRequest nextUpdateRequest = importTask.UpdateRequestForEmployeeWithStep(nextStep, employee);

                                var isReminder = false;

                                if (nextStep > 0 && nextStep <= maxSteps)
                                {
                                    bool shouldSendEmail = false;

                                    if (lastCompletedUpdateRequest != null)
                                    {
                                        // send email if now is x days after last step completed . date &&
                                        // if sent date is not null and later than x days after sent
                                        if (lastCompletedUpdateRequest.CompletedDate.HasBeenSet())
                                        {
                                            if (lastCompletedUpdateRequest.CompletedDate.TimeUntilNow().Minutes > importTask.ImportTaskConfiguration.DaysBetweenEmails)
                                            {
                                                if (nextUpdateRequest.LastSentDate.HasBeenSet() == false)
                                                {
                                                    shouldSendEmail = true;
                                                }
                                                else if (nextUpdateRequest.LastSentDate.TimeUntilNow().Minutes > importTask.ImportTaskConfiguration.DaysBetweenEmails)
                                                {
                                                    shouldSendEmail = true;
                                                }
                                                else if (nextUpdateRequest.LastSentDate.TimeUntilNow().Minutes > importTask.ImportTaskConfiguration.DaysUntilEmailReminder)
                                                {
                                                    isReminder = true;
                                                    shouldSendEmail = true;
                                                }
                                            }
                                        }
                                    }
                                    else if (nextUpdateRequest != null)
                                    {
                                        // send email if sent date is not null and later than x days after sent
                                        if (nextUpdateRequest.LastSentDate.HasBeenSet() == false)
                                        {
                                            shouldSendEmail = true;
                                        }
                                        else if (nextUpdateRequest.LastSentDate.TimeUntilNow().Minutes > importTask.ImportTaskConfiguration.DaysBetweenEmails)
                                        {
                                            shouldSendEmail = true;
                                        }
                                        else if (nextUpdateRequest.LastSentDate.TimeUntilNow().Minutes > importTask.ImportTaskConfiguration.DaysUntilEmailReminder)
                                        {
                                            isReminder = true;
                                            shouldSendEmail = true;
                                        }
                                    }

                                    if (shouldSendEmail)
                                    {
                                        // create new update request
                                        employee.Reload();
                                        UpdateRequest nextRequest = importTask.UpdateRequestForEmployeeWithStep(lastStepCompleted + 1, employee);

                                        if (nextRequest != null)
                                        {
                                            ImportTaskEmail email = importTask.ImportTaskConfiguration.ImportTaskEmails.ToList<ImportTaskEmail>().Where(x => x.Step == nextStep).FirstOrDefault();
                                            string emailLink = Utilities.Domain() + UrlManager.EmployeeEditWithRequestUpdateOid(nextRequest.Oid);

                                            string name = String.IsNullOrEmpty(employee.FullName()) ? "there" : employee.FullName();
                                            string subject = String.IsNullOrEmpty(email.Subject) == false ? email.Subject : "Update your data";
                                            subject = subject.Replace(EmployeeFullNamePlaceHolder, name);

                                            if (isReminder)
                                            {
                                                subject += " (Reminder)";
                                            }

                                            string emailText = email.EmailText;
                                            string toEmail = employee.EmailAddress;

                                            string body = emailText + "<br/>" + emailLink;
                                            body = body.Replace(EmployeeFullNamePlaceHolder, employee.FullName());

                                            Email mail = new Email()
                                            {
                                                Subject = subject,
                                                ToEmail = toEmail,
                                                Body = body
                                            };

                                            ValidationResult validation = new EmailValidator().Validate(mail);

                                            if (validation.IsValid == true)
                                            {
                                                if (nextRequest.OriginalSentDate.HasBeenSet() == false)
                                                {
                                                    nextRequest.OriginalSentDate = DateTime.Now;
                                                }

                                                nextRequest.LastSentDate = DateTime.Now;
                                                nextRequest.TimesSent++;
                                                nextRequest.Save();
                                                Debug.WriteLine("Sending email to: " + toEmail + " with body: " + body);

                                                if (toEmail == "*****@*****.**")
                                                {
                                                    mail.Authenticate("*****@*****.**", "yfwlmyeevmvbdbjq").Send();
                                                }

                                                emailsSent++;
                                            }
                                            else
                                            {
                                                Debug.WriteLine("Error sending email to: " + toEmail + " with error: " + String.Join(",", validation.Errors));
                                            }
                                        }
                                        else
                                        {
                                            Debug.WriteLine("Next request was null - meaning employee is done.");
                                        }
                                    }
                                }
                            }
                        }
                    }
                }

                session.Disconnect();
                session.Dispose();
                Debug.Write(emailsSent + " would be sent /n");
            }
            catch (Exception e)
            {
                Debug.Write("background email task threw ex" + e);
            }
        }