internal override bool Validate(ValidationContext context)
        {
            BuiltinLanguageType globalVariableType = context.GetGlobalVariableType(GlobalIndex);

            if (0 == globalVariableType)
            {
                return(false);
            }
            if (IsGetter)
            {
                context.StackPush(globalVariableType);
                return(true);
            }
            BuiltinLanguageType poppedType = context.StackPop();

            if (0 == poppedType)
            {
                context.AddError("Attempt to pop an empty stack.");
            }
            if (globalVariableType != poppedType)
            {
                context.AddError(string.Format("Attempt to set a {0} global variable with a {1} value.",
                                               globalVariableType, poppedType));
                return(false);
            }
            return(true);
        }
Exemplo n.º 2
0
        public void Validate(Type type, ValidationContext context)
        {
            if (!type.IsEnum)
            {
                var typeName = context.GetTypeName(type);
                context.AddError($"type mismatch, expected enum but found {typeName}");
                return;
            }

            var actualIsFlagsEnum = type.GetCustomAttributes(typeof(FlagsAttribute), false).Any();

            if (actualIsFlagsEnum != _expectedIsFlagsEnum)
            {
                var expectedKind = _expectedIsFlagsEnum ? "flags" : "values";
                var actualKind   = actualIsFlagsEnum ? "flags" : "values";

                context.AddError($"enum kind mismatch, expected {expectedKind} but found {actualKind}");
            }

            var underlyingType = System.Enum.GetUnderlyingType(type);
            var actualValues   = System.Enum.GetValues(type).Cast <object>().Select(x => Convert.ChangeType(x, underlyingType).ToString()).ToList();

            if (actualValues.Except(_expectedValues).Concat(_expectedValues.Except(actualValues)).Any())
            {
                var expectedValuesString = string.Join(",", _expectedValues);
                var actualValuesString   = string.Join(",", actualValues);
                context.AddError($"enum values mismatch, expected [{expectedValuesString}] but found [{actualValuesString}]");
            }
        }
Exemplo n.º 3
0
        internal override bool Validate(ValidationContext context)
        {
            BuiltinLanguageType expectedType = context.FunctionReturnType;

            if (BuiltinLanguageType.EmptyBlock != expectedType)
            {
                BuiltinLanguageType effectiveType = context.StackPeek(0);
                if (0 == effectiveType)
                {
                    return(false);
                }
                if (effectiveType != expectedType)
                {
                    context.AddError(string.Format(
                                         "Expected function return type is {0}. Returned value is {1}.",
                                         expectedType, effectiveType));
                    return(false);
                }
                BuiltinLanguageType poppedType = context.StackPop();
                if (0 == poppedType)
                {
                    return(false);
                }
            }
            int stackSize = context.StackSize;

            if (0 != stackSize)
            {
                context.AddError(string.Format(
                                     "{0} items remaining on stack on function return.",
                                     stackSize));
                return(false);
            }
            return(true);
        }
Exemplo n.º 4
0
        internal override bool Validate(ValidationContext context)
        {
            BuiltinLanguageType poppedType = context.StackPop();

            if (0 == poppedType)
            {
                return(false);
            }
            if (BuiltinLanguageType.I32 != poppedType)
            {
                context.AddError(string.Format(
                                     "Expected an I32 index on the stack. Found an {0}.",
                                     poppedType));
                return(false);
            }
            poppedType = context.StackPop();
            if (0 == poppedType)
            {
                return(false);
            }
            BuiltinLanguageType otherArgument = context.StackPeek(0);

            if (0 == otherArgument)
            {
                return(false);
            }
            if (otherArgument != poppedType)
            {
                context.AddError(string.Format(
                                     "Unconsistent select instruction parameters. Found an {0} and an {1}.",
                                     poppedType, otherArgument));
                return(false);
            }
            return(true);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Validate attributes on AlternateContent, Choice and Fallback element.
        /// </summary>
        /// <param name="validationContext"></param>
        /// <param name="acElement">The element to be validated.</param>
        private static void ValidateMcAttributesOnAcb(ValidationContext validationContext, OpenXmlElement acElement)
        {
            ValidationErrorInfo errorInfo;

            // AlternateContent elements might include the attributes Ignorable, MustUnderstand, ProcessContent, PreserveElements, and PreserveAttributes
            // These attributes’ qualified names shall be prefixed when associated with an AlternateContent / Choice / Fallback element.
            // A markup consumer shall generate an error if it encounters an unprefixed attribute name associated with an AlternateContent element.
            if (acElement.ExtendedAttributes != null)
            {
                foreach (var exAttribute in acElement.ExtendedAttributes)
                {
                    if (string.IsNullOrEmpty(exAttribute.Prefix))
                    {
                        // error on any unprefixed attributes
                        errorInfo = validationContext.ComposeMcValidationError(acElement, ValidationResources.MC_ErrorOnUnprefixedAttributeName, exAttribute.XmlQualifiedName.ToString());
                        validationContext.AddError(errorInfo);
                    }

                    // Markup consumers shall generate an error if they encounter the xml:lang or xml:space attributes on an AlternateContent element.
                    // Markup consumers shall generate an error if they encounter the xml:lang or xml:space attributes on a Choice element, regardless of whether the element is preceded by a selected Choice element.
                    // Markup consumers shall generate an error if they encounter the xml:lang or xml:space attributes on a Fallback element, regardless of whether the element is preceded by a selected Choice element.
                    if (IsXmlSpaceOrXmlLangAttribue(exAttribute))
                    {
                        // report error.
                        errorInfo = validationContext.ComposeMcValidationError(acElement, "MC_InvalidXmlAttribute", acElement.LocalName);
                        validationContext.AddError(errorInfo);
                    }
                }
            }

            // validate MC attribues (Ignorable, PreserveElements, etc.) of this element.
            CompatibilityRuleAttributesValidator.ValidateMcAttributes(validationContext);

            if (acElement is AlternateContentChoice choice)
            {
                // All Choice elements shall have a Requires attribute whose value contains a whitespace-delimited list of namespace prefixes
                if (choice.Requires == null)
                {
                    // report error
                    errorInfo = validationContext.ComposeMcValidationError(acElement, "MC_MissedRequiresAttribute");
                    validationContext.AddError(errorInfo);
                }
                else
                {
                    var prefixes = new ListValue <StringValue>();
                    prefixes.InnerText = choice.Requires;
                    foreach (var prefix in prefixes.Items)
                    {
                        var ignorableNamespace = choice.LookupNamespace(prefix);
                        if (string.IsNullOrEmpty(ignorableNamespace))
                        {
                            // report error, the prefix is not defined.
                            errorInfo = validationContext.ComposeMcValidationError(choice, "MC_InvalidRequiresAttribute", choice.Requires);
                            validationContext.AddError(errorInfo);
                        }
                    }
                }
            }
        }
Exemplo n.º 6
0
        public void Validate(ValidationContext context)
        {
            if (string.IsNullOrWhiteSpace(this.EmailAddress) || this.EmailAddress.IndexOf('@') < 1)
            {
                context.AddError(nameof(this.EmailAddress), "Invalid email address.");
            }

            if (string.IsNullOrWhiteSpace(this.Password) || this.Password.Length < 8)
            {
                context.AddError(nameof(this.Password), "The password must be at least 8 characters long.");
            }
        }
Exemplo n.º 7
0
        public void Validate(Type type, ValidationContext context)
        {
            var actualProperties = type.GetProperties();

            var expectedProperties = _dataContract is Type dataContractType
                ? dataContractType.GetProperties().ToDictionary(x => x.Name, x => (object)x.PropertyType)
                : _dataContract.GetType().GetProperties().ToDictionary(x => x.Name, x => x.GetValue(_dataContract, null));

            var names = actualProperties
                        .Select(x => x.Name)
                        .Concat(expectedProperties.Keys)
                        .OrderBy(x => x)
                        .Distinct();

            foreach (var name in names)
            {
                using (context.CreateScope(name))
                {
                    var actualProperty = actualProperties.FirstOrDefault(x => x.Name == name);

                    if (actualProperty == null)
                    {
                        context.AddError("expected property not found");
                        continue;
                    }

                    var actualPropertyIsIgnored = actualProperty.GetCustomAttributes(false)
                                                  .Any(x => x.GetType().Name == "JsonIgnoreAttribute");

                    if (!expectedProperties.TryGetValue(name, out var expectedProperty))
                    {
                        if (actualPropertyIsIgnored)
                        {
                            continue;
                        }

                        context.AddError("unexpected property");
                        continue;
                    }

                    if (actualPropertyIsIgnored)
                    {
                        context.AddError("expected property found but decorated with ignore attribute");
                        continue;
                    }

                    context.Validate(actualProperty.PropertyType, expectedProperty);
                }
            }
        }
Exemplo n.º 8
0
        internal override bool Validate(ValidationContext context)
        {
            BuiltinLanguageType variableType = context.GetLocalVariableType(LocalIndex);

            if (0 == variableType)
            {
                return(false);
            }
            BuiltinLanguageType topOfStackType;

            switch (OpCode)
            {
            case OpCodes.GetLocal:
                context.StackPush(variableType);
                return(true);

            case OpCodes.SetLocal:
                topOfStackType = context.StackPop();
                if (0 == topOfStackType)
                {
                    return(false);
                }
                if (topOfStackType != variableType)
                {
                    context.AddError(string.Format(
                                         "Local variable setter type mismatch. On stack {0], variable type is {1}.",
                                         topOfStackType, variableType));
                    return(false);
                }
                return(true);

            case OpCodes.TeeLocal:
                topOfStackType = context.StackPeek(0);
                if (0 == topOfStackType)
                {
                    return(false);
                }
                if (topOfStackType != variableType)
                {
                    context.AddError(string.Format(
                                         "Local variable tee type mismatch. On stack {0], variable type is {1}.",
                                         topOfStackType, variableType));
                    return(false);
                }
                return(true);

            default:
                throw new InvalidOperationException();
            }
        }
        public async Task <ValidationContext <UserLoginCommandResult> > Handle(RefreshTokenCommand request, CancellationToken cancellationToken)
        {
            _logger.LogDebug("Attempting to refresh users token");

            var resultContext = new ValidationContext <UserLoginCommandResult>();

            if (string.IsNullOrWhiteSpace(request.RefreshToken) || string.IsNullOrWhiteSpace(request.AccessToken))
            {
                resultContext
                .AddError("Invalid Token");
                _logger.LogDebug("RefreshToken or AccessToken was not specified when attempting to refresh a token");
                return(resultContext);
            }

            var principal   = _tokenService.GetPrincipalFromAccessToken(request.AccessToken);
            var userIdClaim = principal?.Claims?.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier);

            var user = await ValidateAndReturnUser(userIdClaim, resultContext);

            if (!IsUserRefreshTokenValid(user?.UserRefreshTokens, request.RefreshToken))
            {
                resultContext.AddError("Invalid Token");
                _logger.LogDebug("Refresh token has either expired or does not match the users current refresh token");
            }

            if (!resultContext.IsSuccessful)
            {
                return(resultContext);
            }

            _logger.LogDebug("Refresh token is valid, re-creating tokens for user.");

            var accessToken  = _tokenService.CreateToken(user);
            var refreshToken = _tokenService.CreateRefreshToken();

            // ReSharper disable once PossibleNullReferenceException
            user.UserRefreshTokens.Add(refreshToken);

            await _unitOfWork.CommitAsync();

            resultContext.Data = new UserLoginCommandResult
            {
                AccessToken  = accessToken,
                RefreshToken = refreshToken.Token
            };

            return(resultContext);
        }
        public async Task <ValidationContext <UserLoginCommandResult> > Handle(UserLoginCommand request, CancellationToken cancellationToken)
        {
            _logger.LogDebug("Attempting Plex SignIn");

            var result = new ValidationContext <UserLoginCommandResult>();

            PlexRequests.Plex.Models.User plexUser;
            try
            {
                plexUser = await _plexApi.SignIn(request.Username, request.Password);
            }
            catch (PlexRequestException)
            {
                result.AddError("Invalid Plex Credentials", "Unable to login to Plex with the given credentials");
                _logger.LogInformation("Unable to login to Plex with the given credentials");
                return(result);
            }

            _logger.LogDebug("Plex SignIn Successful");
            _logger.LogDebug("Getting PlexRequests User from PlexAccountId");

            var plexRequestsUser = await _userService.GetUserFromPlexId(plexUser.Id);

            if (plexRequestsUser == null || plexRequestsUser.IsDisabled)
            {
                result.AddError("Unrecognised user", "The user is not recognised or has been disabled.");
                _logger.LogInformation($"Successful login from a Plex account that was either not found within our users list or has been disabled [IsDisabled={plexRequestsUser?.IsDisabled}]");
                return(result);
            }

            _logger.LogDebug("Found matching PlexRequests User");

            var refreshToken = _tokenService.CreateRefreshToken();
            var accessToken  = _tokenService.CreateToken(plexRequestsUser);

            plexRequestsUser.LastLoginUtc = DateTime.UtcNow;
            plexRequestsUser.UserRefreshTokens.Add(refreshToken);

            await _unitOfWork.CommitAsync();

            result.Data = new UserLoginCommandResult
            {
                AccessToken  = accessToken,
                RefreshToken = refreshToken.Token
            };

            return(result);
        }
Exemplo n.º 11
0
 public override void Validate(ValidationContext context)
 {
     if (Resource == null)
     {
         context.AddError("Resource is null");
     }
 }
Exemplo n.º 12
0
        internal static bool AddMemberNameToHashSet(IEdmNamedElement item, HashSetInternal <string> memberNameList, ValidationContext context, EdmErrorCode errorCode, string errorString, bool suppressError)
        {
            string            name;
            IEdmSchemaElement edmSchemaElement = item as IEdmSchemaElement;

            if (edmSchemaElement != null)
            {
                name = edmSchemaElement.FullName();
            }
            else
            {
                name = item.Name;
            }
            string str = name;

            if (memberNameList.Add(str))
            {
                return(true);
            }
            else
            {
                if (!suppressError)
                {
                    context.AddError(item.Location(), errorCode, errorString);
                }
                return(false);
            }
        }
Exemplo n.º 13
0
        /// <summary>
        /// Validate the attributes constraint.
        /// </summary>
        /// <param name="validationContext">The validation context.</param>
        private static void ValidateAttributes(ValidationContext validationContext)
        {
            var element = validationContext.Stack.Current?.Element;

            if (element is null)
            {
                return;
            }

            foreach (var attribute in element.ParsedState.Attributes)
            {
                ValidateValue(validationContext, attribute.Property.Validators, attribute.Value, attribute.Property, true);
            }

            // all unknown attributes (attributes not defined in schema) are in ExtendedAttributes.
            // they should be errors
            foreach (var extendedAttribute in element.ExtendedAttributes)
            {
                if (validationContext.McContext.IsIgnorableNs(extendedAttribute.NamespaceUri))
                {
                    // Ignorable attribute, no error.
                }

                // xml:space is always allowed
                else if (extendedAttribute.NamespaceUri == "http://www.w3.org/XML/1998/namespace")
                {
                }
                else
                {
                    // emit error
                    validationContext.AddError(validationContext.ComposeSchemaValidationError(element, null, "Sch_UndeclaredAttribute", extendedAttribute.XmlQualifiedName.ToString()));
                }
            }
        }
Exemplo n.º 14
0
        /// <summary>
        /// Validate the attributes constraint.
        /// </summary>
        /// <param name="validationContext">The validation context.</param>
        private static void ValidateAttributes(ValidationContext validationContext)
        {
            var element = validationContext.Element;

            ValidationErrorInfo errorInfo;

            foreach (var attribute in element.Attributes)
            {
                ValidateValue(validationContext, attribute.Property.Validators, attribute.Value, attribute.Property.GetQName().ToString(), attribute.Property, true);
            }

            // all unknown attributes (attributes not defined in schema) are in ExtendedAttributes.
            // they should be errors
            foreach (var extendedAttribute in element.ExtendedAttributes)
            {
                if (validationContext.McContext.IsIgnorableNs(extendedAttribute.NamespaceUri))
                {
                    // Ignorable attribute, no error.
                }

                // xml:space is always allowed
                else if (extendedAttribute.NamespaceUri == "http://www.w3.org/XML/1998/namespace")
                {
                }
                else
                {
                    // emit error
                    string attributeQname = extendedAttribute.XmlQualifiedName.ToString();
                    errorInfo = validationContext.ComposeSchemaValidationError(element, null, "Sch_UndeclaredAttribute", attributeQname);
                    errorInfo.SetDebugField(attributeQname, "Sch_UndeclaredAttribute");
                    validationContext.AddError(errorInfo);
                }
            }
        }
Exemplo n.º 15
0
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            var timeout = this.GetTimeoutToken();

            var validationContext = new ValidationContext();
            model.Validate(validationContext);
            if (validationContext.HasErrors)
            {
                this.AddModelStateError(validationContext);
                return await this.View(model, timeout);
            }

            var account = new Account
            {
                IdentityType = IdentityType.EmailAddress,
                IdentityValue = model.EmailAddress.Trim().ToLowerInvariant(),
                CreationTime = Clock.UtcNow,
                Name = model.Name.Trim(),
                PasswordHash = BCrypt.Net.BCrypt.HashPassword(model.Password),
            };

            try
            {
                await this.accountStore.Insert(account, this.GetTimeoutToken());
                await this.CreateNewSession(account, false, timeout);
                return this.RedirectToAction("Index", "Home");
            }
            catch (DuplicateKeyException)
            {
                validationContext.AddError(nameof(model.EmailAddress), "This email address is already in use.");
                this.AddModelStateError(validationContext);
                return await this.View(model, timeout);
            }
        }
Exemplo n.º 16
0
        protected override void EmitInvalidElementError(ValidationContext validationContext, ParticleMatchInfo particleMatchInfo)
        {
            var element = validationContext.Stack.Current?.Element;

            if (element is null)
            {
                return;
            }

            var child = particleMatchInfo.LastMatchedElement is null
                ? validationContext.GetFirstChildMc()
                : validationContext.GetNextChildMc(particleMatchInfo.LastMatchedElement);

            if (child is null)
            {
                return;
            }

            string expectedChildren;
            ValidationErrorInfo errorInfo;

            switch (particleMatchInfo.Match)
            {
            case ParticleMatch.Nomatch:
                expectedChildren = GetExpectedChildrenMessage(element, GetExpectedElements());
                errorInfo        = validationContext.ComposeSchemaValidationError(element, child, "Sch_InvalidElementContentExpectingComplex", child.XmlQualifiedName.ToString(), expectedChildren);
                validationContext.AddError(errorInfo);
                break;

            case ParticleMatch.Partial:
            case ParticleMatch.Matched:
                if (_childrenParticles.ContainsKey(child.GetType()))
                {
                    // more than one occurs of a child.
                    errorInfo = validationContext.ComposeSchemaValidationError(element, child, "Sch_AllElement", child.XmlQualifiedName.ToString());
                    validationContext.AddError(errorInfo);
                }
                else
                {
                    expectedChildren = GetExpectedChildrenMessage(element, particleMatchInfo.ExpectedChildren);
                    errorInfo        = validationContext.ComposeSchemaValidationError(element, child, "Sch_InvalidElementContentExpectingComplex", child.XmlQualifiedName.ToString(), expectedChildren);
                    validationContext.AddError(errorInfo);
                }

                break;
            }
        }
 protected override Task Validate(ValidationContext validationContext)
 {
     if (string.Compare(Command.Name, "foo", StringComparison.OrdinalIgnoreCase) == 0)
     {
         validationContext.AddError("UserId", "Validation Failed");
     }
     return(Task.FromResult(0));
 }
Exemplo n.º 18
0
 protected override Task Validate(ValidationContext validationContext)
 {
     if (Command.Id == 999)
     {
         validationContext.AddError("UserId", "Validation Failed");
     }
     return(Task.FromResult(0));
 }
Exemplo n.º 19
0
        internal override bool Validate(ValidationContext context)
        {
            BuiltinLanguageType poppedType;

            if (Conditional)
            {
                poppedType = context.StackPop();
                if (0 == poppedType)
                {
                    return(false);
                }
                if (BuiltinLanguageType.I32 != poppedType)
                {
                    context.AddError(string.Format(
                                         "Expected an I32 for conditional branch evaluation. Found an {0}",
                                         poppedType.ToString()));
                    return(false);
                }
            }
            Tuple <BuiltinLanguageType, int, bool> label;

            if (!context.GetLabel(Depth, out label))
            {
                context.AddError(string.Format(
                                     "Attempt to retrieve label having relative index {0} while there is only {1} labels",
                                     Depth, context.LabelsCount));
                return(false);
            }
            if (BuiltinLanguageType.EmptyBlock != label.Item1)
            {
                poppedType = (Conditional) ? context.StackPeek(0) : context.StackPop();
                if (0 == poppedType)
                {
                    return(false);
                }
                if (label.Item1 != poppedType)
                {
                    context.AddError(string.Format(
                                         "Attempt to exit label having relative index {0} with value having type {1} on top of stack while expecting type {2}",
                                         Depth, poppedType.ToString(), label));
                    return(false);
                }
            }
            return(true);
        }
Exemplo n.º 20
0
 public override void Validate(ValidationContext context)
 {
     base.Validate(context);
     if (this.Element == DamageEnergyType.Fire || this.Element == DamageEnergyType.Cold || (this.Element == DamageEnergyType.Acid || this.Element == DamageEnergyType.Electricity))
     {
         return;
     }
     context.AddError("Only Fire, Cold, Acid or Electricity are allowed", (object[])Array.Empty <object>());
 }
Exemplo n.º 21
0
 internal override bool Validate(ValidationContext context)
 {
     if (0 == context.StackPop())
     {
         context.AddError("Drop instruction encountered while stack is empty.");
         return(false);
     }
     return(true);
 }
        /// <summary>
        /// Add further validation logic.
        /// </summary>
        protected override void OnValidate(ValidationContext <PerformanceReview> context)
        {
            if (!context.HasError(x => x.EmployeeId))
            {
                // Ensure that the EmployeeId has not be changed (change back) as it is immutable.
                if (ExecutionContext.Current.OperationType == OperationType.Update)
                {
                    var prm = (IPerformanceReviewManager)context.ServiceProvider.GetService(typeof(IPerformanceReviewManager));
                    var prv = prm.GetAsync(context.Value.Id).GetAwaiter().GetResult();
                    if (prv == null)
                    {
                        throw new NotFoundException();
                    }

                    if (context.Value.EmployeeId != prv.EmployeeId)
                    {
                        context.AddError(x => x.EmployeeId, ValidatorStrings.ImmutableFormat);
                        return;
                    }
                }

                // Check that the referenced Employee exists, and the review data is within the bounds of their employment.
                var em = (IEmployeeManager)context.ServiceProvider.GetService(typeof(IEmployeeManager));
                var ev = em.GetAsync(context.Value.EmployeeId).GetAwaiter().GetResult();
                if (ev == null)
                {
                    context.AddError(x => x.EmployeeId, ValidatorStrings.ExistsFormat);
                }
                else
                {
                    if (!context.HasError(x => x.Date))
                    {
                        if (context.Value.Date < ev.StartDate)
                        {
                            context.AddError(x => x.Date, "{0} must not be prior to the Employee starting.");
                        }
                        else if (ev.Termination != null && context.Value.Date > ev.Termination.Date)
                        {
                            context.AddError(x => x.Date, "{0} must not be after the Employee has terminated.");
                        }
                    }
                }
            }
        }
Exemplo n.º 23
0
        /// <summary>
        /// Add further validation logic.
        /// </summary>
        protected override async Task OnValidateAsync(ValidationContext <PerformanceReview> context)
        {
            if (!context.HasError(x => x.EmployeeId))
            {
                // Ensure that the EmployeeId has not be changed as it is immutable.
                if (ExecutionContext.Current.OperationType == OperationType.Update)
                {
                    var prv = await _performanceReviewManager.GetAsync(context.Value.Id).ConfigureAwait(false);

                    if (prv == null)
                    {
                        throw new NotFoundException();
                    }

                    if (context.Value.EmployeeId != prv.EmployeeId)
                    {
                        context.AddError(x => x.EmployeeId, ValidatorStrings.ImmutableFormat);
                        return;
                    }
                }

                // Check that the referenced Employee exists, and the review data is within the bounds of their employment.
                var ev = await _employeeManager.GetAsync(context.Value.EmployeeId).ConfigureAwait(false);

                if (ev == null)
                {
                    context.AddError(x => x.EmployeeId, ValidatorStrings.ExistsFormat);
                }
                else
                {
                    if (!context.HasError(x => x.Date))
                    {
                        if (context.Value.Date < ev.StartDate)
                        {
                            context.AddError(x => x.Date, "{0} must not be prior to the Employee starting.");
                        }
                        else if (ev.Termination != null && context.Value.Date > ev.Termination.Date)
                        {
                            context.AddError(x => x.Date, "{0} must not be after the Employee has terminated.");
                        }
                    }
                }
            }
        }
Exemplo n.º 24
0
 private void ValidateElement(ValidationContext context)
 {
     if (_curReg != null)
     {
         foreach (var error in _curReg.CheckConstraints(context))
         {
             context.AddError(error);
         }
     }
 }
Exemplo n.º 25
0
 internal override bool Validate(ValidationContext context)
 {
     for (int index = 0; index < 2; index++)
     {
         BuiltinLanguageType poppedType = context.StackPop();
         if (0 == poppedType)
         {
             context.AddError("Attempt to pop an empty stack.");
         }
         if (ArgumentsType != poppedType)
         {
             context.AddError(string.Format("Popped an {0} for a relational instruction on {1}.",
                                            poppedType, ArgumentsType));
             return(false);
         }
     }
     context.StackPush(BuiltinLanguageType.I32);
     return(true);
 }
        private async Task <UserRow> ValidateAndReturnUser(Claim userIdClaim, ValidationContext <UserLoginCommandResult> context)
        {
            if (userIdClaim?.Value == null)
            {
                context.AddError("Invalid Token");
                _logger.LogDebug("UserId could not be extracted from the claim");
                return(null);
            }

            var user = await _userService.GetUser(Guid.Parse(userIdClaim.Value));

            if (user != null && !user.IsDisabled)
            {
                return(user);
            }

            context.AddError("Invalid Token");
            _logger.LogDebug("User either no longer exists or has been disabled");
            return(null);
        }
Exemplo n.º 27
0
        public void Validate(Type type, ValidationContext context)
        {
            if (!type.TryGetInterfaceClosing(typeof(IEnumerable <>), out var @interface))
            {
                context.AddError($"type mismatch, expected enumerable but found {context.GetTypeName(type)}");
                return;
            }

            using (context.CreateScope("Item"))
                context.Validate(@interface.GetGenericArguments().Single(), _itemDataContract);
        }
Exemplo n.º 28
0
        internal override bool Validate(ValidationContext context)
        {
            Tuple <BuiltinLanguageType, int, bool> label;
            uint defaultLabel = Targets[Targets.Length - 1];

            if (!context.GetLabel(defaultLabel, out label))
            {
                context.AddError(string.Format("Table based branching as undefined default label {0}.", defaultLabel));
                return(false);
            }
            BuiltinLanguageType defaultType = label.Item1;

            foreach (uint target in Targets)
            {
                if (!context.GetLabel(target, out label))
                {
                    context.AddError(string.Format("Table based branching as undefined label {0}.", target.ToString()));
                    return(false);
                }
                if (label.Item1 != defaultType)
                {
                    context.AddError(string.Format("Unconsistent label {0} typing. Default type {1}, current type {2}.",
                                                   target.ToString(), defaultType.ToString(), label.Item1.ToString()));
                    return(false);
                }
            }
            BuiltinLanguageType poppedType = context.StackPop();

            if (0 == poppedType)
            {
                context.AddError("Table based branching found with empty stack.");
                return(false);
            }
            if (BuiltinLanguageType.I32 != poppedType)
            {
                context.AddError("Table based branching requires I32 argument.");
                return(false);
            }
            if (BuiltinLanguageType.EmptyBlock != defaultType)
            {
                poppedType = context.StackPop();
                if (0 == poppedType)
                {
                    context.AddError(string.Format("Table based branching found with missing {0} value on stack.",
                                                   defaultType.ToString()));
                    return(false);
                }
                if (defaultType != poppedType)
                {
                    context.AddError(string.Format("Table based branching expected an {0} value on stack. Found a {1}",
                                                   defaultType.ToString(), poppedType.ToString()));
                    return(false);
                }
            }
            return(true);
        }
Exemplo n.º 29
0
        public void Validate(Type type, ValidationContext context)
        {
            if (type == _type)
            {
                return;
            }

            var expected = context.GetTypeName(_type);
            var actual   = context.GetTypeName(type);

            context.AddError($"type mismatch, expected {expected} but found {actual}");
        }
Exemplo n.º 30
0
        public void Validate(Type type, ValidationContext context)
        {
            var actualType   = GetActualTypeString(type, context, out var enumType);
            var expectedType = GetExpectedTypeString();

            if (actualType != expectedType)
            {
                context.AddError($"type mismatch, expected {expectedType} but found {actualType}");
                return;
            }

            var underlyingType = System.Enum.GetUnderlyingType(enumType);
            var actualValues   = System.Enum.GetValues(enumType).Cast <object>().Select(x => Convert.ChangeType(x, underlyingType).ToString()).ToList();

            if (actualValues.Except(_expectedValues).Concat(_expectedValues.Except(actualValues)).Any())
            {
                var expectedValuesString = string.Join(",", _expectedValues);
                var actualValuesString   = string.Join(",", actualValues);
                context.AddError($"enum values mismatch, expected [{expectedValuesString}] but found [{actualValuesString}]");
            }
        }
Exemplo n.º 31
0
        public void Validate(Type type, ValidationContext context)
        {
            if (!type.TryGetInterfaceClosing(typeof(IDictionary <,>), out var @interface))
            {
                context.AddError($"type mismatch, expected dictionary but found {context.GetTypeName(type)}");
                return;
            }

            using (context.CreateScope("Key"))
                context.Validate(@interface.GetGenericArguments()[0], _keyDataContract);

            using (context.CreateScope("Value"))
                context.Validate(@interface.GetGenericArguments()[1], _valueDataContract);
        }
Exemplo n.º 32
0
            internal static void Validate(ValidationContext validationContext)
            {
                var element = (OpenXmlCompositeElement)validationContext.Element;
                ValidationErrorInfo errorInfo;

                foreach (var child in element.ChildElements)
                {
                    if (!(child is OpenXmlMiscNode))
                    {
                        errorInfo = validationContext.ComposeSchemaValidationError(element, null, "Sch_InvalidChildinLeafElement", element.XmlQualifiedName.ToString());
                        validationContext.AddError(errorInfo);
                        return; // just return one error is enough.
                    }
                }
            }
Exemplo n.º 33
0
        internal static bool AddMemberNameToHashSet(IEdmNamedElement item, HashSetInternal<string> memberNameList, ValidationContext context, EdmErrorCode errorCode, string errorString, bool suppressError)
        {
            IEdmSchemaElement schemaElement = item as IEdmSchemaElement;
            string name = (schemaElement != null) ? schemaElement.FullName() : item.Name;
            if (!memberNameList.Add(name))
            {
                if (!suppressError)
                {
                    context.AddError(item.Location(), errorCode, errorString);
                }

                return false;
            }

            return true;
        }
Exemplo n.º 34
0
        public async Task<ActionResult> Login(LoginViewModel model)
        {
            var timeout = this.GetTimeoutToken();

            var validationContext = new ValidationContext();
            model.Validate(validationContext);
            if (validationContext.HasErrors)
            {
                this.AddModelStateError(validationContext);
                return await this.View(model, timeout);
            }

            var account = new Account
            {
                IdentityType = IdentityType.EmailAddress,
                IdentityValue = model.EmailAddress.Trim().ToLowerInvariant(),
            };

            account = await this.accountStore.Get(account.PartitionKey, account.RowKey, timeout);
            if (account == null || BCrypt.Net.BCrypt.Verify(model.Password, account.PasswordHash) == false)
            {
                validationContext.AddError("Cannot find a matching account and password. Please try again!");
                this.AddModelStateError(validationContext);
                return await this.View(model, timeout);
            }

            await this.CreateNewSession(account, model.RememberMe, timeout);
            return this.RedirectToAction("Index", "Home");
        }