protected override void OnValidate()
 {
     if (string.IsNullOrWhiteSpace(FirstName))
     {
         SetError("FirstName", "First name is required.");
     }
     if (string.IsNullOrWhiteSpace(LastName))
     {
         SetError("LastName", "Last name is required.");
     }
     if (string.IsNullOrWhiteSpace(EmailAddress))
     {
         SetError("EmailAddress", "Email address is required.");
     }
     else if (!EmailRegex.IsMatch(EmailAddress))
     {
         SetError("EmailAddress", "Invalid email address.");
     }
     if (string.IsNullOrWhiteSpace(ApplicationName))
     {
         SetError("ApplicationName", "Application Name is required.");
     }
     if (string.IsNullOrWhiteSpace(ApplicationUrl))
     {
         SetError("ApplicationUrl", "Application Url is required.");
     }
     if (string.IsNullOrWhiteSpace(AccountId))
     {
         SetError("AccountId", "Account Id is required.");
     }
 }
Exemplo n.º 2
0
            static ValidationRule()
            {
                //Interal rule that will always return true, for default rule
                AlwaysTrue = new ValidationRule(string.Empty, s => true);

                Integer = new ValidationRule("Number", delegate(string s)
                {
                    int result;
                    return(int.TryParse(s, out result));
                });

                Double = new ValidationRule("Number", delegate(string s)
                {
                    double result;
                    return(double.TryParse(s, out result));
                });

                Email = new ValidationRule("Email", s => EmailRegex.IsMatch(s));

                AlphaNumerical = new ValidationRule("Alphanumeric string", s => AlphaNumericRegex.IsMatch(s));

                IP = new ValidationRule("IP Address", delegate(string s)
                {
                    IPAddress ip;
                    var valid = !string.IsNullOrEmpty(s) && IPAddress.TryParse(s, out ip);
                    return(valid);
                });
            }
Exemplo n.º 3
0
        public static bool IsEmail(string s)
        {
            if (string.IsNullOrEmpty(s))
            {
                return(false);
            }
            var match = EmailRegex.Match(s);

            return(match.Success && match.Value.Length == s.Length);
        }
Exemplo n.º 4
0
        public static ValidationField[] ValidateUser(
            string usernameOrEmail,
            string password)
        {
            var requiredFileds = (EmailRegex.Match(usernameOrEmail).Success)
                                ? UserFieldName.Email | UserFieldName.Password
                                : UserFieldName.UserName | UserFieldName.Password;

            return(ValidateMemberRegistration(
                       usernameOrEmail, password, null, null, null, null, null, null, null, requiredFileds));
        }
Exemplo n.º 5
0
 /// <summary>
 /// Validates that the specified name meets minimum requirements.
 /// </summary>
 /// <param name="name">The desired name/alias.</param>
 /// <param name="result">Any error messages about the desired name.</param>
 /// <returns></returns>
 public virtual bool ValidateName(string name, ExecutionResults result)
 {
     if (!NameRegex.IsMatch(name) && !EmailRegex.IsMatch(name))
     {
         //if this message is changed, do the same anywhere else it is used
         result.AppendError(
             "The name contains invalid characters.  The name must be an email address OR contain only letters, numbers, dashes, underscores, and spaces, are allowed.");
         return(false);
     }
     return(true);
 }
Exemplo n.º 6
0
        /// <summary>
        /// Returns a value that identifies whether this email is valid
        /// </summary>
        /// <returns><c>True</c> if the provided value is valid, otherwise <c>false</c>.</returns>
        /// <param name="value">Value.</param>
        public bool Validate(T value)
        {
            if (value == null)
            {
                return false;
            }

            var val = value as string;

            var match = EmailRegex.Match(val);

            return match.Success;
        }
        private static bool CheckValidEmailList(InputField field)
        {
            var incorrect = field.transform.Find("Incorrect");

            if (string.IsNullOrEmpty(field.text))
            {
                incorrect.gameObject.SetActive(false);
                return(true);
            }
            else
            {
                bool correct = EmailRegex.IsMatch(field.text);
                incorrect.gameObject.SetActive(!correct);
                return(correct);
            }
        }
Exemplo n.º 8
0
 public RegexType regexCatergory(string s)
 {
     if (EmailRegex.IsMatch(s))
     {
         return(RegexType.EMAIL);
     }
     if (HyperLinkRegex.IsMatch(s))
     {
         return(RegexType.URL);
     }
     if (PhoneNumberRegex.IsMatch(s))
     {
         return(RegexType.PHONE_NO);
     }
     return(RegexType.EMOTICONS);
 }
Exemplo n.º 9
0
 /// <summary>
 /// Validate the email address
 /// </summary>
 /// <param name="emailAddr">Email address to validate</param>
 /// <param name="checkForFakes">Check fake email addresses, when true will test and fail fakes</param>
 /// <param name="checkForProd">Check Production, when true will and not Production will only pass Experient emails</param>
 public static bool IsEmailValid(string emailAddr, bool checkForFakes = false, bool checkForProd = false)
 {
     if (emailAddr.IsEmpty())
     {
         return(false);
     }
     if (checkForFakes && CRMUtility.IsEmailFake(emailAddr))
     {
         return(false);
     }
     if (checkForProd && !CRMUtility.IsEmailWhiteListed(emailAddr))
     {
         return(false);
     }
     return(EmailRegex.IsMatch(emailAddr));
 }
        private void ExtractEmailAndTelephone(List <Festival_Unformatted> festivalsWithSameTitle, Festival festival)
        {
            var hotlineKontaktString = festivalsWithSameTitle
                                       .First(f => f.TableColOne == "Info-Hotline:" || f.TableColOne == "Kontakt")
                                       .TableColTwo;

            if (!string.IsNullOrWhiteSpace(hotlineKontaktString))
            {
                //Extract Email
                festival.Email = EmailRegex.MatchEmail(hotlineKontaktString);

                //Extract Phone Number
                hotlineKontaktString = RemoveCharacters.RemoveWhitespaces(hotlineKontaktString);

                hotlineKontaktString = RemoveCharacters.RemoveSpecialCharacters(hotlineKontaktString, new [] { '+' });

                festival.PhoneNumber = TelephoneRegex.MatchTelephone(hotlineKontaktString);
            }
        }
Exemplo n.º 11
0
        public object Post(RegisteredDomainCheck request)
        {
            if (string.IsNullOrWhiteSpace(request?.Username))
            {
                throw new HttpError(HttpStatusCode.BadRequest);
            }

            if (!EmailRegex.IsMatch(request.Username))
            {
                throw new HttpError(HttpStatusCode.BadRequest);
            }

            var idx          = request.Username.IndexOf("@", StringComparison.Ordinal);
            var isRegistered = _registry.ApplicationIsRegistered(request.Username.Substring(idx + 1));

            return(new RegisteredDomainCheckResponse
            {
                IsRegistered = isRegistered
            });
        }
Exemplo n.º 12
0
 public static bool ValidateEmail(string strToMatch)
 {
     return(EmailRegex.IsMatch(strToMatch));
 }
Exemplo n.º 13
0
 private bool ValidateEmail(string email)
 {
     return(EmailRegex.IsMatch(email));
 }
Exemplo n.º 14
0
 public static bool IsValidEmail(string email)
 {
     return(!string.IsNullOrEmpty(email) && EmailRegex.IsMatch(email));
 }
Exemplo n.º 15
0
        /// <summary>
        /// 指定したResSetを
        /// 設定されているスキンを使用して文字列形式に変換
        /// </summary>
        /// <param name="resSet"></param>
        /// <returns></returns>
        public override string Convert(ResSet resSet)
        {
            if (!resSet.Visible)
            {
                return(String.Empty);
            }

            if (resSet.DateString == "透明あぼーん")
            {
                return(String.Empty);
            }

            /*
             * if (resSet.IsABone) {
             *      resSet = ResSet.ABone(resSet, ABoneType.NG, "");
             *      resSet.Email = String.Empty;
             * }*/

            // 使用するスキン
            string skinhtml = resSet.IsNew ? newResSkin : resSkin;
            string dateonly, body;

            // 本分からtagを取り除く
            body = resSet.Body;
            body = Regex.Replace(body, "<a[^>]+>(?<uri>[^<]*)</a>", "${uri}", RegexOptions.IgnoreCase);
            body = Regex.Replace(body, "<(?!br|hr)[^>]+>", "");

            buffer.Append(body);
            buffer.Replace("<br>", "\r\n");
            buffer.Replace("<hr>", "\r\n ————————————————————\r\n");
            buffer.Replace("&gt;", ">");
            buffer.Replace("&lt;", "<");
            body = buffer.ToString();
            buffer.Remove(0, buffer.Length);

            #region 日付とIDを作成
            dateonly = resSet.DateString;
            Match m = Regex.Match(resSet.DateString, "( ID:)|(\\[)");

            if (m.Success)
            {
                dateonly = resSet.DateString.Substring(0, m.Index);
            }
            #endregion

#if REGEX_REPLACE
            skinhtml = PlainNumberRegex.Replace(skinhtml, resSet.Index.ToString());
            skinhtml = IDRegex.Replace(skinhtml, resSet.ID);
            skinhtml = NameRegex.Replace(skinhtml, resSet.Name);
            skinhtml = EmailRegex.Replace(skinhtml, resSet.Email);
            skinhtml = DateRegex.Replace(skinhtml, resSet.DateString);
            skinhtml = DateOnlyRegex.Replace(skinhtml, dateonly);
            skinhtml = BodyRegex.Replace(skinhtml, body);
#else
            buffer.Append(skinhtml);
            buffer.Replace("<PLAINNUMBER/>", resSet.Index.ToString());
            buffer.Replace("<ID/>", resSet.ID);
            buffer.Replace("<NAME/>", HtmlTextUtility.RemoveTag(resSet.Name));
            buffer.Replace("<MAIL/>", resSet.Email);
            buffer.Replace("<DATE/>", resSet.DateString);
            buffer.Replace("<DATEONLY/>", dateonly);
            buffer.Replace("<MESSAGE/>", body);
            skinhtml = buffer.ToString();
            buffer.Remove(0, buffer.Length);
#endif

            return(skinhtml);
        }
Exemplo n.º 16
0
        /// <summary>
        /// Test user registration info.
        /// </summary>
        /// <param name="value">Validation parameters.</param>
        /// <returns>Results array for each parameter.</returns>
        public static ValidationField[] ValidateMemberRegistration(
            string firstName,
            string lastName,
            string email,
            string username,
            string password,
            string birthday,
            string gender,
            bool?terms,
            bool?news
            )
        {
            string f = string.Empty; // First Name
            string l = string.Empty; // Last Name
            string e = string.Empty; // Email
            string u = string.Empty; // Username
            string p = string.Empty; // Password
            string b = string.Empty; // Birthday
            string g = string.Empty; // Gender
            string t = string.Empty; // Terms
            string n = string.Empty; // Promotions

            // Required fields.
            if (string.IsNullOrEmpty(firstName))
            {
                f = "<b>First Name</b> is required.";
            }
            if (string.IsNullOrEmpty(lastName))
            {
                l = "<b>Last Name</b> is required.";
            }
            if (string.IsNullOrEmpty(email))
            {
                e = "<b>Your Email</b> is required.";
            }
            if (string.IsNullOrEmpty(username))
            {
                u = "<b>Username</b> is required.";
            }
            if (string.IsNullOrEmpty(password))
            {
                p = "<b>Password</b> is required.";
            }
            // First Name
            if (string.IsNullOrEmpty(f) && firstName.Length > 0)
            {
                //if (Engine.DataBase.Data.Resource.IsMatch(firstName, AppContext.Current.Resources.DisallowedNames))
                //{
                //    f = "This first name is not allowed.";
                //}
            }
            // Last Name
            if (string.IsNullOrEmpty(l) && lastName.Length > 0)
            {
                //if (Engine.DataBase.Data.Resource.IsMatch(lastName, AppContext.Current.Resources.DisallowedNames))
                //{
                //    l = "This last name is not allowed.";
                //}
            }
            // Username.
            if (string.IsNullOrEmpty(u) && Regex.Match(username, "[a-zA-Z0-9_]{3,20}").Value != username)
            {
                u = "<b>Username</b> must be between 3-20 characters<br />and contain only letters or numbers.";
            }
            if (string.IsNullOrEmpty(u) && User.GetUser(username) != null)
            {
                u = "<b>Username</b> is already taken.";
            }
            //if (string.IsNullOrEmpty(u) && Engine.Forums.Transforms.IsMatch(
            //        username, Engine.Forums.Transforms.DisallowedNames))
            //{
            //    u = "<b>Username</b> is not available.";
            //}
            // Email
            if (string.IsNullOrEmpty(e) && !EmailRegex.Match(email).Success)
            {
                e = "<b>Your Email</b> address is not valid.";
            }

            if (string.IsNullOrEmpty(e) && User.GetUserByEmail(email) != null)
            {
                e = "<b>Your Email</b> address is used already.";
            }
            // Password
            if (string.IsNullOrEmpty(p) && password.Length < 6)
            {
                p = "<b>Password</b> must be at least 6 characters.";
            }
            // Pasword: Is same as...
            //if (string.IsNullOrEmpty(p) && password == firstName)
            //{
            //    p = "<b>Password</b> can't be same as <b>First Name</b>.";
            //}
            //if (string.IsNullOrEmpty(p) && password == lastName)
            //{
            //    p = "<b>Password</b> can't be same as <b>Last Name</b>.";
            //}
            //if (string.IsNullOrEmpty(p) && password == username)
            //{
            //    p = "<b>Password</b> can't be same as <b>Username</b>.";
            //}
            if (string.IsNullOrEmpty(p) && password == email)
            {
                p = "<b>Password</b> can't be same as <b>Your Email</b>.";
            }
            // Password: Contains...
            //if (string.IsNullOrEmpty(p) && password.Contains(firstName))
            //{
            //    p = "<b>Password</b> can't contain <b>First Name</b> inside.";
            //}
            //if (string.IsNullOrEmpty(p) && password.Contains(lastName))
            //{
            //    p = "<b>Password</b> can't contain <b>Last Name</b> inside.";
            //}
            //if (string.IsNullOrEmpty(p) && password.Contains(username))
            //{
            //    p = "<b>Password</b> can't contain <b>Username</b> inside.";
            //}
            // Birthday
            DateTime bd;

            if (string.IsNullOrEmpty(birthday) || !DateTime.TryParse(birthday, out bd))
            {
                b = "Indicate your <b>Birthday</b> to register.";
            }
            // Gender
            if (gender != "M" && gender != "F")
            {
                g = "Indicate your <b>Gender</b> to register.";
            }
            // Terms
            if (terms.HasValue && terms.Value == false)
            {
                t = "You must accept <b>Terms of use</b>.";
            }
            List <ValidationField> results = new List <ValidationField>();

            results.Add(new ValidationField()
            {
                Name = UserFieldName.FirstName, Value = firstName, Message = f
            });
            results.Add(new ValidationField()
            {
                Name = UserFieldName.LastName, Value = lastName, Message = l
            });
            results.Add(new ValidationField()
            {
                Name = UserFieldName.Email, Value = email, Message = e
            });
            results.Add(new ValidationField()
            {
                Name = UserFieldName.UserName, Value = username, Message = u
            });
            results.Add(new ValidationField()
            {
                Name = UserFieldName.Password, Value = password, Message = p
            });
            results.Add(new ValidationField()
            {
                Name = UserFieldName.Birthday, Value = birthday, Message = b
            });
            results.Add(new ValidationField()
            {
                Name = UserFieldName.Gender, Value = gender, Message = g
            });
            results.Add(new ValidationField()
            {
                Name = UserFieldName.Terms, Value = terms, Message = t
            });
            results.Add(new ValidationField()
            {
                Name = UserFieldName.News, Value = news, Message = n
            });
            return(results.ToArray());
        }
Exemplo n.º 17
0
        private static void Main(string[] args)
        {
            var options = new Options();

            if (Parser.Default.ParseArguments(args, options))
            {
                log.Info(options.InputFile);
                log.Info(options.OutputFile);
                if (!string.IsNullOrEmpty(options.CompareToInputFile))
                {
                    log.Info("Compare-to list: {0}", options.CompareToInputFile);
                    log.Info("Auto correct username based on compare-to list: {0}", options.AutoCorrect ? "Yes" : "No");
                }
                if (!string.IsNullOrEmpty(options.ReplaceToInputFile))
                {
                    log.Info("Replace-to list: {0}", options.ReplaceToInputFile);
                    log.Info("Auto correct values based on replace-to list: {0}", options.AutoCorrect ? "Yes" : "No");
                }
                if (options.EmailAsAccountName)
                {
                    log.Info("Auto replace AccountName with EmailAddress: {0}", options.EmailAsAccountName ? "Yes" : "No");
                }

                var users     = new List <User>();
                var compareTo = new List <Tuple <string, string, string> >();
                var replaceTo = new List <Tuple <string, string> >();

                #region load users
                try
                {
                    log.Debug("start loading {0}.", options.InputFile);
                    var inputWorkbook = new XSSFWorkbook(new MemoryStream(File.ReadAllBytes(options.InputFile)));

                    for (int i = 0; i < inputWorkbook.NumberOfSheets; i++)
                    {
                        var sheet = inputWorkbook.GetSheetAt(i);
                        for (int j = sheet.FirstRowNum + 1; j <= sheet.LastRowNum; j++)
                        {
                            var row = sheet.GetRow(j);
                            if (row == null)
                            {
                                continue;
                            }
                            var user = new User();
                            for (int k = row.FirstCellNum; k <= row.LastCellNum; k++)
                            {
                                var cell  = row.GetCell(k);
                                var value = cell?.ToString().Trim();
                                value = !string.Equals("NULL", value, StringComparison.OrdinalIgnoreCase) ? value : null;
                                switch (k)
                                {
                                case 0:
                                    user.FirstName = value;
                                    break;

                                case 1:
                                    user.LastName = value;
                                    break;

                                case 2:
                                    user.BusinessTitle = !string.IsNullOrEmpty(value) ? value : "Other";
                                    break;

                                case 3:
                                    user.OrganizationUnit = value;
                                    break;

                                case 4:
                                    user.PhoneType = !string.IsNullOrEmpty(value) ? value : "Other";
                                    break;

                                case 5:
                                    user.PhoneNumber = !string.IsNullOrEmpty(value) ? value : "000-000-0000";
                                    break;

                                case 6:
                                    user.UserRoles = value;
                                    break;

                                case 7:
                                    user.AccountName = value;
                                    break;

                                case 8:
                                    if (value != null)
                                    {
                                        if (!EmailRegex.IsMatch(value))
                                        {
                                            log.Warn("{0} has invalid format, skipped this row. Current Sheet/Row [{1}]/[{2}]", value, sheet.SheetName, row.RowNum);
                                            continue;
                                        }
                                        if (options.AutoCorrect)
                                        {
                                            if (value.Contains(","))
                                            {
                                                log.Info("{0} auto corrected. Current Sheet/Row [{1}]/[{2}]", value, sheet.SheetName, row.RowNum);
                                                value = value?.Replace(",", ".");
                                            }
                                        }
                                    }
                                    user.EmailAddress = value;
                                    break;
                                }
                            }
                            user.AccountName = user.AccountName ?? user.EmailAddress;//set email address as default account name
                            if (!string.IsNullOrEmpty(user.EmailAddress))
                            {
                                var loadedUser = users.FirstOrDefault(x => x.EmailAddress == user.EmailAddress);
                                if (loadedUser != null)
                                {
                                    log.Info("{0} already loaded. Current Sheet/Row [{1}]/[{2}]", user.EmailAddress, sheet.SheetName, row.RowNum);
                                }
                                else
                                {
                                    users.Add(user);
                                }
                            }
                        }
                    }
                }
                catch (Exception exception)
                {
                    log.Error(exception, "Cannot load users from input file {0}", options.InputFile);
                }
                log.Info("{0} users loaded.", users.Count);
                #endregion

                if (!string.IsNullOrEmpty(options.CompareToInputFile))
                {
                    #region load compare-to users
                    try
                    {
                        log.Debug("start loading {0}.", options.CompareToInputFile);
                        var inputWorkbook = new XSSFWorkbook(new MemoryStream(File.ReadAllBytes(options.CompareToInputFile)));

                        //original spreadsheet has 1 sheet
                        var sheet = inputWorkbook.GetSheetAt(0);

                        for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
                        {
                            var row = sheet.GetRow(i);
                            if (row == null)
                            {
                                continue;
                            }
                            var key      = row.GetCell(0)?.ToString()?.Trim();
                            var username = row.GetCell(1)?.ToString()?.Trim();
                            var email    = row.GetCell(2)?.ToString()?.Trim();
                            if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(email))
                            {
                                compareTo.Add(new Tuple <string, string, string>(key, username, email));
                            }
                        }
                    }
                    catch (Exception exception)
                    {
                        log.Error(exception, "Cannot load users from compare to input file {0}", options.CompareToInputFile);
                    }
                    log.Info("{0} compare-to users loaded.", compareTo.Count);
                    #endregion

                    if (options.AutoCorrect)
                    {
                        #region correct username by following compre-to users
                        foreach (var user in users)
                        {
                            var existUser = compareTo.FirstOrDefault(x => string.Equals(x.Item3, user.EmailAddress, StringComparison.OrdinalIgnoreCase));
                            if (existUser != null && !string.Equals(existUser.Item2, user.AccountName))
                            {
                                log.Info("Account name replaced with {0} from {1} for {2}", existUser.Item2, user.AccountName, user.EmailAddress);
                                user.AccountName = existUser.Item2;
                            }
                        }
                        #endregion
                    }

                    var usersNotExist = users.Where(x => compareTo.All(y => !string.Equals(y.Item3, x.EmailAddress, StringComparison.OrdinalIgnoreCase))).ToList();
                    log.Info("Users cannot be found in our database: {0}", string.Join(",", usersNotExist.Select(x => x.EmailAddress)));

                    var usersNotFromClient =
                        compareTo.Where(
                            x =>
                            users.All(y => !string.Equals(x.Item3, y.EmailAddress, StringComparison.OrdinalIgnoreCase))).ToList();
                    log.Info("Users cannot be found from input file (keys): {0}", string.Join(",", usersNotFromClient.Select(x => x.Item1)));
                    log.Info("Users cannot be found from input file: {0}", string.Join(",", usersNotFromClient.Select(x => x.Item3)));
                }

                if (!string.IsNullOrEmpty(options.ReplaceToInputFile))
                {
                    #region load replace-to values
                    try
                    {
                        log.Debug("start loading {0}.", options.ReplaceToInputFile);
                        var inputWorkbook = new XSSFWorkbook(new MemoryStream(File.ReadAllBytes(options.ReplaceToInputFile)));

                        //original spreadsheet has 1 sheet
                        var sheet = inputWorkbook.GetSheetAt(0);

                        for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
                        {
                            var row = sheet.GetRow(i);
                            if (row == null)
                            {
                                continue;
                            }
                            var originalValue = row.GetCell(0)?.ToString()?.Trim();
                            var newValue      = row.GetCell(1)?.ToString()?.Trim();
                            if (!string.IsNullOrEmpty(originalValue) && !string.IsNullOrEmpty(newValue))
                            {
                                replaceTo.Add(new Tuple <string, string>(originalValue, newValue));
                            }
                        }
                    }
                    catch (Exception exception)
                    {
                        log.Error(exception, "Cannot load users from replace to input file {0}", options.ReplaceToInputFile);
                    }
                    #endregion

                    if (options.AutoCorrect)
                    {
                        foreach (var user in users)
                        {
                            #region correct OrganizationUnit by following replace-to values
                            var organizationUnit = replaceTo.FirstOrDefault(x => string.Equals(x.Item1, user.OrganizationUnit, StringComparison.OrdinalIgnoreCase));
                            if (organizationUnit != null)
                            {
                                log.Info("OrganizationUnit replaced with {0} from {1} for {2}", organizationUnit.Item2, user.OrganizationUnit, user.EmailAddress);
                                user.OrganizationUnit = organizationUnit.Item2;
                            }
                            #endregion

                            #region correct PhoneType by following replace-to values
                            var phoneType = replaceTo.FirstOrDefault(x => string.Equals(x.Item1, user.PhoneType, StringComparison.OrdinalIgnoreCase));
                            if (phoneType != null)
                            {
                                log.Info("PhoneType replaced with {0} from {1} for {2}", phoneType.Item2, user.PhoneType, user.EmailAddress);
                                user.PhoneType = phoneType.Item2;
                            }
                            #endregion

                            #region correct UserRoles by following replace-to values
                            var userRoles = replaceTo.FirstOrDefault(x => string.Equals(x.Item1, user.UserRoles, StringComparison.OrdinalIgnoreCase));
                            if (userRoles != null)
                            {
                                log.Info("UserRoles replaced with {0} from {1} for {2}", userRoles.Item2, user.UserRoles, user.EmailAddress);
                                user.UserRoles = userRoles.Item2;
                            }
                            #endregion
                        }
                    }
                }

                if (options.EmailAsAccountName)
                {
                    #region Repalce AccountName with EmailAddress
                    foreach (var user in users)
                    {
                        log.Info("Account name replaced with email address for {0}", user.EmailAddress);
                        user.AccountName = user.EmailAddress;
                    }
                    #endregion
                }

                #region write users into files
                if (users.Any())
                {
                    try
                    {
                        WriteWorkbook(users, options.OutputFile);
                        log.Info("New file generated: {0}", options.OutputFile);
                    }
                    catch (Exception exception)
                    {
                        log.Error(exception, "Cannot write users to PA output file {0}", options.OutputFile);
                    }
                }
                #endregion
            }
            else
            {
                Console.WriteLine(options.GetUsage());
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// Test user registration info.
        /// </summary>
        /// <param name="value">Validation parameters.</param>
        /// <returns>Results array for each parameter.</returns>
        public static ValidationField[] ValidateMemberRegistration(
            string firstName,
            string lastName,
            string email,
            string userName,
            string password,
            string birthday,
            string gender,
            bool?terms,
            bool?news,
            UserFieldName requiredFields = 0
            )
        {
            var results = new List <ValidationField>();
            var values  = new List <ValidationField>()
            {
                new ValidationField(UserFieldName.FirstName, firstName ?? ""),
                new ValidationField(UserFieldName.LastName, lastName ?? ""),
                new ValidationField(UserFieldName.Email, email ?? ""),
                new ValidationField(UserFieldName.UserName, userName ?? ""),
                new ValidationField(UserFieldName.Password, password ?? ""),
                new ValidationField(UserFieldName.Birthday, birthday ?? ""),
                new ValidationField(UserFieldName.Gender, gender ?? ""),
                new ValidationField(UserFieldName.Terms, terms),
                new ValidationField(UserFieldName.News, news),
            };
            var allValues = (UserFieldName[])Enum.GetValues(typeof(UserFieldName));

            if (requiredFields == 0)
            {
                requiredFields = (UserFieldName)allValues.Select(x => (int)x).Sum();
            }
            foreach (var item in allValues)
            {
                var description = ClassLibrary.ClassTools.EnumTools.GetDescription(item);
                if (requiredFields.HasFlag(item))
                {
                    var  field  = values.FirstOrDefault(x => x.Name == item);
                    bool isEmpy = field.Value is string
                                  ?string.IsNullOrEmpty((string)field.Value)
                                      : field.Value == null;

                    if (isEmpy)
                    {
                        results.Add(new ValidationField(item, field.Value, "<b>" + description + "</b> is required."));
                    }
                    else if (field.Value is string)
                    {
                        var value = (string)field.Value;
                        if (DisallowedNames.Contains(value))
                        {
                            results.Add(new ValidationField(item, value, "This <b>" + description + "</b> is not allowed."));
                        }
                        if ((item == UserFieldName.FirstName || item == UserFieldName.LastName) && Regex.Match(value, "[a-zA-Z]{1,20}").Value != value)
                        {
                            results.Add(new ValidationField(item, value, "<b>" + description + "</b> must be between 1-20 characters<br/> and contain only letters."));
                        }
                        if (item == UserFieldName.UserName)
                        {
                            if (Regex.Match(value, "[a-zA-Z0-9_]{3,20}").Value != value)
                            {
                                results.Add(new ValidationField(item, value, "<b>" + description + "</b> must be between 3-20 characters<br />and contain only letters or numbers."));
                            }
                            else if (User.GetUser(value) != null)
                            {
                                results.Add(new ValidationField(item, value, "" + description + " is already taken."));
                            }
                        }
                        if (item == UserFieldName.Email)
                        {
                            if (!EmailRegex.Match(email).Success)
                            {
                                results.Add(new ValidationField(item, value, "" + description + " is not valid."));
                            }
                            else if (User.GetUserByEmail(email) != null)
                            {
                                results.Add(new ValidationField(item, value, "" + description + " is already taken."));
                            }
                        }
                        if (item == UserFieldName.Password)
                        {
                            if (value.Length < 6)
                            {
                                results.Add(new ValidationField(item, value, "" + description + " must be at least 6 characters."));
                            }
                            if (password == firstName)
                            {
                                results.Add(new ValidationField(item, value, "" + description + " can't be same as First Name."));
                            }
                            if (password == lastName)
                            {
                                results.Add(new ValidationField(item, value, "" + description + " can't be same as Last Name."));
                            }
                            if (password == userName)
                            {
                                results.Add(new ValidationField(item, value, "" + description + " can't be same as User Name."));
                            }
                            if (password == email)
                            {
                                results.Add(new ValidationField(item, value, "" + description + " can't be same as Email."));
                            }
                            if (!string.IsNullOrEmpty(firstName) && value.Contains(firstName))
                            {
                                results.Add(new ValidationField(item, value, "" + description + " can't contain First Name."));
                            }
                            if (!string.IsNullOrEmpty(lastName) && value.Contains(lastName))
                            {
                                results.Add(new ValidationField(item, value, "" + description + " can't contain Last Name."));
                            }
                            if (!string.IsNullOrEmpty(userName) && value.Contains(userName))
                            {
                                results.Add(new ValidationField(item, value, "" + description + " can't contain User Name."));
                            }
                        }
                        if (item == UserFieldName.Birthday)
                        {
                            DateTime bd;
                            if (!DateTime.TryParse(birthday, out bd))
                            {
                                results.Add(new ValidationField(item, value, description + " is not valid."));
                            }
                        }
                        if (item == UserFieldName.Gender)
                        {
                            if (gender != "M" && gender != "F")
                            {
                                results.Add(new ValidationField(item, value, description + " is not valid."));
                            }
                        }
                    }
                    else
                    {
                        var bValue = (bool?)field.Value;
                        if (item == UserFieldName.Terms)
                        {
                            if (!bValue.Value)
                            {
                                results.Add(new ValidationField(item, bValue, "You must accept <b>" + description + "</b>."));
                            }
                        }
                    }
                }
            }
            return(results.ToArray());
        }
Exemplo n.º 19
0
 public static bool IsValidEmail(this string str)
 {
     return(str != null && EmailRegex.IsMatch(str));
 }