當前位置: 首頁>>代碼示例>>C#>>正文


C# ValidationContext.GetService方法代碼示例

本文整理匯總了C#中System.ComponentModel.DataAnnotations.ValidationContext.GetService方法的典型用法代碼示例。如果您正苦於以下問題:C# ValidationContext.GetService方法的具體用法?C# ValidationContext.GetService怎麽用?C# ValidationContext.GetService使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在System.ComponentModel.DataAnnotations.ValidationContext的用法示例。


在下文中一共展示了ValidationContext.GetService方法的8個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的C#代碼示例。

示例1: GetValidationService

 private static IValidationService GetValidationService(ValidationContext validationContext)
 {
     var service = ((IValidationService)validationContext.GetService(typeof(IValidationService)));
     if (service == null)
         service = Factories.BuildValidationService();
     return service;
 }
開發者ID:flobacher,項目名稱:unobtrusive-angular-validation,代碼行數:7,代碼來源:ValidateObjectAttribute.cs

示例2: IsValid

 /// <summary>
 /// Validates the specified value with respect to the current validation attribute.
 /// </summary>
 /// <param name="value"></param>
 /// <param name="validationContext"></param>
 /// <returns></returns>
 protected override ValidationResult IsValid(object value, ValidationContext validationContext)
 {
     if (value == null)
         return null;
     IEntity entity = (IEntity)validationContext.ObjectInstance;
     dynamic entityContext;
     Type type = validationContext.ObjectType;
     while (type.Assembly.IsDynamic)
         type = type.BaseType;
     entityContext = validationContext.GetService(typeof(IEntityQueryable<>).MakeGenericType(type));
     if (entityContext == null)
         return null;
     if (value is string && IsCaseSensitive)
         value = ((string)value).ToLower();
     ParameterExpression parameter = Expression.Parameter(type);
     Expression left = Expression.NotEqual(Expression.Property(parameter, "Index"), Expression.Constant(entity.Index));
     Expression right;
     if (value is string && IsCaseSensitive)
         right = Expression.Equal(Expression.Call(Expression.Property(parameter, validationContext.MemberName), typeof(string).GetMethod("ToLower")), Expression.Constant(value));
     else
         right = Expression.Equal(Expression.Property(parameter, validationContext.MemberName), Expression.Constant(value));
     Expression expression = Expression.And(left, right);
     expression = Expression.Lambda(typeof(Func<,>).MakeGenericType(type, typeof(bool)), expression, parameter);
     object where = _QWhereMethod.MakeGenericMethod(type).Invoke(null, new[] { entityContext.Query(), expression });
     int count = (int)_QCountMethod.MakeGenericMethod(type).Invoke(null, new[] { where });
     if (count != 0)
         return new ValidationResult(string.Format("{0} can not be {1}, there is a same value in the database.", validationContext.MemberName, value));
     else
         return null;
 }
開發者ID:alexyjian,項目名稱:ComBoost,代碼行數:36,代碼來源:DistinctAttribute.cs

示例3: IsValid

 protected override ValidationResult IsValid(object value, ValidationContext validationContext)
 {
     var email = value as String;
     if (email == null)
     {
         throw new ArgumentException("Property type is not String");
     }
     var repository = validationContext.GetService(typeof(IUserRepository)) as IUserRepository;
     if (repository == null)
     {
         throw new InvalidOperationException("Can't access repository");
     }
     var user = AsyncHelper.RunSynchronously(() => repository.GetUserByEmail(email));
     if (user != null)
     {
         return new ValidationResult(String.Format("This email '{0}' has taken by another user", email), new [] {validationContext.DisplayName});
     }
     return null;
 }
開發者ID:WadeOne,項目名稱:EasyTeach,代碼行數:19,代碼來源:UniqueEmailAttribute.cs

示例4: IsValidLocation

        public static ValidationResult IsValidLocation(string location, ValidationContext validationContext)
        {
            if (!string.IsNullOrEmpty(location))
            {
                var meetingData = validationContext.GetService(typeof(IMeetingDataProvider))
                    as IMeetingDataProvider;

                if (meetingData != null)
                {
                    if (!meetingData.Locations.Any(l => l.LocationName == location))
                    {
                        return new ValidationResult(
                            "That is not a valid location",
                            new[] { validationContext.MemberName });
                    }
                }
            }

            return ValidationResult.Success;
        }
開發者ID:jeffhandley,項目名稱:RIAServicesValidation,代碼行數:20,代碼來源:MeetingValidators.shared.cs

示例5: AdaptShouldReturnValidationContextAdapter

        public void AdaptShouldReturnValidationContextAdapter()
        {
            // arrange
            var instance = new object();
            var service = new object();
            var serviceProvider = new ServiceContainer();
            var items = new Dictionary<object, object>() { { "Test", "Test" } };
            var expected = new ValidationContext( instance, serviceProvider, items );

            expected.MemberName = "Foo";
            serviceProvider.AddService( typeof( object ), service );

            // act
            var actual = expected.Adapt();

            // assert
            Assert.Equal( expected.DisplayName, actual.DisplayName );
            Assert.Same( expected.Items["Test"], actual.Items["Test"] );
            Assert.Equal( expected.MemberName, actual.MemberName );
            Assert.Same( expected.ObjectInstance, actual.ObjectInstance );
            Assert.Equal( expected.ObjectType, actual.ObjectType );
            Assert.Same( expected.GetService( typeof( object ) ), actual.GetService( typeof( object ) ) );
        }
開發者ID:WaffleSquirrel,項目名稱:More,代碼行數:23,代碼來源:ValidationAdapterExtensionsTest.cs

示例6: IsValid

        /// <summary>
        /// 現在の検証屬性に対して、指定した値を検証します。
        /// </summary>
        /// <param name="value">検証対象の値。</param>
        /// <param name="validationContext">検証操作に関するコンテキスト情報。</param>
        /// <returns>
        ///   <see cref="T:System.ComponentModel.DataAnnotations.ValidationResult"/> クラスのインスタンス。
        /// </returns>
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            validator = validationContext.GetService(typeof(IPersonNameValidator)) as IPersonNameValidator;

            return base.IsValid(value, validationContext);
        }
開發者ID:miso-soup,項目名稱:CustomModelValidatorTry,代碼行數:14,代碼來源:TwitterUserNameAttribute.cs

示例7: ValidateViewModelName

        public static ValidationResult ValidateViewModelName( string value, ValidationContext context )
        {
            Arg.NotNull( context, nameof( context ) );

            var model = context.ObjectInstance as ViewItemTemplateWizardViewModel;

            if ( model == null )
                return new ValidationResult( SR.InvalidObjectForValidation.FormatDefault( typeof( ViewItemTemplateWizardViewModel ) ) );

            switch ( model.ViewModelOption )
            {
                case 1:
                    {
                        // must have the name of the new view model
                        if ( string.IsNullOrEmpty( value ) )
                            return new ValidationResult( SR.ViewModelNameUnspecified, new[] { "ViewModelName" } );

                        var validator = context.GetService<IProjectItemNameValidator>();

                        // the specified view model name must be unique
                        if ( validator != null && !validator.IsItemNameUnique( value ) )
                            return new ValidationResult( SR.ViewModelNameNonUnique.FormatDefault( value ), new[] { "ViewModelName" } );

                        break;
                    }
                case 2:
                    {
                        // must have a selected view model
                        if ( string.IsNullOrEmpty( value ) )
                            return new ValidationResult( SR.ExistingViewModelUnspecified, new[] { "ViewModelName" } );

                        break;
                    }
            }

            return ValidationResult.Success;
        }
開發者ID:WaffleSquirrel,項目名稱:More,代碼行數:37,代碼來源:ViewItemTemplateWizardViewModel.cs

示例8: PreventDoubleBooking

        public static ValidationResult PreventDoubleBooking(Meeting meeting, ValidationContext validationContext)
        {
            if (validationContext.Items.ContainsKey("AllowOverBooking"))
            {
                bool allowOverBooking = (bool)validationContext.Items["AllowOverBooking"];

                if (!allowOverBooking)
                {
                    var meetingData = validationContext.GetService(typeof(IMeetingDataProvider))
                        as IMeetingDataProvider;

                    if (meetingData != null)
                    {
                        var conflicts = from other in meetingData.Meetings.Except(new[] { meeting })
                                        where other.Location == meeting.Location
                                        // Check for conflicts by seeing if the times overlap in any way
                                        && (
                                            (other.Start >= meeting.Start && other.Start <= meeting.End) ||
                                            (meeting.Start >= other.Start && meeting.Start <= other.End) ||
                                            (other.End >= meeting.Start && other.End <= meeting.End) ||
                                            (meeting.End >= other.Start && meeting.End <= other.End)
                                            )
                                        select other;

                        if (conflicts.Any())
                        {
                            return new ValidationResult(
                                "The location selected is already booked at this time.",
                                new[] { "Location", "Start", "End" });
                        }
                    }
                }
            }

            return ValidationResult.Success;
        }
開發者ID:jeffhandley,項目名稱:RIAServicesValidation,代碼行數:36,代碼來源:MeetingValidators.shared.cs


注:本文中的System.ComponentModel.DataAnnotations.ValidationContext.GetService方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。