Пример #1
0
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var emailAttribute = new EmailAddressAttribute();
            var emails         = value as IList <string>;

            if (!emails?.Any() ?? true)
            {
                return(new ValidationResult("An email is required."));
            }

            if (emails.Count() > 20)
            {
                return(new ValidationResult("You can only submit up to 20 emails at a time."));
            }

            for (var i = 0; i < emails.Count(); i++)
            {
                var email = emails.ElementAt(i);
                if (!emailAttribute.IsValid(email) || email.Contains(" ") || email.Contains("<"))
                {
                    return(new ValidationResult($"Email #{i + 1} is not valid."));
                }

                if (email.Length > 256)
                {
                    return(new ValidationResult($"Email #{i + 1} is longer than 256 characters."));
                }
            }

            return(ValidationResult.Success);
        }
Пример #2
0
 public AtualizarPublicadorCommandValidator()
 {
     RuleFor(pub => pub.PublicadorId).NotEmpty();
     RuleFor(pub => pub.PrimeiroNome).NotNull().NotEmpty()
     .WithMessage("O campo 'Primeiro Nome' é nulo ou está vazio");
     RuleFor(pub => pub.UltimoNome).NotNull().NotEmpty()
     .WithMessage("O campo 'Ultimo Nome' é nulo ou está vazio");
     RuleFor(pub => pub.Privilegio).IsInEnum()
     .WithMessage("O campo 'Privilegio' não tem um valor permitido dentro da enumeração");
     RuleFor(pub => pub.Sexo).IsInEnum()
     .WithMessage("O campo 'Sexo' não tem um valor permitido dentro da enumeração");
     RuleFor(pub => pub.Email).Custom((email, context) =>
     {
         if (!String.IsNullOrEmpty(email))
         {
             var attr   = new EmailAddressAttribute();
             var result = attr.IsValid(email);
             if (!result)
             {
                 context.AddFailure("O campo 'Email' não é um endereço de e-mail válido");
             }
         }
     });
     RuleFor(pub => pub.Telefone).Custom((fone, context) =>
     {
         if (!String.IsNullOrEmpty(fone))
         {
             if (fone.Length < 8 || fone.Length > 11)
             {
                 context.AddFailure("O campo 'Telefone' não está dentro do intervalo de 8 a 11 dígitos");
             }
         }
     });
 }
Пример #3
0
        internal ULoginResp UserLoginAction(ULoginData data)
        {
            UDbTable result;
            var      validate = new EmailAddressAttribute();

            if (validate.IsValid(data.Credential))
            {
                var pass = LoginHelper.HashGen(data.Password);
                using (var db = new UserContext())
                {
                    result = db.Users.FirstOrDefault(u => u.Email == data.Credential && u.Password == pass);
                }

                if (result == null)
                {
                    return(new ULoginResp {
                        Status = false, StatusMsg = "The Username or Password is Incorrect"
                    });
                }

                using (var todo = new UserContext())
                {
                    result.LasIp             = data.LoginIp;
                    result.LastLogin         = data.LoginDateTime;
                    todo.Entry(result).State = EntityState.Modified;
                    todo.SaveChanges();
                }

                return(new ULoginResp {
                    Status = true
                });
            }
            else
            {
                var pass = LoginHelper.HashGen(data.Password);
                using (var db = new UserContext())
                {
                    result = db.Users.FirstOrDefault(u => u.Username == data.Credential && u.Password == pass);
                }

                if (result == null)
                {
                    return(new ULoginResp {
                        Status = false, StatusMsg = "The Username or Password is Incorrect"
                    });
                }

                using (var todo = new UserContext())
                {
                    result.LasIp             = data.LoginIp;
                    result.LastLogin         = data.LoginDateTime;
                    todo.Entry(result).State = EntityState.Modified;
                    todo.SaveChanges();
                }

                return(new ULoginResp {
                    Status = true
                });
            }
        }
        public static void DataType_CustomDataType_ReturnExpected()
        {
            var attribute = new EmailAddressAttribute();

            Assert.Equal(DataType.EmailAddress, attribute.DataType);
            Assert.Null(attribute.CustomDataType);
        }
        public bool IsValidEmail(string text)
        {
            bool result = false;

            try
            {
                result = new EmailAddressAttribute().IsValid(text);
            }
            catch
            {
                return(false);
            }

            if (result)
            {
                foreach (var a in text)
                {
                    if (!char.IsLetter(a) && !char.IsDigit(a) && a != '@' && a != '_' && a != '.')
                    {
                        return(false);
                    }
                }
            }

            return(result);
        }
Пример #6
0
        public JsonResult SaveRegistration(FullUserDetail user)
        {
            Models.Misc.ValidationResult result = new Models.Misc.ValidationResult();

            var foo = new EmailAddressAttribute();

            if (!new EmailAddressAttribute().IsValid(user.Email))
            {
                result.HasValidationFailed = true;
                result.ValidationMsg       = "Invalid Email Format.";
                return(Json(result));
            }
            else if (bl.ValidateUsername(user.Username))
            {
                result.HasValidationFailed = true;
                result.ValidationMsg       = "Please Choose A Different Username.";
                return(Json(result));
            }
            else
            {
                user.Password = EncryptionHelper.Encrypt(user.Password);
                var      userId  = bl.SaveRegistration(user);
                UserInfo newUser = new UserInfo()
                {
                    UserId    = userId,
                    FirstName = user.FirstName
                };
                Session["UserInfo"] = newUser;
            }

            return(Json(result));
        }
Пример #7
0
        private void validateAccountDTO(List <string> errors, AccountDTO dto)
        {
            if (dto == null)
            {
                errors.Add("Account dto cannot be null");
            }
            else
            {
                if (string.IsNullOrEmpty(dto.Password))
                {
                    errors.Add("A password is required");
                }
                else
                {
                    validatePassword(errors, dto.Password);
                }


                if (string.IsNullOrEmpty(dto.Email))
                {
                    errors.Add("A email is required");
                }
                else
                {
                    var check = new EmailAddressAttribute();
                    if (!check.IsValid(dto.Email))
                    {
                        errors.Add("Incorrect email format");
                    }
                }
            }
        }
        public async Task <IActionResult> SaveChanges(int appId, int offerId, string email, string phone, IFormFile file)
        {
            var application = _applicationData.FindById(appId);

            if (application == null)
            {
                return(View("NotFound"));
            }

            string uploadedUri = null;

            if (file != null)
            {
                var uploadSuccess = false;
                using (var stream = file.OpenReadStream())
                {
                    (uploadSuccess, uploadedUri) = await BlobStorageService.UploadToBlob(file.FileName,
                                                                                         _configuration["storageconnectionstring"], null, stream);
                }

                if (uploadSuccess)
                {
                    application.CvFile = uploadedUri;
                }
            }

            PhoneAttribute        phoneAttr  = new PhoneAttribute();
            bool                  phoneValid = phoneAttr.IsValid(phone);
            EmailAddressAttribute emailAttr  = new EmailAddressAttribute();
            bool                  emailValid = emailAttr.IsValid(email);
            bool                  emailFree  = !_jobOfferData.CheckIfEmailIsTaken(email, offerId);

            if (email == application.CommunicationEmail)
            {
                emailFree = true;
            }
            bool success = false;

            if (phoneValid && emailValid && emailFree)
            {
                application.Phone = phone;
                application.CommunicationEmail = email;
                _applicationData.Update(application);
                _applicationData.Commit();
                success = true;
            }

            var result = Json(new
            {
                success,
                phoneValid,
                emailValid,
                emailFree,
                uploadedUri
            });

            System.Threading.Thread.Sleep(700);
            return(result);
        }
Пример #9
0
        public string GetEmailForBackups()
        {
            var emailAddressAttribute = new EmailAddressAttribute();

            return(emailAddressAttribute.IsValid(this.emailAddress)
                ? this.emailAddress
                : string.Empty);
        }
Пример #10
0
 public FormValidator()
 {
     RuleFor(x => x.Email).Must((model, mail) =>
     {
         var emailAddressAttribute = new EmailAddressAttribute();
         return(emailAddressAttribute.IsValid(mail));
     }).WithMessage("Please enter a valid email");
 }
Пример #11
0
        public static bool IsValidEmail(string email)
        {
            var  foo = new EmailAddressAttribute();
            bool bar;

            bar = foo.IsValid(email);
            return(bar);
        }
Пример #12
0
        public async Task <ActionResult> Create(EmailScheduleViewModel emailScheduleViewModel)
        {
            byte[] recipients = null;
            ViewBag.UserEmail = await GetUserInfo(u => u.Email);

            if (Request.Files.Count == 0 || Path.GetExtension(Request.Files[0].FileName).ToLower() != ".csv")
            {
                ModelState.AddModelError("Recipients", "Choose a valid CSV file.");
            }

            else
            {
                using (var ms = new MemoryStream())
                {
                    Request.Files[0].InputStream.CopyTo(ms);
                    recipients = ms.ToArray();
                }
                var recipientsString = Encoding.UTF8.GetString(recipients).Replace("\r", "").Replace("\n", "").TrimEnd(',');
                var emails           = recipientsString.Split(',');
                EmailAddressAttribute emailValidator = new EmailAddressAttribute();
                foreach (var email in emails)
                {
                    if (!emailValidator.IsValid(email))
                    {
                        ModelState.AddModelError("Recipients", email + " is not an email. The format of file must be like this: [email protected], [email protected], [email protected][,]");
                        break;
                    }
                }
            }

            if (ModelState.IsValid)
            {
                emailScheduleViewModel.Recipients = recipients;
                EmailSchedule entity = await MapToEmailSchadle(emailScheduleViewModel);

                if (!EmailScheduleISDuplicate(entity))
                {
                    db.EmailSchedules.Add(entity);
                    db.SaveChanges();
                    try
                    {
                        entity.JobId = BackgroundJob.Schedule(() => sendEmail(entity.Id), new DateTimeOffset(entity.SendDateTime));
                    }
                    catch
                    {
                        db.EmailSchedules.Remove(entity);
                    }
                    finally
                    {
                        db.SaveChanges();
                    }
                    return(RedirectToAction("Index", new { message = "Sending Email was scheduled on " + entity.SendDateTime.ToString() }));
                }
                ModelState.AddModelError("", "You can not send a same massage in one day.");
            }

            return(View(emailScheduleViewModel));
        }
        internal async Task <DataWrapper <InvoiceResponse> > CreateInvoiceCore(Invoice invoice, StoreData store, string serverUrl, double expiryMinutes = 15)
        {
            //TODO: expiryMinutes (time before a new invoice can become paid) and monitoringMinutes (time before a paid invoice becomes invalid)  should be configurable at store level
            var derivationStrategy = store.DerivationStrategy;
            var entity             = new InvoiceEntity
            {
                InvoiceTime        = DateTimeOffset.UtcNow,
                DerivationStrategy = derivationStrategy ?? throw new BitpayHttpException(400, "This store has not configured the derivation strategy")
            };
            var storeBlob       = store.GetStoreBlob(_Network);
            Uri notificationUri = Uri.IsWellFormedUriString(invoice.NotificationURL, UriKind.Absolute) ? new Uri(invoice.NotificationURL, UriKind.Absolute) : null;

            if (notificationUri == null || (notificationUri.Scheme != "http" && notificationUri.Scheme != "https")) //TODO: Filer non routable addresses ?
            {
                notificationUri = null;
            }
            EmailAddressAttribute emailValidator = new EmailAddressAttribute();

            entity.ExpirationTime       = entity.InvoiceTime.AddMinutes(expiryMinutes);
            entity.MonitoringExpiration = entity.ExpirationTime + TimeSpan.FromMinutes(storeBlob.MonitoringExpiration);
            entity.OrderId           = invoice.OrderId;
            entity.ServerUrl         = serverUrl;
            entity.FullNotifications = invoice.FullNotifications;
            entity.NotificationURL   = notificationUri?.AbsoluteUri;
            entity.BuyerInformation  = Map <Invoice, BuyerInformation>(invoice);
            //Another way of passing buyer info to support
            FillBuyerInfo(invoice.Buyer, entity.BuyerInformation);
            if (entity?.BuyerInformation?.BuyerEmail != null)
            {
                if (!EmailValidator.IsEmail(entity.BuyerInformation.BuyerEmail))
                {
                    throw new BitpayHttpException(400, "Invalid email");
                }
                entity.RefundMail = entity.BuyerInformation.BuyerEmail;
            }
            entity.ProductInformation = Map <Invoice, ProductInformation>(invoice);
            entity.RedirectURL        = invoice.RedirectURL ?? store.StoreWebsite;
            entity.Status             = "new";
            entity.SpeedPolicy        = ParseSpeedPolicy(invoice.TransactionSpeed, store.SpeedPolicy);

            var getFeeRate = _FeeProvider.GetFeeRateAsync();
            var getRate    = _RateProvider.GetRateAsync(invoice.Currency);
            var getAddress = _Wallet.ReserveAddressAsync(ParseDerivationStrategy(derivationStrategy));

            entity.TxFee          = storeBlob.NetworkFeeDisabled ? Money.Zero : (await getFeeRate).GetFee(100); // assume price for 100 bytes
            entity.Rate           = (double)await getRate;
            entity.PosData        = invoice.PosData;
            entity.DepositAddress = await getAddress;
            entity = await _InvoiceRepository.CreateInvoiceAsync(store.Id, entity);

            _Watcher.Watch(entity.Id);
            var resp = entity.EntityToDTO();

            return(new DataWrapper <InvoiceResponse>(resp)
            {
                Facade = "pos/invoice"
            });
        }
Пример #14
0
        public ActionResult ChangMemberInfo(int?id, string email, string name, string surname, string address, string phonenumber)
        {
            Boolean isNumber  = Regex.IsMatch(phonenumber, @"^\d+$");
            Member  checkmail = _MemberRepo.GetByExactlyEmail(email);
            Member  checkname = _MemberRepo.GetByNameAndSurname(name, surname);
            var     foo       = new EmailAddressAttribute();
            bool    bar       = foo.IsValid(email);

            if (String.IsNullOrEmpty(email))
            {
                return(Json(new { Result = "Fail, email is required" }, JsonRequestBehavior.AllowGet));
            }
            if (String.IsNullOrEmpty(name))
            {
                return(Json(new { Result = "Fail, name is required" }, JsonRequestBehavior.AllowGet));
            }
            if (String.IsNullOrEmpty(surname))
            {
                return(Json(new { Result = "Fail, surname is required" }, JsonRequestBehavior.AllowGet));
            }
            if (String.IsNullOrEmpty(address))
            {
                return(Json(new { Result = "Fail, address is required" }, JsonRequestBehavior.AllowGet));
            }
            if (String.IsNullOrEmpty(phonenumber))
            {
                return(Json(new { Result = "Fail, phone number is required" }, JsonRequestBehavior.AllowGet));
            }
            if (isNumber == false)
            {
                return(Json(new { Result = "Fail, phone number can only contain 0-9" }, JsonRequestBehavior.AllowGet));
            }
            if (phonenumber.Length != 10)
            {
                return(Json(new { Result = "Fail, phone number have to contain 10 numeric character" }, JsonRequestBehavior.AllowGet));
            }
            if (bar == false)
            {
                return(Json(new { Result = "Fail, email address is in invalid format, the valid format of email is [email protected]" }, JsonRequestBehavior.AllowGet));
            }
            if ((checkmail != null) && (checkmail.id != id.Value))
            {
                return(Json(new { Result = "Fail, the email is already exits in the system" }, JsonRequestBehavior.AllowGet));
            }
            if ((checkname != null) && (checkname.id != id.Value))
            {
                return(Json(new { Result = "Fail, member with name " + name + " and surname " + surname + "is alredy exits in the system" }, JsonRequestBehavior.AllowGet));
            }
            Member member = _MemberRepo.GetByID(id.Value);

            member.name        = name;
            member.surname     = surname;
            member.address     = address;
            member.email       = email;
            member.phonenumber = phonenumber;
            _MemberRepo.Update(member);
            return(Json(new { Result = "Edit success" }, JsonRequestBehavior.AllowGet));
        }
Пример #15
0
        public static void ValidateEmail(string emailString)
        {
            var emailAddressAttribute = new EmailAddressAttribute();

            if (emailAddressAttribute.IsValid(emailString) == false)
            {
                throw new UnvalidEmailExeption("You are entering unvalid email address");
            }
        }
Пример #16
0
        private void EmailValidCheck(string email)
        {
            var isValid = new EmailAddressAttribute().IsValid(email);

            if (!isValid)
            {
                throw new Exception($"Email {email} is not valid format");
            }
        }
Пример #17
0
        public static void CheckEmail(string email)
        {
            bool data = new EmailAddressAttribute().IsValid(email);

            if (!data)
            {
                throw new InvalidEmailException();
            }
        }
Пример #18
0
        public ActionResult Create(PollDTO dto)
        {
            if (ModelState.IsValid)
            {
                var emailHelper = new EmailAddressAttribute();
                if (emailHelper.IsValid(dto.NewPoll.Email))
                {
                    dto.NewPoll.CreatedDate       = DateTime.Now;
                    dto.NewPoll.TimeToParticipate = string.Join(", ", dto.SelectedParticipation);
                    dto.NewPoll.TypeOfHelp        = string.Join(", ", dto.SelectedHelps);
                    _repo.Add(dto.NewPoll);
                    TempData["Info"] = dto.NewPoll.Name();

                    try
                    {
                        _mailer.Thanks(dto.NewPoll);
                    }
                    catch {
                    }

                    return(RedirectToAction("SuccessMessage"));
                }
                else
                {
                    foreach (var helpType in Helpers.GetVolunteerType())
                    {
                        dto.MultipleChoiceHelps.Add(new MultipleChoiceDto {
                            Name = helpType, Selected = false
                        });
                    }

                    foreach (var time in Helpers.GetTimes())
                    {
                        dto.MultipleChoiceParticipation.Add(new MultipleChoiceDto {
                            Name = time, Selected = false
                        });
                    }
                    ViewBag.ErrorMessage = "Por favor colocar un email válido";
                    return(View(dto));
                }
            }
            foreach (var helpType in Helpers.GetVolunteerType())
            {
                dto.MultipleChoiceHelps.Add(new MultipleChoiceDto {
                    Name = helpType, Selected = false
                });
            }

            foreach (var time in Helpers.GetTimes())
            {
                dto.MultipleChoiceParticipation.Add(new MultipleChoiceDto {
                    Name = time, Selected = false
                });
            }
            ViewBag.ErrorMessage = "Revisar los campos requeridos";
            return(View(dto));
        }
Пример #19
0
        public static void AgainstInvalidEmailAddress(string value)
        {
            var validator = new EmailAddressAttribute();

            if (string.IsNullOrEmpty(value) || !validator.IsValid(value))
            {
                throw new GuardException($"{value} is not a valid email address");
            }
        }
Пример #20
0
        public static void ValidateEmailAddress(this UsersLogic usersLogic, string emailAddress)
        {
            var valid = new EmailAddressAttribute().IsValid(emailAddress);

            if (!valid)
            {
                throw new ArgumentException($"{emailAddress} was not a valid mailaddress");
            }
        }
Пример #21
0
        private void IsCorrectEmail()
        {
            bool isCorrectEmail = new EmailAddressAttribute().IsValid(user.Email);

            if (!isCorrectEmail)
            {
                result.AddError(ValidationKey.EmailIncorrect);
            }
        }
Пример #22
0
        public bool IsValid()
        {
            var addr = new EmailAddressAttribute();

            return
                (addr.IsValid(Email) &&
                 !string.IsNullOrWhiteSpace(this.UserName) &&
                 !string.IsNullOrWhiteSpace(this.PasswordHash));
        }
Пример #23
0
        public static void CheckEmailParameter(string email)
        {
            var isValid = new EmailAddressAttribute().IsValid(email);

            if (string.IsNullOrEmpty(email) || !isValid)
            {
                throw new ArgumentException("Please provide correct email address");
            }
        }
Пример #24
0
        public Email(string name) : base(name)
        {
            var emailAddressAttribute = new EmailAddressAttribute();

            if (!emailAddressAttribute.IsValid(name))
            {
                throw new ArgumentException(emailAddressAttribute.ErrorMessage);
            }
        }
Пример #25
0
        public ActionResult RecoverPassword(RecoverPasswordModel model)
        {
            var url = "";

            try
            {
                var email = new EmailAddressAttribute();
                if (!email.IsValid(model.Email))
                {
                    ModelState.AddModelError("", "Please enter a valid email!");
                    return(View(model));
                }

                Account account = _dc.Accounts.FirstOrDefault(a => a.Email == model.Email);

                if (account != null)
                {
                    account.ResetPassword    = Convert.ToBase64String(Guid.NewGuid().ToByteArray()).Substring(0, 22).Replace("/", "_").Replace("+", "-");
                    _dc.Entry(account).State = EntityState.Modified;
                    _dc.SaveChanges();
                    var currentURL = Request.Url.Scheme + Uri.SchemeDelimiter + Request.Url.Host;
                    url += currentURL + "/Account/ResetPassword/" + account.ResetPassword;
                    string body = "<!DOCTYPE html> <html> <head> <title>Reset Password</title> <style> body{ font-family: 'Source Sans Pro', sans-serif; color: #7f8186; } .btn{ display: inline-block; padding: 6px 12px; margin-bottom: 0; font-size: 14px; font-weight: normal; line-height: 1.42857143; text-align: center; white-space: nowrap; vertical-align: middle; -ms-touch-action: manipulation; touch-action: manipulation; cursor: pointer; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; background-image: none; border: 1px solid transparent; border-radius: 50px; background: #D54E40;\r\n    background: -moz-linear-gradient(left,  #D54E40 0%, #C41F4F 100%);\r\n    background: -webkit-linear-gradient(left,  #D54E40 0%,#C41F4F 100%); background: linear-gradient(to right,  #D54E40 0%,#C41F4F 100%);filter: progid:DXImageTransform.Microsoft.gradient( startColorstr=\'#D54E40\', endColorstr=\'#C41F4F\',GradientType=1 );} .text-center{ text-align: center; } .img-responsive { margin: 0 auto; } .btn{ width: 100%; font-weight: bold; font-size: 20px; height: 50px; background-color: #D54D3F; border-radius: 0; box-shadow: none; color: #fff; } .btn:hover, .btn:focus{ background-color: #D54D3F; color: #fff; } a{ color: #fff; } a:hover, a:focus{ text-decoration: none; color: #fff; } </style> </head> <body> <div class='container'> <div class='text-center'> </br> </br> <img src='http://i.imgur.com/t7DZoQs.png' class='img-responsive' width='200' height='200'><br> <h2>Hi " + account.FirstName + " " + account.LastName + "!</h2><br> <h4>We've recived a request to reset your password. If you didn't make the request,<br> just ignore this email. Otherwise, you can reset you password using this link:</h4><br> <a href=" + url + "><button class='btn btn-default'>Reset password</button></a> <h4>Thanks,</h4> <h4>IT Friends Team</h4> </div> </div> </body> </html>";
                    SendSimpleMessage(account.Email, body);


                    //MailMessage mail = new MailMessage();
                    //mail.To.Add(model.Email);
                    //mail.From = new MailAddress("*****@*****.**", "IT Friends", System.Text.Encoding.UTF8);
                    //mail.Subject = "IT Friends - Reset Password";
                    //mail.SubjectEncoding = System.Text.Encoding.UTF8;
                    //mail.Body = "<!DOCTYPE html> <html> <head> <title>Reset Password</title> <style> body{ font-family: 'Source Sans Pro', sans-serif; color: #7f8186; } .btn{ display: inline-block; padding: 6px 12px; margin-bottom: 0; font-size: 14px; font-weight: normal; line-height: 1.42857143; text-align: center; white-space: nowrap; vertical-align: middle; -ms-touch-action: manipulation; touch-action: manipulation; cursor: pointer; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; background-image: none; border: 1px solid transparent; border-radius: 50px; background: #D54E40;\r\n    background: -moz-linear-gradient(left,  #D54E40 0%, #C41F4F 100%);\r\n    background: -webkit-linear-gradient(left,  #D54E40 0%,#C41F4F 100%); background: linear-gradient(to right,  #D54E40 0%,#C41F4F 100%);filter: progid:DXImageTransform.Microsoft.gradient( startColorstr=\'#D54E40\', endColorstr=\'#C41F4F\',GradientType=1 );} .text-center{ text-align: center; } .img-responsive { margin: 0 auto; } .btn{ width: 100%; font-weight: bold; font-size: 20px; height: 50px; background-color: #D54D3F; border-radius: 0; box-shadow: none; color: #fff; } .btn:hover, .btn:focus{ background-color: #D54D3F; color: #fff; } a{ color: #fff; } a:hover, a:focus{ text-decoration: none; color: #fff; } </style> </head> <body> <div class='container'> <div class='text-center'> </br> </br> <img src='http://i.imgur.com/t7DZoQs.png' class='img-responsive' width='200' height='200'><br> <h2>Hi " + account.FirstName + " " + account.LastName + "!</h2><br> <h4>We've recived a request to reset your password. If you didn't make the request,<br> just ignore this email. Otherwise, you can reset you password using this link:</h4><br> <a href=" + url + "><button class='btn btn-default'>Reset password</button></a> <h4>Thanks,</h4> <h4>IT Friends Team</h4> </div> </div> </body> </html>";
                    //mail.BodyEncoding = System.Text.Encoding.UTF8;
                    //mail.IsBodyHtml = true;
                    //mail.Priority = MailPriority.High;
                    //SmtpClient client = new SmtpClient();
                    //client.Credentials = new System.Net.NetworkCredential("*****@*****.**", "konanpass123-");
                    //client.Port = 587;
                    //client.Host = "smtp.gmail.com";
                    //client.EnableSsl = true;
                    //client.Send(mail);



                    return(RedirectToAction("Index", "Home"));
                }

                ModelState.AddModelError("", "This email is not associated with a user.");
                return(View(model));
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", "This service is blocked by the host.\nGo to: " + url);
                return(View(model));
            }
        }
Пример #26
0
        public ActionResult SignIn(SignInViewModel model)
        {
            if (ModelState.IsValid)
            {
                if (string.IsNullOrEmpty(model.Email))
                {
                    ModelState.AddModelError("", "Please enter your email!");
                    return(View(model));
                }
                else
                {
                    var email = new EmailAddressAttribute();
                    if (!email.IsValid(model.Email))
                    {
                        ModelState.AddModelError("", "Please enter a valid email!");
                        return(View(model));
                    }
                }
                if (string.IsNullOrEmpty(model.Password))
                {
                    ModelState.AddModelError("", "Please enter your password!");
                    return(View(model));
                }
                if (Account.ValidAccount(model))
                {
                    Session["Email"] = model.Email;
                    Account a = _dc.Accounts.Where(e => e.Email == model.Email).FirstOrDefault();
                    if (a != null)
                    {
                        Session["Id"]        = a.Id;
                        Session["Password"]  = a.Password;
                        Session["FullName"]  = a.FirstName + " " + a.LastName;
                        Session["FirstName"] = a.FirstName;
                        Session["LastName"]  = a.LastName;

                        var cookie = new HttpCookie("AuthID");
                        cookie.Value = a.Id;
                        Response.Cookies.Add(cookie);

                        FormsAuthentication.SetAuthCookie(model.Email, false);

                        return(RedirectToAction("Index", "Home"));
                    }
                    else
                    {
                        ModelState.AddModelError("", "Session error.");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Incorrect email and/or password.");
                }
            }

            return(View(model));
        }
Пример #27
0
        protected void submitEventMethod(object sender, EventArgs e)
        {
            using (SqlConnection sqlCon = new SqlConnection(connectionString))
            {
                sqlCon.Open();
                var  email = new EmailAddressAttribute();
                bool isEmail;
                isEmail = email.IsValid(usernameText.Text.Trim());

                if (isEmail == true)
                {
                    string     query  = "SELECT COUNT(1) FROM CUSTOMER WHERE email=@email AND password=@password";
                    SqlCommand sqlCmd = new SqlCommand(query, sqlCon);
                    sqlCmd.Parameters.AddWithValue("@email", usernameText.Text.Trim());
                    sqlCmd.Parameters.AddWithValue("@password", passwordText.Text.Trim());
                    int count = Convert.ToInt32(sqlCmd.ExecuteScalar());
                    if (count == 1)
                    {
                        Session["username"] = usernameText.Text.Trim();
                        Response.Redirect("Dashboard.aspx");
                    }
                    else
                    {
                        statusMessage.Text = "invalid credentials";
                    }
                }
                else
                {
                    //statusMessage.Text = "not a valid email";
                    int employeecheck;
                    int.TryParse(usernameText.Text, out employeecheck);
                    if (employeecheck == 0)
                    {
                        statusMessage.Text = "invalid username";
                    }
                    else
                    {
                        statusMessage.Text = "valid id";
                        string     query  = "SELECT COUNT(1) FROM EMPLOYEES WHERE Employee_ID=@employeeID AND password=@password";
                        SqlCommand sqlCmd = new SqlCommand(query, sqlCon);
                        sqlCmd.Parameters.AddWithValue("@employeeID", usernameText.Text.Trim());
                        sqlCmd.Parameters.AddWithValue("@password", passwordText.Text.Trim());
                        int count = Convert.ToInt32(sqlCmd.ExecuteScalar());
                        if (count == 1)
                        {
                            Session["username"] = usernameText.Text.Trim();
                            Response.Redirect("EmployeeDashboard.aspx");
                        }
                        else
                        {
                            statusMessage.Text = "invalid credentials";
                        }
                    }
                }
            }
        }
Пример #28
0
        public static bool IsEmail(this string text)
        {
            var email = new EmailAddressAttribute();

            if (email.IsValid(text))
            {
                return(true);
            }
            return(false);
        }
Пример #29
0
        private static bool ValidateEmailAddress(string formFieldName, string labelText, string formFieldNameValue2, string stringValue1, string stringValue2, ModelStateDictionary modelStateDictionary)
        {
            bool isValid = new EmailAddressAttribute().IsValid(stringValue1);

            if (!isValid)
            {
                modelStateDictionary.AddModelError(formFieldName, labelText + " value '" + stringValue1 + "' is invalid. You must enter a valid Email Address.");
            }
            return(isValid);
        }
Пример #30
0
        // Validate the format of an email.
        public bool validateEmailFormat(string email)
        {
            if (email == null)
            {
                return(false);
            }
            var emailValidator = new EmailAddressAttribute();

            return(emailValidator.IsValid(email));
        }
        public void IsValidTests() {
            // Arrange
            var attribute = new EmailAddressAttribute();

            // Act & Assert
            Assert.IsTrue(attribute.IsValid(null)); // Optional values are always valid
            Assert.IsTrue(attribute.IsValid("*****@*****.**"));
            Assert.IsTrue(attribute.IsValid("*****@*****.**"));
            Assert.IsFalse(attribute.IsValid("joe"));
            Assert.IsFalse(attribute.IsValid("joe@"));
            Assert.IsFalse(attribute.IsValid("joe@contoso"));
        }
        public void ClientRule() {
            // Arrange
            var attribute = new EmailAddressAttribute();
            var provider = new Mock<ModelMetadataProvider>();
            var metadata = new ModelMetadata(provider.Object, null, null, typeof(string), "PropertyName");

            // Act
            ModelClientValidationRule clientRule = attribute.GetClientValidationRules(metadata, null).Single();

            // Assert
            Assert.AreEqual("email", clientRule.ValidationType);
            Assert.AreEqual("The PropertyName field is not a valid e-mail address.", clientRule.ErrorMessage);
            Assert.AreEqual(0, clientRule.ValidationParameters.Count);
        }
 public static void DataType_CustomDataType_ReturnExpected()
 {
     var attribute = new EmailAddressAttribute();
     Assert.Equal(DataType.EmailAddress, attribute.DataType);
     Assert.Null(attribute.CustomDataType);
 }