Example #1
0
        public static void IsValidEmailAddressOrEmpty(string emailAddress, ISet <string> errors)
        {
            if (emailAddress == null)
            {
                return; //contractors may miss email
            }
            emailAddress = emailAddress.Trim();
            var emailCount = emailAddress.Count(x => x == '@');

            switch (emailCount)
            {
            case 0:
                errors.IfTrueAdd(!string.IsNullOrEmpty(emailAddress), I18n.Translate("This is not a valid email address"));
                return;

            case 1:
                if (emailAddress.Length < 3 ||
                    emailAddress.IndexOf('@') == 0 ||
                    emailAddress.IndexOf('@') == emailAddress.Length - 1)
                {
                    errors.Add(I18n.Translate("This is not a valid email address"));
                }
                return;

            default:
                errors.IfTrueAdd(!string.IsNullOrEmpty(emailAddress.Trim()), I18n.Translate("This is not a valid email address"));
                break;
            }
        }
Example #2
0
 public static Validate <T?> MustBePositive <T>() where T : struct, IComparable <T>
 {
     return((x, errors) => {
         if (!x.HasValue || default(T).CompareTo(x.Value) >= 0)
         {
             errors.Add(I18n.Translate("Must be positive"));
         }
     });
 }
Example #3
0
        public static void IsNotNull <T>(T x, ISet <string> errors) where T : new()
        {
            var realNull = default(T) == null;

            errors.IfTrueAdd(
                realNull && null == x ||
                !realNull && default(T).Equals(x),
                I18n.Translate("Field cannot be empty"));
        }
Example #4
0
        public string Localize(bool input, BoolFormat format)
        {
            switch (format)
            {
            case BoolFormat.UnicodeBallotBox: return(LocalizationUtil.BoolToUnicodeCheckbox(input));

            case BoolFormat.YesNo: return(input ? I18n.Translate("Yes") : I18n.Translate("No"));

            case BoolFormat.TrueFalse: return(input ? I18n.Translate("True") : I18n.Translate("False"));

            default: throw new Exception("unsupported BoolFormat");
            }
        }
        public static string GetUserFriendlyPattern(this DateTimeFormat format)
        {
            switch (format)
            {
            case DateTimeFormat.DateOnly: return(I18n.Translate("YYYY-MM-DD"));

            case DateTimeFormat.YMDhm: return(I18n.Translate("YYYY-MM-DD hh:mm"));

            case DateTimeFormat.YMDhms: return(I18n.Translate("YYYY-MM-DD hh:mm:ss"));

            case DateTimeFormat.YM: return(I18n.Translate("YYYY-MM"));

            case DateTimeFormat.Y: return(I18n.Translate("YYYY"));

            default: throw new ArgumentException("BuildDateTimePicker got unexpected format");
            }
        }
Example #6
0
        public decimal ParseDecimal(string s)
        {
            var inp = s
                      .Replace(NonbreakableSpaceStr, "") //nonbreakable space
                      .Replace(" ", "");

            if (SupposedlyDecimalContainsUnknownChars(s))
            {
                throw new FormatException(I18n.Translate("Illegal characters in number"));
            }

            //still some Bridge bugs
            inp = inp
                  .Replace(_currentCulture.NumberFormat.NumberGroupSeparator, "")
                  .Replace(_currentCulture.NumberFormat.NumberDecimalSeparator, ".");
            return(Convert.ToDecimal(inp, CultureInfo.InvariantCulture));
        }
Example #7
0
        // REVIEW: valuetuple
        public static Tuple <ValueChangedRich <bool>, Action> BindAction <WidgetT, T>(this IActionView <WidgetT> view, IActionModel <T> domain)
        {
            ValueChangedRich <bool> domainHandler = (sender, oldValue, newValue, errors, isUserAction) => {
                Logger.Debug(typeof(ActionViewExtensions), "BindAction: changing view to {0} and {1}", newValue, errors.PrettyToString());
                view.Enabled        = newValue;
                view.DisabledReason = new HashSet <string>(errors);
            };

            domain.EnabledChanged += domainHandler;

            Action viewHandler = async() => {
                Logger.Debug(typeof(ActionViewExtensions), "BindAction: triggering enabled?={0} action {1} from view {2}", domain.Enabled, domain, view);
                if (!domain.Enabled)
                {
                    return;
                }

                view.State          = ActionViewState.CreateOperationRunning();
                view.Enabled        = false;
                view.DisabledReason = new HashSet <string> {
                    I18n.Translate("Please wait while operation is running...")
                };
                try {
                    await domain.Trigger();

                    view.State = ActionViewState.CreateIdleOrSuccess();
                } catch (Exception ex) {
                    Logger.Error(typeof(ActionViewExtensions), "Bound action failed to execute {0}", ex);
                    view.State = ActionViewState.CreateOperationFailed(ex);
                    //should be handled by domain.ActionExecuted subscribers
                } finally {
                    view.Enabled        = domain.Enabled;
                    view.DisabledReason = new HashSet <string>(domain.DisabledReasons);
                }
            };

            view.Triggered += viewHandler;
            return(new Tuple <ValueChangedRich <bool>, Action>(domainHandler, viewHandler));
        }
Example #8
0
 public static void IsNotNull <T>(T?x, ISet <string> errors) where T : struct
 {
     errors.IfTrueAdd(!x.HasValue, I18n.Translate("Field cannot be empty"));
 }
Example #9
0
 public static Validate <T?> MustBeNonNegative <T>() where T : struct, IComparable <T>
 {
     return((x, errors) => errors.IfTrueAdd(
                x.HasValue && default(T).CompareTo(x.Value) > 0,
                I18n.Translate("Must be non negative")));
 }
Example #10
0
 public static void IsNotNullRef <T>(T x, ISet <string> errors) where T : class
 {
     errors.IfTrueAdd(x == null, I18n.Translate("Field cannot be empty"));
 }
Example #11
0
 public static void MustBeNonNegative <T>(T x, ISet <string> errors) where T : IComparable <T>
 {
     IsBiggerOrEqualTo(default(T), I18n.Translate("Must be zero or more"))(x, errors);
 }
Example #12
0
        public decimal ParseDecimalWithoutLoss(string s, int precision)
        {
            var inp = s
                      .Replace(NonbreakableSpaceStr, "") //nonbreakable space
                      .Replace(" ", "");

            if (SupposedlyDecimalContainsUnknownChars(s))
            {
                throw new FormatException(I18n.Translate("Illegal characters in number"));
            }

            //still some Bridge bugs
            inp = inp
                  .Replace(_currentCulture.NumberFormat.NumberGroupSeparator, "")
                  .Replace(_currentCulture.NumberFormat.NumberDecimalSeparator, ".");
            var beforeAndAfter = inp.Split('.'); //Chrome ignores xx in '<html lang=xx>' and overrides '<input type=number>' decimal character with one taken from browser's language/system locale

            if (beforeAndAfter.Length < 1)
            {
                throw new Exception("bug - got zero tokens");
            }

            if (precision < 0)
            {
                throw new Exception("bug - incorrect precision");
            }

            if (precision == 0)
            {
                if (beforeAndAfter.Length > 1)
                {
                    throw new Exception(I18n.Translate("Decimal part is not allowed"));
                }

                //beforeAndAfter.Length must be 1 since here

                return(Convert.ToDecimal(beforeAndAfter[0], _currentCulture));
            }

            //precision must be > 0 since here

            if (beforeAndAfter.Length > 2)
            {
                throw new Exception(I18n.Translate("Incorrect number format"));
            }

            if (beforeAndAfter.Length == 1)
            {
                //no decimal part
                return(Convert.ToDecimal(beforeAndAfter[0], _currentCulture));
            }

            var actualFactPrecision = beforeAndAfter[1].TrimEnd('0').Length;

            if (actualFactPrecision > precision)
            {
                throw new Exception(string.Format(
                                        I18n.Translate("Error: allowed {0} digits after decimal point"), precision));
            }

            return(Convert.ToDecimal(
                       beforeAndAfter[0] + "." + beforeAndAfter[1],
                       CultureInfo.InvariantCulture));
        }
Example #13
0
 public static void MustBePositive <T>(T x, ISet <string> errors) where T : IComparable <T>
 {
     IsBiggerThan(default(T), I18n.Translate("Must be positive"))(x, errors);
 }
Example #14
0
 public static void MustBeTomorrowOrLaterNullable(DateTime?x, ISet <string> errors)
 {
     errors.IfTrueAdd(x.HasValue && x.Value.Date < DateTimeExtensions.BuildSoonestMidnight(), I18n.Translate("Must be tomorrow or later"));
 }
Example #15
0
 public static void CannotBePastDate(DateTime?x, ISet <string> errors)
 {
     errors.IfTrueAdd(x.HasValue && x.Value.Date < DateTime.Now.Date, I18n.Translate("Cannot be past date"));
 }
Example #16
0
 public static void IsNotEmptyOrWhitespaceOnly(string x, ISet <string> errors)
 {
     errors.IfTrueAdd(string.IsNullOrWhiteSpace(x), I18n.Translate("Field cannot be empty"));
 }
Example #17
0
 public static Validate <string> LimitSize(int length, string customerErrorMsg0 = null)
 {
     return((v, errors) => errors.IfTrueAdd(v != null && v.Length > length,
                                            string.Format(customerErrorMsg0 ?? I18n.Translate("Field is too long by {0} chars"), v?.Length - length)));
 }