public static IAsyncValidationRule AddChildValidatable([NotNull] this ValidationHelper validator,
                                                               [NotNull] Expression <Func <IValidatable> > childValidatableGetter)
        {
            Guard.NotNull(validator, nameof(validator));
            Guard.NotNull(childValidatableGetter, nameof(childValidatableGetter));

            Func <IValidatable> getter = childValidatableGetter.Compile();

            return(validator.AddAsyncRule(PropertyName.For(childValidatableGetter), () =>
            {
                IValidatable validatable = getter();

                if (validatable != null)
                {
                    return validatable.Validate().ContinueWith(r =>
                    {
                        ValidationResult result = r.Result;

                        var ruleResult = new RuleResult();

                        foreach (ValidationError error in result.ErrorList)
                        {
                            ruleResult.AddError(error.ErrorText);
                        }

                        return ruleResult;
                    });
                }

                return TaskEx.FromResult(RuleResult.Valid());
            }));
        }
Ejemplo n.º 2
0
        protected void RaisePropertyChanged(
            Expression <Func <object> > expression)
        {
            var propertyName = PropertyName.For(expression);

            this.RaisePropertyChanged(propertyName);
        }
Ejemplo n.º 3
0
        public static void Update(string DIN, string bloodGroup, string note)
        {
            RedBloodDataContext db = new RedBloodDataContext();

            Donation e = DonationBLL.Get(db, DIN);

            if (e == null)
            {
                throw new Exception(DonationErrEnum.NonExist.Message);
            }

            if (!CanUpdateTestResult(e))
            {
                throw new Exception(DonationErrEnum.TRLocked.Message);
            }

            if (bloodGroup.Trim() != e.BloodGroup)
            {
                e.BloodGroup = bloodGroup;
                DonationTestLogBLL.Insert(db, e, PropertyName.For <Donation>(r => r.BloodGroup), note);
            }

            //Have to save before updaye TestResult Status
            db.SubmitChanges();

            UpdateTestResultStatus(e);
            db.SubmitChanges();
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Localizeds the label for.
        /// </summary>
        /// <typeparam name="TModel">The type of the model.</typeparam>
        /// <param name="html">The HTML helper instance that this method extends.</param>
        /// <param name="propertyAccessor">The property accessor.</param>
        /// <param name="options">The options.</param>
        /// <returns>
        /// An HTML label element and the property name of the property that is represented by the model.
        /// </returns>
        public static MvcHtmlString LocalizedLabelFor <TModel>(this HtmlHelper <TModel> html, Expression <Func <TModel, Object> > propertyAccessor, Object options)
        {
            var labelText = ResourceHelper.TranslatePropertyName(html.ViewContext.HttpContext, typeof(TModel), PropertyName.For(propertyAccessor));

            if (String.IsNullOrEmpty(labelText))
            {
                labelText = PropertyName.For(propertyAccessor).Humanize();
            }

            var builder = new TagBuilder("label");

            builder.Attributes.Add("for", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(String.Empty));

            var routeValues = new RouteValueDictionary(options);

            routeValues = Defaults.Merge(routeValues);

            Object cssClass;

            if (routeValues.TryGetValue(CssClassKey, out cssClass))
            {
                builder.AddCssClass(cssClass as String);
            }

            if (html.ViewData.ModelMetadata.IsRequired && (bool)routeValues[DisplayAsterixKey])
            {
                labelText = String.Format("{0}{1}", labelText, routeValues[AsterixKey]);
            }

            builder.SetInnerText(labelText);
            MvcHtmlString result = MvcHtmlString.Create(builder.ToString(TagRenderMode.Normal));

            return(result);
        }
        public ValidationResult GetResult([NotNull] Expression <Func <object> > propertyExpression)
        {
            Contract.Requires(propertyExpression != null);
            Contract.Ensures(Contract.Result <ValidationResult>() != null);

            return(GetResult(PropertyName.For(propertyExpression)));
        }
Ejemplo n.º 6
0
        public IAsyncValidationRule AddAsyncRule([NotNull] IEnumerable <Expression <Func <object> > > properties, [NotNull] Func <Task <RuleResult> > validateAction)
        {
            Guard.NotNull(properties, nameof(properties));
            Guard.NotNull(validateAction, nameof(validateAction));

            return(AddAsyncRule(properties.Select(x => PropertyName.For(x, false)), validateAction));
        }
Ejemplo n.º 7
0
        public void RemoveRule_ThereAreTwoFailedRules_RemoveOne_ResultChangedShouldBeFiredWithNewResultStillInvalid()
        {
            // ARRANGE
            var dummy = new DummyViewModel();

            var validation = new ValidationHelper();

            validation.AddRule(() => dummy.Foo, () => RuleResult.Invalid("error2"));
            var invalidRule = validation.AddRule(() => dummy.Foo, () => RuleResult.Invalid("error"));

            var validationResult = validation.ValidateAll();

            Assert.False(validationResult.IsValid);

            bool resultChangedEventFired = false;

            validation.ResultChanged += (sender, args) =>
            {
                Assert.Equal(PropertyName.For(() => dummy.Foo), args.Target);
                Assert.False(args.NewResult.IsValid);

                resultChangedEventFired = true;
            };

            // ACT
            validation.RemoveRule(invalidRule);

            // VERIFY
            Assert.True(resultChangedEventFired);
        }
Ejemplo n.º 8
0
        public Task <ValidationResult> ValidateAsync([NotNull] Expression <Func <object> > propertyPathExpression)
        {
            Contract.Requires(propertyPathExpression != null);
            Contract.Ensures(Contract.Result <Task <ValidationResult> >() != null);

            return(ValidateInternalAsync(PropertyName.For(propertyPathExpression)));
        }
Ejemplo n.º 9
0
        /// <summary>
        /// OBSOLTE: If you are using C# 6 compiler consider using another overload of this method that
        /// takes a <see cref="string"/> argument (<see cref="AddRule(string,System.Func{MvvmValidation.RuleResult})"/>)
        /// and invoke it with nameof(MyProperty) instead.
        /// </summary>
        public IValidationRule AddRule([NotNull] Expression <Func <object> > propertyExpression,
                                       [NotNull] Func <RuleResult> validateDelegate)
        {
            Guard.NotNull(propertyExpression, nameof(propertyExpression));
            Guard.NotNull(validateDelegate, nameof(validateDelegate));

            return(AddRule(PropertyName.For(propertyExpression, false), validateDelegate));
        }
Ejemplo n.º 10
0
        public IValidationRule AddRule([NotNull] IEnumerable <Expression <Func <object> > > properties,
                                       [NotNull] Func <RuleResult> validateDelegate)
        {
            Guard.NotNull(properties, nameof(properties));
            Guard.NotNull(validateDelegate, nameof(validateDelegate));

            return(AddRule(properties.Select(x => PropertyName.For(x, false)), validateDelegate));
        }
Ejemplo n.º 11
0
        public IAsyncValidationRule AddAsyncRule([NotNull] Expression <Func <object> > property1Expression, [NotNull] Expression <Func <object> > property2Expression, [NotNull] Func <Task <RuleResult> > validateAction)
        {
            Guard.NotNull(property1Expression, nameof(property1Expression));
            Guard.NotNull(property2Expression, nameof(property2Expression));
            Guard.NotNull(validateAction, nameof(validateAction));

            return(AddAsyncRule(PropertyName.For(property1Expression, false), PropertyName.For(property2Expression, false), validateAction));
        }
Ejemplo n.º 12
0
        public void RaisePropertyChanged(Expression <Func <object> > propertyExpression)
        {
            PropertyChangedEventHandler handler = PropertyChanged;

            if (handler != null)
            {
                handler(this, new PropertyChangedEventArgs(PropertyName.For(propertyExpression)));
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Validates the form element.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <param name="modelState">State of the model.</param>
        public static void ValidateFormElement(FormElementViewModel model, ModelStateDictionary modelState)
        {
            var currentType = model.Types.Find(type => type.Type == model.Type.ToString());

            if (currentType.IsValuesEnabled && String.IsNullOrEmpty(model.Values))
            {
                modelState.AddModelError(PropertyName.For <FormElementViewModel>(item => item.Values),
                                         ResourceHelper.TranslateErrorMessage(new HttpContextWrapper(HttpContext.Current), typeof(FormElementViewModel),
                                                                              PropertyName.For <FormElementViewModel>(item => item.Values), "required", null));
            }
        }
Ejemplo n.º 14
0
 /// <summary>
 ///     Databinding with strongly typed object names
 /// </summary>
 /// <typeparam name="TControl">The type of the control.</typeparam>
 /// <typeparam name="TDataSourceItem">The type of the data source item.</typeparam>
 /// <param name="control">The control you are binding to</param>
 /// <param name="controlProperty">The property on the control you are binding to</param>
 /// <param name="dataSource">The object you are binding to</param>
 /// <param name="dataSourceProperty">The property on the object you are binding to</param>
 /// <returns>The Binding.</returns>
 public static Binding Bind <TControl, TDataSourceItem>(
     this TControl control,
     Expression <Func <TControl, object> > controlProperty,
     object dataSource,
     Expression <Func <TDataSourceItem, object> > dataSourceProperty)
     where TControl : Control
 {
     return(control.DataBindings.Add(
                PropertyName.For(controlProperty),
                dataSource,
                PropertyName.For(dataSourceProperty)));
 }
Ejemplo n.º 15
0
        public ActionResult UpdateFindMapCenter(string lat, string lng)
        {
            if (!String.IsNullOrEmpty(lat))
            {
                Repo.InsertOrUpdate(PropertyName.For(() => AppSetting.FindMapCenterLat), lat);
            }

            if (!String.IsNullOrEmpty(lng))
            {
                Repo.InsertOrUpdate(PropertyName.For(() => AppSetting.FindMapCenterLng), lng);
            }

            return(RedirectToAction("Index", "Home"));
        }
Ejemplo n.º 16
0
        public ActionResult UpdatePicasaAccount(string username, string password)
        {
            if (!String.IsNullOrEmpty(username))
            {
                Repo.InsertOrUpdate(PropertyName.For(() => AppSetting.GoogleUsername), username);
            }

            if (!String.IsNullOrEmpty(password))
            {
                Repo.InsertOrUpdate(PropertyName.For(() => AppSetting.GooglePassword), password);
            }

            return(RedirectToAction("Index", "Home"));
        }
Ejemplo n.º 17
0
 /// <summary>
 /// Validates the form model.
 /// </summary>
 /// <param name="model">The model.</param>
 /// <param name="modelState">State of the model.</param>
 public static void ValidateForm(FormViewModel model, ModelStateDictionary modelState)
 {
     if (model.ShowSubmitButton && String.IsNullOrEmpty(model.SubmitButtonText))
     {
         modelState.AddModelError(PropertyName.For <FormViewModel>(item => item.SubmitButtonText),
                                  ResourceHelper.TranslateErrorMessage(new HttpContextWrapper(HttpContext.Current), typeof(FormViewModel),
                                                                       PropertyName.For <FormViewModel>(item => item.SubmitButtonText), "required", null));
     }
     if (model.ShowResetButton && String.IsNullOrEmpty(model.ResetButtonText))
     {
         modelState.AddModelError(PropertyName.For <FormViewModel>(item => item.ResetButtonText),
                                  ResourceHelper.TranslateErrorMessage(new HttpContextWrapper(HttpContext.Current), typeof(FormViewModel),
                                                                       PropertyName.For <FormViewModel>(item => item.ResetButtonText), "required", null));
     }
 }
        public int GetScore(Expression <Func <Site, object> > expression)
        {
            try
            {
                var propertyName = PropertyName.For(expression);
                var value        = this.GetType().GetProperty(propertyName).GetValue(this, null).ToString();

                return((int)CodeMasterRepository.I.Get(propertyName, value).Score.ToInt());
            }
            catch (Exception ex)
            {
                Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
                return(0);
            }
        }
Ejemplo n.º 19
0
 /// <summary>
 ///     Binds the specified control property.
 /// </summary>
 /// <typeparam name="TControl">The type of the control.</typeparam>
 /// <typeparam name="TDataSourceItem">The type of the data source item.</typeparam>
 /// <param name="control">The control you are binding to.</param>
 /// <param name="controlProperty">The control property.</param>
 /// <param name="dataSource">The data source.</param>
 /// <param name="dataSourceProperty">The data source property.</param>
 /// <param name="updateMode">The update mode.</param>
 /// <param name="formattingEnabled">if set to <c>true</c> formatting is enabled.</param>
 /// <returns>The Binding.</returns>
 public static Binding Bind <TControl, TDataSourceItem>(
     this TControl control,
     Expression <Func <TControl, object> > controlProperty,
     object dataSource,
     Expression <Func <TDataSourceItem, object> > dataSourceProperty,
     DataSourceUpdateMode updateMode,
     bool formattingEnabled)
     where TControl : Control
 {
     return(control.DataBindings.Add(
                PropertyName.For(controlProperty),
                dataSource,
                PropertyName.For(dataSourceProperty),
                formattingEnabled,
                updateMode));
 }
Ejemplo n.º 20
0
        public static DonationErr Update(string DIN,
                                         string HIV, string HCV_Ab, string HBs_Ag, string Syphilis, string Malaria,
                                         string note, bool updateIfAllNon = false)
        {
            RedBloodDataContext db = new RedBloodDataContext();

            Donation e = DonationBLL.Get(db, DIN);

            if (e == null || !CanUpdateTestResult(e))
            {
                return(DonationErrEnum.TRLocked);
            }

            string old = e.InfectiousMarkers;

            if (!updateIfAllNon ||
                (updateIfAllNon && e.Markers.IsAllNon)
                )
            {
                // Warning: As CR user requirement, value for both test result are always the same.
                e.InfectiousMarkers = Infection.HIV_Ab.Encode(e.InfectiousMarkers, HIV);
                e.InfectiousMarkers = Infection.HIV_Ag.Encode(e.InfectiousMarkers, HIV);

                e.InfectiousMarkers = Infection.HCV_Ab.Encode(e.InfectiousMarkers, HCV_Ab);
                e.InfectiousMarkers = Infection.HBs_Ag.Encode(e.InfectiousMarkers, HBs_Ag);
                e.InfectiousMarkers = Infection.Syphilis.Encode(e.InfectiousMarkers, Syphilis);
                e.InfectiousMarkers = Infection.Malaria.Encode(e.InfectiousMarkers, Malaria);

                if (old != e.InfectiousMarkers)
                {
                    DonationTestLogBLL.Insert(db, e, PropertyName.For <Donation>(r => r.Markers), note);
                }

                //Have to save before update TestResult Status
                db.SubmitChanges();

                UpdateTestResultStatus(e);
                db.SubmitChanges();
            }

            return(DonationErrEnum.Non);
        }
Ejemplo n.º 21
0
        public void Reset_ResultChangedFiresForInvalidTargets()
        {
            // ARRANGE
            var dummy = new DummyViewModel();

            var validation = new ValidationHelper();

            validation.AddRule(RuleResult.Valid);
            validation.AddRule(() => dummy.Foo, () => RuleResult.Invalid("error1"));
            validation.AddRule(() => dummy.Bar, () => RuleResult.Invalid("error2"));

            validation.ValidateAll();

            bool eventFiredForFoo = false;
            bool evernFiredForBar = false;

            validation.ResultChanged += (sender, args) =>
            {
                if (Equals(args.Target, PropertyName.For(() => dummy.Foo)))
                {
                    eventFiredForFoo = true;
                }
                else if (Equals(args.Target, PropertyName.For(() => dummy.Bar)))
                {
                    evernFiredForBar = true;
                }
                else
                {
                    Assert.False(true, "ResultChanged event fired for an unexpected target.");
                }

                Assert.True(args.NewResult.IsValid);
            };

            // ACT
            validation.Reset();

            // VERIFY
            Assert.True(eventFiredForFoo);
            Assert.True(evernFiredForBar);
        }
        public static IValidationRule AddRequiredRule([NotNull] this ValidationHelper validator,
                                                      [NotNull] Expression <Func <object> > propertyExpression, [NotNull] string errorMessage)
        {
            Guard.NotNull(validator, nameof(validator));
            Guard.NotNull(propertyExpression, nameof(propertyExpression));
            Guard.NotNullOrEmpty(errorMessage, nameof(errorMessage));

            Func <object> propertyGetter = propertyExpression.Compile();

            return(validator.AddRule(PropertyName.For(propertyExpression, false), () =>
            {
                object propertyValue = propertyGetter();

                var stringPropertyValue = propertyValue as string;

                if (propertyValue == null || (stringPropertyValue != null && string.IsNullOrEmpty(stringPropertyValue)))
                {
                    return RuleResult.Invalid(errorMessage);
                }

                return RuleResult.Valid();
            }));
        }
        public static IAsyncValidationRule AddChildValidatable([NotNull] this ValidationHelper validator,
                                                               [NotNull] Expression <Func <IValidatable> > childValidatableGetter)
        {
            Contract.Requires(validator != null);
            Contract.Requires(childValidatableGetter != null);
            Contract.Ensures(Contract.Result <IAsyncValidationRule>() != null);

            Func <IValidatable> getter = childValidatableGetter.Compile();

            return(validator.AddAsyncRule(PropertyName.For(childValidatableGetter), () =>
            {
                IValidatable validatable = getter();

                if (validatable != null)
                {
#if SILVERLIGHT_4
                    validatable.Validate(result =>
                    {
#else
                    return validatable.Validate().ContinueWith(r =>
                    {
                        ValidationResult result = r.Result;
#endif
                        var ruleResult = new RuleResult();

                        foreach (ValidationError error in result.ErrorList)
                        {
                            ruleResult.AddError(error.ErrorText);
                        }

                        return ruleResult;
                    });
                }

                return Task.Factory.StartNew(() => RuleResult.Valid());
            }));
        }
Ejemplo n.º 24
0
 /// <summary>
 /// Validates the article model.
 /// </summary>
 /// <param name="model">The model.</param>
 /// <param name="modelState">State of the model.</param>
 public static void ValidateArticle(ArticleViewModel model, ModelStateDictionary modelState)
 {
     if (!String.IsNullOrEmpty(model.Url))
     {
         if (model.UrlType == ArticleUrlType.External)
         {
             if (!Regex.IsMatch(model.Url, RegexValidationConfig.GetPattern(RegexTemplates.Url)))
             {
                 modelState.AddModelError(PropertyName.For <ArticleViewModel>(item => item.Url),
                                          ResourceHelper.TranslateErrorMessage(new HttpContextWrapper(HttpContext.Current), typeof(ArticleViewModel),
                                                                               PropertyName.For <ArticleViewModel>(item => item.Url), "regularexpression", null));
             }
         }
         else if (model.UrlType == ArticleUrlType.Internal)
         {
             if (!Regex.IsMatch(model.Url, RegexValidationConfig.GetPattern(RegexTemplates.UrlPart)))
             {
                 modelState.AddModelError(PropertyName.For <ArticleViewModel>(item => item.Url),
                                          ResourceHelper.TranslateErrorMessage(new HttpContextWrapper(HttpContext.Current), typeof(ArticleViewModel),
                                                                               PropertyName.For <ArticleViewModel>(item => item.Url), "regularexpression", null));
             }
         }
     }
 }
Ejemplo n.º 25
0
        public ActionResult UpdateMapBound(string swlat, string swlng, string nelat, string nelng)
        {
            if (!String.IsNullOrEmpty(swlat))
            {
                Repo.InsertOrUpdate(PropertyName.For(() => AppSetting.MapBoundSWLat), swlat);
            }

            if (!String.IsNullOrEmpty(swlng))
            {
                Repo.InsertOrUpdate(PropertyName.For(() => AppSetting.MapBoundSWLng), swlng);
            }

            if (!String.IsNullOrEmpty(nelat))
            {
                Repo.InsertOrUpdate(PropertyName.For(() => AppSetting.MapBoundNELat), nelat);
            }

            if (!String.IsNullOrEmpty(nelng))
            {
                Repo.InsertOrUpdate(PropertyName.For(() => AppSetting.MapBoundNELng), nelng);
            }

            return(RedirectToAction("Index", "Home"));
        }
Ejemplo n.º 26
0
        public Task <ValidationResult> ValidateAsync([NotNull] Expression <Func <object> > propertyPathExpression)
        {
            Guard.NotNull(propertyPathExpression, nameof(propertyPathExpression));

            return(ValidateAsync(PropertyName.For(propertyPathExpression, false)));
        }
Ejemplo n.º 27
0
        public ValidationResult GetResult([NotNull] Expression <Func <object> > propertyExpression)
        {
            Guard.NotNull(propertyExpression, nameof(propertyExpression));

            return(GetResult(PropertyName.For(propertyExpression, false)));
        }
Ejemplo n.º 28
0
 public static bool SetFocus(this IViewAware screen, Expression <Func <object> > propertyExpression)
 {
     return(SetFocus(screen, PropertyName.For(propertyExpression)));
 }
        public static IAsyncValidationRule AddChildValidatableCollection([NotNull] this ValidationHelper validator,
                                                                         [NotNull] Expression <Func <IEnumerable <IValidatable> > > validatableCollectionGetter)
        {
            Contract.Requires(validator != null);
            Contract.Requires(validatableCollectionGetter != null);
            Contract.Ensures(Contract.Result <IAsyncValidationRule>() != null);

            Func <IEnumerable <IValidatable> > getter = validatableCollectionGetter.Compile();

            return(validator.AddAsyncRule(PropertyName.For(validatableCollectionGetter), () =>
            {
                IEnumerable <IValidatable> items = getter();

                if (items == null)
                {
                    return Task.Factory.StartNew(() => RuleResult.Valid());
                }

                return Task.Factory.StartNew(() =>
                {
                    var result = new RuleResult();

                    // Execute validation on all items at the same time, wait for all
                    // to fininish and combine the results.

                    var results = new List <ValidationResult>();

                    var syncEvent = new ManualResetEvent(false);

                    var itemsArray = items as IValidatable[] ?? items.ToArray();
                    int[] numerOfThreadsNotYetCompleted = { itemsArray.Length };

                    foreach (var item in itemsArray)
                    {
#if SILVERLIGHT_4
                        item.Validate(r =>
                        {
                            Exception ex = null;
#else
                        item.Validate().ContinueWith(tr =>
                        {
                            ValidationResult r = tr.Result;
                            AggregateException ex = tr.Exception;
#endif
                            lock (results)
                            {
                                // ReSharper disable ConditionIsAlwaysTrueOrFalse
                                if (ex == null && r != null)
                                // ReSharper restore ConditionIsAlwaysTrueOrFalse
                                {
                                    results.Add(r);
                                }

                                if (Interlocked.Decrement(ref numerOfThreadsNotYetCompleted[0]) == 0)
                                {
                                    syncEvent.Set();
                                }
                            }
                        });
                    }

                    if (numerOfThreadsNotYetCompleted[0] > 0)
                    {
                        // Wait for all items to finish validation
                        syncEvent.WaitOne();

                                          // Add errors from all validation results
                                          foreach (ValidationResult itemResult in results)
                        {
                            foreach (ValidationError error in itemResult.ErrorList)
                            {
                                result.AddError(error.ErrorText);
                            }
                        }
                    }

                    return result;
                });
            }));
        }
Ejemplo n.º 30
0
 public static Binding Bind <TControl, TDataSourceItem>(this TControl control, Expression <Func <TControl, object> > controlProperty, object dataSource, Expression <Func <TDataSourceItem, object> > dataSourceProperty, bool formattingEnabled, DataSourceUpdateMode updateMode, object nullValue, string formatString, IFormatProvider formatInfo)
     where TControl : Control
 {
     return(control.DataBindings.Add(PropertyName.For(controlProperty), dataSource, PropertyName.For(dataSourceProperty), formattingEnabled, updateMode, nullValue, formatString, formatInfo));
 }