示例#1
0
        public void CompletelyInvalidIntParameterModifier_ShouldLogExpectedErrors()
        {
            var obj = TestSyntaxFactory.CreateObject(new[]
            {
                // not a bool
                TestSyntaxFactory.CreateProperty("secure", TestSyntaxFactory.CreateInt(1)),

                // default value of wrong type
                TestSyntaxFactory.CreateProperty("default", TestSyntaxFactory.CreateBool(true)),

                // not an array
                TestSyntaxFactory.CreateProperty("allowed", TestSyntaxFactory.CreateObject(new ObjectPropertySyntax[0])),

                // not ints
                TestSyntaxFactory.CreateProperty("minValue", TestSyntaxFactory.CreateBool(true)),
                TestSyntaxFactory.CreateProperty("maxValue", TestSyntaxFactory.CreateString("11")),
                TestSyntaxFactory.CreateProperty("minLength", TestSyntaxFactory.CreateObject(new ObjectPropertySyntax[0])),
                TestSyntaxFactory.CreateProperty("maxLength", TestSyntaxFactory.CreateBool(false)),

                // extra property
                TestSyntaxFactory.CreateProperty("extra", TestSyntaxFactory.CreateBool(false)),

                TestSyntaxFactory.CreateProperty("metadata", TestSyntaxFactory.CreateObject(new[]
                {
                    // wrong type of description
                    TestSyntaxFactory.CreateProperty("description", TestSyntaxFactory.CreateInt(155))
                }))
            });

            TypeValidator.GetExpressionAssignmentDiagnostics(CreateTypeManager(), obj, LanguageConstants.CreateParameterModifierType(LanguageConstants.Int, LanguageConstants.Int))
            .Select(d => d.Message)
            .Should().BeEquivalentTo(
                "The property 'allowed' expected a value of type int[] but the provided value is of type object.",
                "The property 'minValue' expected a value of type int but the provided value is of type bool.",
                "The property 'default' expected a value of type int but the provided value is of type bool.",
                "The property 'maxValue' expected a value of type int but the provided value is of type '11'.",
                "The property 'description' expected a value of type string but the provided value is of type int.",
                "The property 'secure' is not allowed on objects of type ParameterModifier<int>.",
                "The property 'minLength' is not allowed on objects of type ParameterModifier<int>.",
                "The property 'maxLength' is not allowed on objects of type ParameterModifier<int>.",
                "The property 'extra' is not allowed on objects of type ParameterModifier<int>.");
        }
示例#2
0
 protected override object GetItemChildAtIndex(object aNode, int aIndex)
 {
     if (TypeValidator.IsCompatible(aNode.GetType(), typeof(DevelopmentDescriptionCollection)) == true)
     {
         if ((aIndex < 0) || (aIndex >= (aNode as DevelopmentDescriptionCollection).Count))
         {
             return(null);
         }
         return((aNode as DevelopmentDescriptionCollection)[aIndex]);
     }
     else if (TypeValidator.IsCompatible(aNode.GetType(), typeof(DevelopmentInformationAttribute)) == true)
     {
         if ((aIndex < 0) || (aIndex >= (aNode as DevelopmentInformationAttribute).Count))
         {
             return(null);
         }
         return((aNode as DevelopmentInformationAttribute)[aIndex]);
     }
     return(null);
 }
 public static StateType ResolveState(this IDrawingCell aCell)
 {
     if (aCell.MasterIsSensitive() == false)
     {
         return(StateType.Insensitive);
     }
     if (TypeValidator.IsCompatible(aCell.GetType(), typeof(IGtkState)) == true)
     {
         return((aCell as IGtkState).State);
     }
     if (TypeValidator.IsCompatible(aCell.Owner.GetType(), typeof(IDrawingCell)) == true)
     {
         return((aCell.Owner as IDrawingCell).ResolveState());
     }
     if (TypeValidator.IsCompatible(aCell.Owner.GetType(), typeof(Gtk.Widget)) == true)
     {
         return((aCell.Owner as Gtk.Widget).State);
     }
     return(StateType.Normal);
 }
 public BaseGenericClientObservableListView(IList <T> aParentView)
 {
     if (aParentView == null)
     {
         throw new NullReferenceException("Parent view can't be null");
     }
     parentView = aParentView;
     if (TypeValidator.IsCompatible(parentView.GetType(), typeof(IListEvents)) == true)
     {
         myAddedMethod       = new ElementAddedInListObjectEvent(ElementAddedIntoMaster);
         myChangedMethod     = new ElementChangedInListObjectEvent(ElementChangedInMaster);
         myListChangedMethod = new ListChangedEvent(MasterListChanged);
         myRemovedMethod     = new ElementRemovedFromListObjectEvent(ElementRemovedFromMaster);
         mySortedMethod      = new ElementsInListSortedEvent(ElementsSortedInMaster);
         (parentView as IListEvents).ElementAdded   += myAddedMethod;
         (parentView as IListEvents).ElementChanged += myChangedMethod;
         (parentView as IListEvents).ElementRemoved += myRemovedMethod;
         (parentView as IListEvents).ElementsSorted += mySortedMethod;
         (parentView as IListEvents).ListChanged    += myListChangedMethod;
     }
 }
示例#5
0
        public override IEnumerable <ErrorDiagnostic> GetDiagnostics()
        {
            var diagnostics = this.ValidateIdentifierAccess();

            switch (this.Modifier)
            {
            case ParameterDefaultValueSyntax defaultValueSyntax:
                diagnostics = diagnostics.Concat(ValidateDefaultValue(defaultValueSyntax));
                break;

            case ObjectSyntax modifierSyntax:
                if (this.Type.TypeKind != TypeKind.Error && this.TryGetPrimitiveType() is TypeSymbol primitiveType)
                {
                    var modifierType = LanguageConstants.CreateParameterModifierType(primitiveType, this.Type);
                    diagnostics = diagnostics.Concat(TypeValidator.GetExpressionAssignmentDiagnostics(this.Context.TypeManager, modifierSyntax, modifierType));
                }
                break;
            }

            return(diagnostics);
        }
示例#6
0
        public void ValidBoolParameterModifierShouldProduceNoDiagnostics()
        {
            var obj = TestSyntaxFactory.CreateObject(new[]
            {
                TestSyntaxFactory.CreateProperty("default", TestSyntaxFactory.CreateBool(true)),

                TestSyntaxFactory.CreateProperty("allowed", TestSyntaxFactory.CreateArray(new []
                {
                    TestSyntaxFactory.CreateArrayItem(TestSyntaxFactory.CreateBool(false))
                })),

                TestSyntaxFactory.CreateProperty("metadata", TestSyntaxFactory.CreateObject(new[]
                {
                    TestSyntaxFactory.CreateProperty("description", TestSyntaxFactory.CreateString("my description")),
                    TestSyntaxFactory.CreateProperty("extra1", TestSyntaxFactory.CreateString("extra")),
                    TestSyntaxFactory.CreateProperty("extra2", TestSyntaxFactory.CreateBool(true)),
                    TestSyntaxFactory.CreateProperty("extra3", TestSyntaxFactory.CreateInt(100))
                }))
            });

            TypeValidator.GetExpressionAssignmentDiagnostics(CreateTypeManager(), obj, LanguageConstants.CreateParameterModifierType(LanguageConstants.Bool)).Should().BeEmpty();
        }
 public static void SetGtkState(this IDrawingCell aCell, StateType aState)
 {
     if (TypeValidator.IsCompatible(aCell.GetType(), typeof(ICustomGtkState)) == true)
     {
         if ((aCell as ICustomGtkState).StateResolving == ValueResolveMethod.Manual)
         {
             (aCell as ICustomGtkState).CustomState = aState;
         }
         else
         {
             return;
         }
         return;
     }
     if (aCell.Owner != null)
     {
         if (TypeValidator.IsCompatible(aCell.Owner.GetType(), typeof(IDrawingCell)) == true)
         {
             (aCell.Owner as IDrawingCell).SetGtkState(aState);
         }
     }
 }
示例#8
0
        /// <summary>
        /// Handles ButtonPress event
        /// </summary>
        /// <param name="evnt">
        /// Arguments <see cref="Gdk.EventButton"/>
        /// </param>
        /// <returns>
        /// true if handled, false if not <see cref="System.Boolean"/>
        /// </returns>
        protected override bool OnButtonPressEvent(Gdk.EventButton evnt)
        {
            if (HasFocus == false)
            {
                return(base.OnButtonPressEvent(evnt));
            }
            IDrawingCell cell = mainbox.CellAtCoordinates(System.Convert.ToInt32(evnt.X), System.Convert.ToInt32(evnt.Y));

            if (cell == null)
            {
                return(base.OnButtonPressEvent(evnt));
            }
            if (TypeValidator.IsCompatible(cell.GetType(), typeof(DateText)) == true)
            {
                if ((int)(cell as DateText).Part < 3)
                {
                    Selected = (cell as DateText).Part;
                    return(true);
                }
            }
            return(base.OnButtonPressEvent(evnt));
        }
        private static IServiceCollection AddBaseGraphQLClientServices(
            this IServiceCollection services,
            string schema,
            IEnumerable <string> modelNamespaces = null)
        {
            services.AddTransient <IFieldValidator, FieldValidator>();
            services.AddTransient <ISchemaValidator, SchemaValidator>();

            var typeValidator = new TypeValidator(modelNamespaces ?? new List <string>());

            services.AddSingleton <ITypeValidator>(typeValidator);

            services.AddTransient <IRequestBuilder, RequestBuilder>();
            services.AddTransient <IResultBuilder, ResultBuilder>();

            var schemaPrivider = new PartialSchemaProvider();

            schemaPrivider.WithSchema(schema);
            services.AddSingleton <IPartialSchemaProvider>(schemaPrivider);

            return(services);
        }
示例#10
0
        public void UnionShouldBeAssignableToTypeIfAllMembersAre()
        {
            var boolIntUnion = UnionType.Create(LanguageConstants.Bool, LanguageConstants.Int);
            var stringUnion  = UnionType.Create(LanguageConstants.String);

            TypeValidator.AreTypesAssignable(stringUnion, LanguageConstants.String).Should().BeTrue();
            TypeValidator.AreTypesAssignable(stringUnion, LanguageConstants.Bool).Should().BeFalse();
            TypeValidator.AreTypesAssignable(stringUnion, boolIntUnion).Should().BeFalse();

            var logLevelsUnion        = UnionType.Create(new StringLiteralType("Error"), new StringLiteralType("Warning"), new StringLiteralType("Info"));
            var failureLogLevelsUnion = UnionType.Create(new StringLiteralType("Error"), new StringLiteralType("Warning"));

            TypeValidator.AreTypesAssignable(logLevelsUnion, LanguageConstants.String).Should().BeTrue();
            TypeValidator.AreTypesAssignable(logLevelsUnion, stringUnion).Should().BeTrue();
            TypeValidator.AreTypesAssignable(logLevelsUnion, boolIntUnion).Should().BeFalse();

            // Source union is a subset of target union - this should be allowed
            TypeValidator.AreTypesAssignable(failureLogLevelsUnion, logLevelsUnion).Should().BeTrue();

            // Source union is a strict superset of target union - this should not be allowed
            TypeValidator.AreTypesAssignable(logLevelsUnion, failureLogLevelsUnion).Should().BeFalse();
        }
示例#11
0
        private TypeDesc SimpleExpression(HashSet <SymbolEnum> followers)
        {
            bool hasPrefixSign = false;

            if (CurrentSymbol == SymbolEnum.Minus || CurrentSymbol == SymbolEnum.Plus)
            {
                hasPrefixSign = true;
                NextSymbol();
            }

            var firstOperandType = NeutralizerDecoratorWithReturn(Term, Starters.Term, Followers.Term, 6, followers);

            if (hasPrefixSign)
            {
                if (!TypeValidator.SupportsSign(firstOperandType))
                {
                    Error(211);
                }
            }

            while (CurrentSymbol == SymbolEnum.Plus ||
                   CurrentSymbol == SymbolEnum.Minus ||
                   CurrentSymbol == SymbolEnum.OrSy)
            {
                var operation = CurrentSymbol;
                NextSymbol();
                var secondOperandType = NeutralizerDecoratorWithReturn(Term, Starters.Term, Followers.Term, 6, followers);
                var expressionType    = TypeValidator.GetTypeAfterAddition(firstOperandType, secondOperandType, operation);
                if (expressionType == null)
                {
                    Error(328);
                }

                return(expressionType);
            }

            return(firstOperandType);
        }
示例#12
0
        // Слагаемое
        private TypeDesc Term(HashSet <SymbolEnum> followers)
        {
            var firstOperandType = NeutralizerDecoratorWithReturn(Factor, Starters.Factor, Followers.Factor, 6, followers);

            while (CurrentSymbol == SymbolEnum.Star ||
                   CurrentSymbol == SymbolEnum.Slash ||
                   CurrentSymbol == SymbolEnum.DivSy ||
                   CurrentSymbol == SymbolEnum.ModSy ||
                   CurrentSymbol == SymbolEnum.AndSy)
            {
                var operation = CurrentSymbol;
                NextSymbol();
                var secondOperandType = NeutralizerDecoratorWithReturn(Factor, Starters.Factor, Followers.Factor, 6, followers);
                var expressionType    = TypeValidator.GetTypeAfterMultiplication(firstOperandType, secondOperandType, operation);
                if (expressionType == null)
                {
                    Error(328);
                }

                return(expressionType);
            }

            return(firstOperandType);
        }
示例#13
0
        public void InvalidArrayValuesShouldBeRejected()
        {
            var obj = TestSyntaxFactory.CreateObject(new[]
            {
                TestSyntaxFactory.CreateProperty("name", TestSyntaxFactory.CreateString("test")),

                // zones is an array of strings - set wrong item types
                TestSyntaxFactory.CreateProperty("zones", TestSyntaxFactory.CreateArray(new[]
                {
                    TestSyntaxFactory.CreateArrayItem(TestSyntaxFactory.CreateBool(true)),
                    TestSyntaxFactory.CreateArrayItem(TestSyntaxFactory.CreateInt(2))
                })),

                // this property is an array - specify a string instead
                TestSyntaxFactory.CreateProperty("managedByExtended", TestSyntaxFactory.CreateString("not an array"))
            });

            TypeValidator.GetExpressionAssignmentDiagnostics(CreateTypeManager(), obj, CreateDummyResourceType())
            .Select(d => d.Message)
            .Should().BeEquivalentTo(
                "The enclosing array expected an item of type string, but the provided item was of type bool.",
                "The property 'managedByExtended' expected a value of type string[] but the provided value is of type 'not an array'.",
                "The enclosing array expected an item of type string, but the provided item was of type int.");
        }
        //private Type validator;
        //public TypeValidationAttribute(Type propertyClassType) {

        //     if (propertyClassType == null)
        //    {
        //        throw new ArgumentNullException("propertyClassType");
        //    }
        //    if (!typeof (CoinValidatorBase).IsAssignableFrom(validator))
        //    {
        //        throw new ArgumentException("Validator Attribute param not validator");
        //    }
        //    type = propertyClassType;

        public override bool IsValid(object value)
        {
            PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(value);
            object originalValue = properties.Find("Attendee", true /* ignoreCase */).GetValue(value);

            // object confirmValue = properties.Find(ConfirmProperty, true /* ignoreCase */).GetValue(value);
            return(false);

            if (AcceptedTypes == null)
            {
                AcceptedTypes = new List <Type>();
            }
            if (AcceptedType1 != null)
            {
                AcceptedTypes.Add(AcceptedType1);
            }
            if (AcceptedType2 != null)
            {
                AcceptedTypes.Add(AcceptedType2);
            }
            var validator = new TypeValidator(AcceptedTypes);

            return(validator.IsValid(value.GetType()));
        }
示例#15
0
            public override void VisitFunctionCallSyntax(FunctionCallSyntax syntax)
            {
                // must have more than 1 argument to use interpolation
                if (syntax.NameEquals(concatFunction) &&
                    syntax.Arguments.Length > 1 &&
                    !syntax.GetParseDiagnostics().Any())
                {
                    // We should only suggest rewriting concat() calls that result in a string (concat can also operate on and
                    // return arrays)
                    var resultType = this.model.GetTypeInfo(syntax);
                    if (resultType is not AnyType && TypeValidator.AreTypesAssignable(resultType, LanguageConstants.String))
                    {
                        if (CreateFix(syntax) is CodeFix fix)
                        {
                            this.diagnostics.Add(parent.CreateFixableDiagnosticForSpan(syntax.Span, fix));

                            // Only report on the top-most string-valued concat call
                            return;
                        }
                    }
                }

                base.VisitFunctionCallSyntax(syntax);
            }
示例#16
0
        protected override SyntaxBase ReplaceStringSyntax(StringSyntax syntax)
        {
            var declaredType = semanticModel.GetDeclaredType(syntax);

            if (semanticModel.GetTypeInfo(syntax) is not StringLiteralType actualType)
            {
                return(base.ReplaceStringSyntax(syntax));
            }

            if (declaredType is null || TypeValidator.AreTypesAssignable(actualType, declaredType))
            {
                return(base.ReplaceStringSyntax(syntax));
            }

            var stringLiteralCandidates = Enumerable.Empty <StringLiteralType>();

            if (declaredType is StringLiteralType stringLiteralType)
            {
                stringLiteralCandidates = stringLiteralType.AsEnumerable();
            }
            else if (declaredType is UnionType unionType && unionType.Members.All(x => x.Type is StringLiteralType))
            {
                stringLiteralCandidates = unionType.Members.Select(x => (StringLiteralType)x.Type);
            }

            var insensitiveMatch = stringLiteralCandidates.FirstOrDefault(x => StringComparer.OrdinalIgnoreCase.Equals(x.Name, actualType.Name));

            if (insensitiveMatch == null)
            {
                return(base.ReplaceStringSyntax(syntax));
            }

            var stringToken = new Token(TokenType.StringComplete, new TextSpan(0, 0), insensitiveMatch.Name, Enumerable.Empty <SyntaxTrivia>(), Enumerable.Empty <SyntaxTrivia>());

            return(new StringSyntax(stringToken.AsEnumerable(), Enumerable.Empty <SyntaxBase>(), insensitiveMatch.RawStringValue.AsEnumerable()));
        }
示例#17
0
        public void Publics()
        {
            TokenValidationParameters validationParameters = new TokenValidationParameters();
            Type type = typeof(TokenValidationParameters);

            PropertyInfo[] properties = type.GetProperties();
            if (properties.Length != 43)
            {
                Assert.True(false, "Number of properties has changed from 43 to: " + properties.Length + ", adjust tests");
            }

            TokenValidationParameters actorValidationParameters = new TokenValidationParameters();
            SecurityKey issuerSigningKey  = KeyingMaterial.DefaultX509Key_2048_Public;
            SecurityKey issuerSigningKey2 = KeyingMaterial.RsaSecurityKey_2048;

            List <SecurityKey> issuerSigningKeys =
                new List <SecurityKey>
            {
                KeyingMaterial.DefaultX509Key_2048_Public,
                KeyingMaterial.RsaSecurityKey_2048
            };

            List <SecurityKey> issuerSigningKeysDup =
                new List <SecurityKey>
            {
                KeyingMaterial.DefaultX509Key_2048_Public,
                KeyingMaterial.RsaSecurityKey_2048
            };

            string        validAudience  = "ValidAudience";
            List <string> validAudiences = new List <string> {
                validAudience
            };
            string        validIssuer  = "ValidIssuer";
            List <string> validIssuers = new List <string> {
                validIssuer
            };

            var propertyBag =
                new Dictionary <string, Object>
            {
                { "CustomKey", "CustomValue" }
            };

            TypeValidator typeValidator = (typ, token, parameters) => "ActualType";

            AlgorithmValidator algorithmValidator = ValidationDelegates.AlgorithmValidatorBuilder(false);

            var validTypes = new List <string> {
                "ValidType1", "ValidType2", "ValidType3"
            };

            var validAlgorithms = new List <string> {
                "RSA2048", "RSA1024"
            };

            TokenValidationParameters validationParametersInline = new TokenValidationParameters()
            {
                AlgorithmValidator        = algorithmValidator,
                ActorValidationParameters = actorValidationParameters,
                AudienceValidator         = ValidationDelegates.AudienceValidatorReturnsTrue,
                IssuerSigningKey          = issuerSigningKey,
                IssuerSigningKeyResolver  = (token, securityToken, keyIdentifier, tvp) => { return(new List <SecurityKey> {
                        issuerSigningKey
                    }); },
                IssuerSigningKeys         = issuerSigningKeys,
                IssuerValidator           = ValidationDelegates.IssuerValidatorEcho,
                LifetimeValidator         = ValidationDelegates.LifetimeValidatorReturnsTrue,
                PropertyBag        = propertyBag,
                SignatureValidator = ValidationDelegates.SignatureValidatorReturnsJwtTokenAsIs,
                SaveSigninToken    = true,
                TypeValidator      = typeValidator,
                ValidAlgorithms    = validAlgorithms,
                ValidateAudience   = false,
                ValidateIssuer     = false,
                ValidAudience      = validAudience,
                ValidAudiences     = validAudiences,
                ValidIssuer        = validIssuer,
                ValidIssuers       = validIssuers,
                ValidTypes         = validTypes
            };

            Assert.True(object.ReferenceEquals(actorValidationParameters, validationParametersInline.ActorValidationParameters));
            Assert.True(object.ReferenceEquals(validationParametersInline.IssuerSigningKey, issuerSigningKey));
            Assert.True(object.ReferenceEquals(validationParametersInline.PropertyBag, propertyBag));
            Assert.True(validationParametersInline.SaveSigninToken);
            Assert.False(validationParametersInline.ValidateAudience);
            Assert.False(validationParametersInline.ValidateIssuer);
            Assert.True(object.ReferenceEquals(validationParametersInline.ValidAlgorithms, validAlgorithms));
            Assert.True(object.ReferenceEquals(validationParametersInline.AlgorithmValidator, algorithmValidator));
            Assert.True(object.ReferenceEquals(validationParametersInline.TypeValidator, typeValidator));
            Assert.True(object.ReferenceEquals(validationParametersInline.ValidAudience, validAudience));
            Assert.True(object.ReferenceEquals(validationParametersInline.ValidAudiences, validAudiences));
            Assert.True(object.ReferenceEquals(validationParametersInline.ValidIssuer, validIssuer));
            Assert.True(validationParametersInline.IgnoreTrailingSlashWhenValidatingAudience);

            TokenValidationParameters validationParametersSets = new TokenValidationParameters();

            validationParametersSets.AlgorithmValidator        = algorithmValidator;
            validationParametersSets.ActorValidationParameters = actorValidationParameters;
            validationParametersSets.AudienceValidator         = ValidationDelegates.AudienceValidatorReturnsTrue;
            validationParametersSets.IssuerSigningKey          = KeyingMaterial.DefaultX509Key_2048_Public;
            validationParametersSets.IssuerSigningKeyResolver  = (token, securityToken, keyIdentifier, tvp) => { return(new List <SecurityKey> {
                    issuerSigningKey2
                }); };
            validationParametersSets.IssuerSigningKeys         = issuerSigningKeysDup;
            validationParametersSets.IssuerValidator           = ValidationDelegates.IssuerValidatorEcho;
            validationParametersSets.LifetimeValidator         = ValidationDelegates.LifetimeValidatorReturnsTrue;
            validationParametersSets.PropertyBag        = propertyBag;
            validationParametersSets.SignatureValidator = ValidationDelegates.SignatureValidatorReturnsJwtTokenAsIs;
            validationParametersSets.SaveSigninToken    = true;
            validationParametersSets.TypeValidator      = typeValidator;
            validationParametersSets.ValidateAudience   = false;
            validationParametersSets.ValidateIssuer     = false;
            validationParametersSets.ValidAlgorithms    = validAlgorithms;
            validationParametersSets.ValidAudience      = validAudience;
            validationParametersSets.ValidAudiences     = validAudiences;
            validationParametersSets.ValidIssuer        = validIssuer;
            validationParametersSets.ValidIssuers       = validIssuers;
            validationParametersSets.ValidTypes         = validTypes;

            var compareContext = new CompareContext();

            IdentityComparer.AreEqual(validationParametersInline, validationParametersSets, compareContext);
            IdentityComparer.AreEqual(validationParametersInline.Clone() as TokenValidationParameters, validationParametersInline, compareContext);

            string id = Guid.NewGuid().ToString();
            DerivedTokenValidationParameters derivedValidationParameters       = new DerivedTokenValidationParameters(id, validationParametersInline);
            DerivedTokenValidationParameters derivedValidationParametersCloned = derivedValidationParameters.Clone() as DerivedTokenValidationParameters;

            IdentityComparer.AreEqual(derivedValidationParameters, derivedValidationParametersCloned, compareContext);
            IdentityComparer.AreEqual(derivedValidationParameters.InternalString, derivedValidationParametersCloned.InternalString, compareContext);

            TestUtilities.AssertFailIfErrors(compareContext);
        }
示例#18
0
        private bool IsValidBooking(BookingModel booking, Result result)
        {
            if (TypeValidator.Validate(booking) == FlowOptions.Failed)
            {
                result.AddMessageToList(BookingResource.NotValidBooking);
            }
            else
            {
                if (booking.StartDate >= booking.EndDate)
                {
                    result.AddMessageToList(BookingResource.DatesNotValid);
                }
                if (TypeValidator.Validate(booking.IdHotel) == FlowOptions.Failed)
                {
                    result.AddMessageToList(BookingResource.HotelRequired);
                }
                if (TypeValidator.Validate(booking.IdRoom) == FlowOptions.Failed)
                {
                    result.AddMessageToList(BookingResource.RoomRequired);
                }
                if (TypeValidator.Validate(booking.ApplicantName) == FlowOptions.Failed)
                {
                    result.AddMessageToList(BookingResource.ApplicantRequired);
                }
                if (TypeValidator.Validate(booking.Email) == FlowOptions.Failed)
                {
                    result.AddMessageToList(BookingResource.EmailRequired);
                }
                if (TypeValidator.Validate(booking.ContactName) == FlowOptions.Failed)
                {
                    result.AddMessageToList(BookingResource.ContactNameRequired);
                }
                if (TypeValidator.Validate(booking.ContactPhone) == FlowOptions.Failed)
                {
                    result.AddMessageToList(BookingResource.ContactPhoneRequired);
                }

                foreach (GuestModel guest in booking.Guests)
                {
                    if (TypeValidator.Validate(guest) == FlowOptions.Failed)
                    {
                        result.AddMessageToList(BookingResource.NotValidGuest);
                    }
                    else
                    {
                        if (TypeValidator.Validate(guest.Name) == FlowOptions.Failed)
                        {
                            result.AddMessageToList(BookingResource.GuestNameRequired);
                        }
                        if (TypeValidator.Validate(guest.LastName) == FlowOptions.Failed)
                        {
                            result.AddMessageToList(BookingResource.GuestLastNRequired);
                        }
                        if (TypeValidator.Validate(guest.BirtDate) == FlowOptions.Failed)
                        {
                            result.AddMessageToList(BookingResource.GuestBirtRequired);
                        }
                        if (TypeValidator.Validate(guest.Name) == FlowOptions.Failed)
                        {
                            result.AddMessageToList(BookingResource.GuestNameRequired);
                        }
                        if (TypeValidator.Validate(guest.LastName) == FlowOptions.Failed)
                        {
                            result.AddMessageToList(BookingResource.GuestLastNRequired);
                        }
                        if (TypeValidator.Validate(guest.BirtDate) == FlowOptions.Failed)
                        {
                            result.AddMessageToList(BookingResource.GuestBirtRequired);
                        }
                        if (TypeValidator.Validate(guest.Genre) == FlowOptions.Failed)
                        {
                            result.AddMessageToList(BookingResource.GuestGenreRequired);
                        }
                        if (TypeValidator.Validate(guest.Identification) == FlowOptions.Failed)
                        {
                            result.AddMessageToList(BookingResource.GuestIdRequired);
                        }
                        if (TypeValidator.Validate(guest.IdentificationType) == FlowOptions.Failed)
                        {
                            result.AddMessageToList(BookingResource.GuestIdTypeRequired);
                        }
                        if (TypeValidator.Validate(guest.Email) == FlowOptions.Failed)
                        {
                            result.AddMessageToList(BookingResource.GuesEmailRequired);
                        }
                        if (TypeValidator.Validate(guest.PhoneNumber) == FlowOptions.Failed)
                        {
                            result.AddMessageToList(BookingResource.GuestPhoneRequired);
                        }
                    }
                }
            }
            return((result.Messages.Count == 0) ? true : false);
        }
示例#19
0
        private bool CheckedMember(MemberExpression column)
        {
            var result = column != null && TypeValidator.IsValidat(column.Member.Name) == false;

            return(result);
        }
示例#20
0
        public override Expression Visit(Expression node)
        {
            if (node == null)
            {
                return(node);
            }

            var targetExpression
                = QueryModelVisitor.QueryCompilationContext.QuerySourceMapping
                  .GetExpression(_querySource);

            if (targetExpression.Type == typeof(ValueBuffer) &&
                !CheckedMember(node as MemberExpression))
            {
                return(node);
            }

            var result = base.Visit(node);

            if (result.NodeType == ExpressionType.Convert)
            {
                var convert  = result as UnaryExpression;
                var pas      = convert.Operand as MethodCallExpression;
                var parmeter = pas.Arguments.ToArray()[0] as ConstantExpression;
                if (parmeter.Type == typeof(int) && object.Equals(parmeter.Value, -999))
                {
                    parmeter = Expression.Constant(0);
                    var gentMethod = convertMethod.MakeGenericMethod(convert.Type, parmeter.Type);
                    pas = Expression.Call(gentMethod, parmeter);

                    result = Expression.Convert(pas, convert.Type);
                }
                return(result);
            }

            switch (node)
            {
            case MemberExpression column:
                if (TypeValidator.IsValidat(column.Member.Name) == false)
                {
                    var select = column.Expression as QuerySourceReferenceExpression;
                    var type   = select.ReferencedQuerySource.ItemType;
                    for (int i = 0; i < Projection.Count; i++)
                    {
                        var col = Projection[i] as ColumnExpression;
                        if (col.Name == column.Member.Name)
                        {
                            Projection.RemoveAt(i);
                        }
                    }
                }
                break;

            default:
                break;
            }

            //var column = node as MemberExpression;
            //if (column != null && TypeValidator.IsValidat(column.Member.Name) == false)
            //{
            //    var select = column.Expression as QuerySourceReferenceExpression;
            //    var type = select.ReferencedQuerySource.ItemType;
            //    for (int i = 0; i < Projection.Count; i++)
            //    {
            //        var col = Projection[i] as ColumnExpression;
            //        if (col.Name == column.Member.Name)
            //        {
            //            Projection.RemoveAt(i);
            //        }
            //    }
            //}

            return(result);
        }
 public static bool MasterIsGtkWidget(this IDrawingCell aCell)
 {
     return(TypeValidator.IsCompatible(aCell.Master.GetType(), typeof(Gtk.Widget)) == true);
 }
示例#22
0
        protected void AddValidation(string field, TypeValidator validator, string[] args = null)
        {
            switch (validator)
            {
            case TypeValidator.CampoObrigatorio:
                Details.Add(new ErrorDetail()
                {
                    message = string.Format("Campo {0}: obrigatório.", field)
                });
                break;

            case TypeValidator.CampoTamanho:
                Details.Add(new ErrorDetail()
                {
                    message = string.Format("Campo {0}: tamanho máximo: {1} caracteres.", field, args[0])
                });
                break;

            case TypeValidator.CampoTamanhoIntervalo:
                Details.Add(new ErrorDetail()
                {
                    message = string.Format("Campo {0}: valor inválido (mínimo: {1}, máximo: {2}).", field, args[0], args[1])
                });
                break;

            case TypeValidator.CampoTamanhoUnico:
                Details.Add(new ErrorDetail()
                {
                    message = string.Format("Campo {0}: tamanho obrigatório de {1} caracteres.", field, args[0])
                });
                break;

            case TypeValidator.CampoValorInvalido:
                Details.Add(new ErrorDetail()
                {
                    message = string.Format("Campo {0}: valor inválido.", field)
                });
                break;

            case TypeValidator.CampoNaoExisteBanco:
                Details.Add(new ErrorDetail()
                {
                    message = string.Format("O campo {0} não tem valor relacionado na tabela {1}", field, args[0])
                });
                break;

            case TypeValidator.CampoDuplicado:
                Details.Add(new ErrorDetail()
                {
                    message = string.Format("Já existe um {0} com o valor informado.", field)
                });
                break;

            case TypeValidator.None:
                Details.Add(new ErrorDetail()
                {
                    message = args[0]
                });
                break;
            }
        }
示例#23
0
 public void TestInit()
 {
     this.mockReflectHelper = new Mock <ReflectHelper>();
     this.typeValidator     = new TypeValidator(this.mockReflectHelper.Object);
     this.warnings          = new List <string>();
 }
示例#24
0
        public void DiscriminatedObjectType_raises_appropriate_diagnostics_for_matches()
        {
            var discriminatedType = new DiscriminatedObjectType(
                "discObj",
                "myDiscriminator",
                new []
            {
                new NamedObjectType("typeA", new []
                {
                    new TypeProperty("myDiscriminator", new StringLiteralType("valA")),
                    new TypeProperty("fieldA", LanguageConstants.Any, TypePropertyFlags.Required),
                }, null),
                new NamedObjectType("typeB", new []
                {
                    new TypeProperty("myDiscriminator", new StringLiteralType("valB")),
                    new TypeProperty("fieldB", LanguageConstants.Any, TypePropertyFlags.Required),
                }, null),
            });

            // no discriminator field supplied
            var obj = TestSyntaxFactory.CreateObject(new []
            {
                TestSyntaxFactory.CreateProperty("fieldA", TestSyntaxFactory.CreateString("someVal")),
            });

            var errors = TypeValidator.GetExpressionAssignmentDiagnostics(CreateTypeManager(), obj, discriminatedType);

            errors.Should().SatisfyRespectively(
                x => {
                x.Message.Should().Be("The property 'myDiscriminator' requires a value of type 'valA' | 'valB', but none was supplied.");
            });

            // incorrect type specified for the discriminator field
            obj = TestSyntaxFactory.CreateObject(new []
            {
                TestSyntaxFactory.CreateProperty("myDiscriminator", TestSyntaxFactory.CreateObject(Enumerable.Empty <ObjectPropertySyntax>())),
                TestSyntaxFactory.CreateProperty("fieldB", TestSyntaxFactory.CreateString("someVal")),
            });

            errors = TypeValidator.GetExpressionAssignmentDiagnostics(CreateTypeManager(), obj, discriminatedType);
            errors.Should().SatisfyRespectively(
                x => {
                x.Message.Should().Be("The property 'myDiscriminator' expected a value of type 'valA' | 'valB' but the provided value is of type object.");
            });

            // discriminator value that matches neither option supplied
            obj = TestSyntaxFactory.CreateObject(new []
            {
                TestSyntaxFactory.CreateProperty("myDiscriminator", TestSyntaxFactory.CreateString("valC")),
            });

            errors = TypeValidator.GetExpressionAssignmentDiagnostics(CreateTypeManager(), obj, discriminatedType);
            errors.Should().SatisfyRespectively(
                x => {
                x.Message.Should().Be("The property 'myDiscriminator' expected a value of type 'valA' | 'valB' but the provided value is of type 'valC'.");
            });

            // missing required property for the 'valB' branch
            obj = TestSyntaxFactory.CreateObject(new []
            {
                TestSyntaxFactory.CreateProperty("myDiscriminator", TestSyntaxFactory.CreateString("valB")),
            });

            errors = TypeValidator.GetExpressionAssignmentDiagnostics(CreateTypeManager(), obj, discriminatedType);
            errors.Should().SatisfyRespectively(
                x => {
                x.Message.Should().Be("The specified object is missing the following required properties: fieldB.");
            });

            // supplied the required property for the 'valB' branch
            obj = TestSyntaxFactory.CreateObject(new []
            {
                TestSyntaxFactory.CreateProperty("myDiscriminator", TestSyntaxFactory.CreateString("valB")),
                TestSyntaxFactory.CreateProperty("fieldB", TestSyntaxFactory.CreateString("someVal")),
            });

            errors = TypeValidator.GetExpressionAssignmentDiagnostics(CreateTypeManager(), obj, discriminatedType);
            errors.Should().BeEmpty();
        }
示例#25
0
 public void NonLiteralExpression_IsLiteralExpression_ShouldReturnViolations(string displayName, SyntaxBase expression)
 {
     TypeValidator.GetCompileTimeConstantViolation(expression).Should().NotBeEmpty();
 }
示例#26
0
 public void NonExpressionShouldProduceNoViolations(string displayName, SyntaxBase expression)
 {
     TypeValidator.GetCompileTimeConstantViolation(expression).Should().BeEmpty();
 }
示例#27
0
        public void EmptyModifierIsValid()
        {
            var obj = TestSyntaxFactory.CreateObject(new ObjectPropertySyntax[0]);

            TypeValidator.GetExpressionAssignmentDiagnostics(CreateTypeManager(), obj, LanguageConstants.CreateParameterModifierType(LanguageConstants.Int)).Should().BeEmpty();
        }
示例#28
0
 public void VariousObjects_ShouldProduceNoDiagnosticsWhenAssignedToObjectType(string displayName, ObjectSyntax @object)
 {
     TypeValidator.GetExpressionAssignmentDiagnostics(CreateTypeManager(), @object, LanguageConstants.Object).Should().BeEmpty();
 }
示例#29
0
 public bool CanAttachTo(TypeSymbol targetType) => TypeValidator.AreTypesAssignable(targetType, attachableType);
示例#30
0
 public void AnyTypeShouldBeAssignableToAnyType()
 {
     TypeValidator.AreTypesAssignable(LanguageConstants.Any, LanguageConstants.Any).Should().BeTrue();
 }