Пример #1
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);
                });
            }
 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.");
     }
 }
Пример #3
0
        private void ValidateEmail(EmailSendServer email, MessageDisplay msgDisplay, int line)
        {
            if (string.IsNullOrEmpty(email.SmtpServer))
            {
                msgDisplay.AddError(new CustomError("SmtpServer", line, "smtp服务器地址不能为空!"));
            }

            if (string.IsNullOrEmpty(email.SenderEmail))
            {
                msgDisplay.AddError(new CustomError("SenderEmail", line, "发送端Email地址不能为空"));
            }
            else if (!emailreg.IsMatch(email.SenderEmail))
            {
                msgDisplay.AddError(new CustomError("SenderEmail", line, "发送端Email地址格式错误"));
            }


            if (string.IsNullOrEmpty(email.SmtpServerAccount))
            {
                msgDisplay.AddError(new CustomError("SmtpServerAccount", line, "邮箱用户名不能为空"));
            }

            if (string.IsNullOrEmpty(email.SmtpServerPassword))
            {
                msgDisplay.AddError(new CustomError("SmtpServerPassword", line, "邮箱密码不能为空"));
            }

            if (email.Port > 65535 || email.Port < 2)
            {
                msgDisplay.AddError(new CustomError("Port", line, "SMTP服务器端口错误"));
            }
        }
Пример #4
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);
 }
        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);
            }
        }
Пример #6
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));
 }
Пример #7
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);
 }
Пример #8
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
            });
        }
Пример #9
0
 public static bool IsValidEmail(string email)
 {
     return(!string.IsNullOrEmpty(email) && EmailRegex.IsMatch(email));
 }
Пример #10
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());
            }
        }
Пример #11
0
 public static bool ValidateEmail(string strToMatch)
 {
     return(EmailRegex.IsMatch(strToMatch));
 }
Пример #12
0
 private bool ValidateEmail(string email)
 {
     return(EmailRegex.IsMatch(email));
 }
Пример #13
0
 public static bool IsValidEmail(this string str)
 {
     return(str != null && EmailRegex.IsMatch(str));
 }