Esempio n. 1
0
 public ValidationHandler TempBuild(ValidationOptions options)
 {
     BuildMySelf();
     return(_parentRegistrar.TempBuild(options));
 }
Esempio n. 2
0
        /// <summary>
        /// Verify that the body of the actual response is consistent with the method definition and expected response parameters
        /// </summary>
        /// <param name="method">The MethodDefinition that generated the response.</param>
        /// <param name="actualResponse">The actual response from the service to validate.</param>
        /// <param name="expectedResponse">The prototype expected response from the service.</param>
        /// <param name="detectedErrors">A collection of errors that will be appended with any detected errors</param>
        private void VerifyResponseBody(HttpResponse actualResponse, HttpResponse expectedResponse, out ValidationError[] errors, ValidationOptions options = null)
        {
            List <ValidationError> detectedErrors = new List <ValidationError>();

            if (string.IsNullOrEmpty(actualResponse.Body) &&
                (expectedResponse != null && !string.IsNullOrEmpty(expectedResponse.Body)))
            {
                detectedErrors.Add(new ValidationError(ValidationErrorCode.HttpBodyExpected, null, "Body missing from response (expected response includes a body or a response type was provided)."));
            }
            else if (!string.IsNullOrEmpty(actualResponse.Body))
            {
                ValidationError[] schemaErrors;
                if (this.ExpectedResponseMetadata == null ||
                    (string.IsNullOrEmpty(this.ExpectedResponseMetadata.ResourceType) &&
                     (expectedResponse != null && !string.IsNullOrEmpty(expectedResponse.Body))))
                {
                    detectedErrors.Add(new ValidationError(ValidationErrorCode.ResponseResourceTypeMissing, null, "Expected a response, but resource type on method is missing: {0}", this.Identifier));
                }
                else
                {
                    var otherResources = this.SourceFile.Parent.ResourceCollection;
                    if (
                        !otherResources.ValidateResponseMatchesSchema(
                            this,
                            actualResponse,
                            expectedResponse,
                            out schemaErrors,
                            options))
                    {
                        detectedErrors.AddRange(schemaErrors);
                    }
                }

                var responseValidation = actualResponse.IsResponseValid(
                    this.SourceFile.DisplayName,
                    this.SourceFile.Parent.Requirements);
                detectedErrors.AddRange(responseValidation.Messages);
            }

            errors = detectedErrors.ToArray();
        }
Esempio n. 3
0
 private static bool IsOptionSet(ValidationOptions options, ValidationOptions flag)
 {
     return((options & flag) == flag);
 }
Esempio n. 4
0
        /// <inheritdoc/>
        public IList <JsonSchemaValidationResult> Validate(byte[] jsonBuffer, TextReader schemaReader)
        {
            if (jsonBuffer is null)
            {
                throw new ArgumentNullException(nameof(jsonBuffer));
            }

            if (schemaReader is null)
            {
                throw new ArgumentNullException(nameof(schemaReader));
            }

            var schema = JsonSchema.FromText(schemaReader.ReadToEnd());

            var jsonString = Encoding.UTF8.GetString(jsonBuffer);

            // Remove BOM characters from the string if present.
            var jsonStringWithoutBom = jsonString.Trim(new char[] { '\uFEFF', '\u200B' });

            // Use "Basic" output as that will only generate
            // two levels of validation results (Root and one level down)
            // see the API documentation for Json Everything for further details
            // https://gregsdennis.github.io/json-everything/api/Json.Schema.OutputFormat.html
            var validationOptions = new ValidationOptions()
            {
                OutputFormat = OutputFormat.Basic,
            };

            // Run validation ensuring that trailing commas are supported
            // as it appears trailing commas have been allowable in the
            // configuration files for some time.
            var validationResults = schema.Validate(
                JsonDocument.Parse(
                    jsonStringWithoutBom,
                    new JsonDocumentOptions()
            {
                AllowTrailingCommas = true,
            }
                    ).RootElement,
                validationOptions);

            var jsonSchemaValidationResultCollection = new List <JsonSchemaValidationResult>();

            // Copy and flatten validation result to generic json validation result objects
            // as we don't want to bleed JsonSchema.Net lib objects outside of this class.

            // Add the top level error message before iterating the nested errors to add to the collection.
            jsonSchemaValidationResultCollection.Add(
                new JsonSchemaValidationResult(
                    validationResults.IsValid,
                    validationResults.Message,
                    validationResults.SchemaLocation.ToString(),
                    validationResults.InstanceLocation.ToString()));

            // Iterate the nested errors and push them into the error collection
            jsonSchemaValidationResultCollection.AddRange(
                validationResults.NestedResults.Select(nr =>
                                                       new JsonSchemaValidationResult(
                                                           nr.IsValid,
                                                           nr.Message,
                                                           nr.SchemaLocation.ToString(),
                                                           nr.InstanceLocation.ToString())
                                                       ));

            return(jsonSchemaValidationResultCollection);
        }
Esempio n. 5
0
 public LengthShould16Validator(ValidationOptions options)
     : base("LengthShould16Validator")
 {
     _options = options ?? new ValidationOptions();
 }
Esempio n. 6
0
        /// <summary>
        /// Run data type and field length validation on a specific value.
        /// Certain types of validators obviate the need to specify a minimum or maximum length,
        /// like ValidationOptions.Email.
        /// <example>
        /// <code>
        /// using Mezzocode.Halide3;
        /// ...
        /// string result = h3Identify.Validate(
        ///		value,
        ///		h3Identify.ValidationOptions.Email,
        ///		0,
        ///		0,
        ///		false);
        /// </code>
        /// </example>
        /// <para>A common practice is to add error message fields underneath each of your form fields,
        /// and then use a single line to validate the input and display the error on the form, as well
        /// as set a global flag that identifies that there has been an error.</para>
        /// <example>
        /// <code>
        /// using Mezzocode.Halide3;
        /// ...
        /// errorFlag +=
        ///		EmailFieldErrorMessage.InnerHtml =
        ///			h3Identify.Validate(
        ///				EmailField.Value,
        ///				h3Identify.ValidationOptions.Email,
        ///				0,
        ///				0,
        ///				false);
        /// </code>
        /// </example>
        /// <para>In this way, you can check "errorFlag" to see if it's empty or null, in which case,
        /// there were no validation errors, otherwise, you know one or more validations failed.
        /// And in the same line, the error message for each field is filled with the error message,
        /// since ValidateItem() returns an empty string if the validation is successful, or a friendly
        /// error string if it fails.</para>
        /// </summary>
        /// <param name="value">Value to validate.</param>
        /// <param name="valType">Constant determining what type of validation.</param>
        /// <param name="minLength">Minimum length alowed.</param>
        /// <param name="maxLength">Maximum length allowed.</param>
        /// <param name="opt">Field is optional. Zero length validates, otherwise, full validation occurs.</param>
        /// <returns>Empty string if validation succeeds, error message on failure.</returns>
        public static String Validate(string value, ValidationOptions valType, int minLength, int maxLength, Boolean opt)
        {
            string retVal = "";

            if (opt && value.Length < 1) return retVal;

            // Evaluate length of value if minLength and maxLengths are non-zero
            if (minLength > 0 && maxLength > 0)
            {
                if (value.Length > maxLength)
                {
                    retVal += "Must be " + maxLength.ToString() + " character(s) long";
                }
                else
                {
                    if (value.Length < minLength)
                    {
                        retVal += "Must be " + minLength.ToString() + " character(s) or longer";
                    }
                }
            }

            // If no length errors, validate data is of a specific format
            if (retVal == "")
            {
                if (valType == ValidationOptions.State)
                {
                    bool flag = false;

                    for (int x = 0; x < StatesList.Length; x++)
                        if (value.ToLower() == StatesList[x].ToLower())
                            flag = true;

                    if (!flag)
                    {
                        retVal += "Not a State";
                    }
                }

                if (valType == ValidationOptions.Email)
                {
                    if (!IsEmail(value))
                    {
                        retVal += "Invalid e-mail address format";
                    }
                }

                if (valType == ValidationOptions.EmailList)
                {
                    // Invalid string
                    if (value.Length < 6)
                    {
                        retVal += "Invalid e-mail address format";
                    }
                    else
                    {
                        // Only one email address? If not, check for multiple.
                        if (!IsEmail(value))
                        {
                            string delim = "";

                            if (delim == "" && value.IndexOf(",") > 0) delim = ",";
                            if (delim == "" && value.IndexOf("|") > 0) delim = "|";
                            if (delim == "" && value.IndexOf(";") > 0) delim = ";";
                            if (delim == "" && value.IndexOf("/") > 0) delim = "/";
                            if (delim == "" && value.IndexOf(" ") > 0) delim = " ";

                            if (delim != "")
                            {
                                value = value.Replace(delim, ",");
                                value = value.Replace(" ", "");

                                while (value.IndexOf(",,") > 0) value = value.Replace(",,", ",");

                                string[] addresses = value.Split(',');

                                for (int x = 0; x < addresses.Length; x++)
                                {
                                    if (!IsEmail(addresses[x]))
                                    {
                                        retVal += "One or more e-mail addresses are invalid";
                                    }
                                }
                            }
                            else
                            {
                                retVal += "Must have one or more e-mail addresses";
                            }
                        }
                    }
                }

                if (valType == ValidationOptions.Number)
                {
                    if (!IsNumeric(value))
                    {
                        retVal += "Not a numeric value";
                    }
                }

                if (valType == ValidationOptions.PureNumber)
                {
                    if (!IsPureNumeric(value))
                    {
                        retVal += "Must only contain numbers";
                    }
                }

                if (valType == ValidationOptions.NonZero)
                {
                    if (!IsPureNumeric(value))
                    {
                        retVal += "Must only contain numbers";
                    }
                    else
                    {
                        if (Convert.ToInt32(value) <= 0)
                        {
                            retVal += "Must be greater than zero";
                        }
                    }
                }

                if (valType == ValidationOptions.Money)
                {
                    if (!IsCurrency(value))
                    {
                        retVal += "Not a currency value";
                    }
                }

                if (valType == ValidationOptions.Date)
                {
                    if (!IsDate(value))
                    {
                        retVal += "Not a date";
                    }
                }

                if (valType == ValidationOptions.Telephone)
                {
                    if (!HasPattern(REGEX_US_TELEPHONE, value))
                    {
                        retVal += "Not a telephone number";
                    }
                }

                if (valType == ValidationOptions.Telephone10)
                {
                    if (!HasPattern(REGEX_US_TELEPHONE_10, value))
                    {
                        retVal += "Not a telephone number with area code";
                    }
                }

                if (valType == ValidationOptions.CreditCard)
                {
                    if (!HasPattern(REGEX_CREDIT_CARD, value))
                    {
                        retVal += "Not a credit card number";
                    }
                }

                if (valType == ValidationOptions.ZipCode)
                {
                    if (!HasPattern(REGEX_US_ZIPCODE, value))
                    {
                        retVal += "Not a 5-digit zip code";
                    }
                }

                if (valType == ValidationOptions.Url)
                {
                    if (!HasPattern(REGEX_URL, value))
                    {
                        retVal += "Not a URL";
                    }
                }

                if (valType == ValidationOptions.IpAddress)
                {
                    if (!HasPattern(REGEX_IP_ADDRESS, value))
                    {
                        retVal += "Not an IP address";
                    }
                }

                if (valType == ValidationOptions.Ssn)
                {
                    if (!HasPattern(REGEX_SOCIAL_SECURITY, value))
                    {
                        retVal += "Not a social security number";
                    }
                }

                if (valType == ValidationOptions.Time)
                {
                    if (!HasPattern(REGEX_TIME, value) && !HasPattern(REGEX_TIME_24, value))
                    {
                        retVal += "Not a time of day";
                    }
                }

                if (valType == ValidationOptions.Domain)
                {
                    if (!HasPattern(REGEX_DOMAIN_NAME, value))
                    {
                        retVal += "Not a domain name";
                    }
                }

                if (valType == ValidationOptions.Name)
                {
                    if (!HasPattern(REGEX_NAME_COMMA_NAME, value))
                    {
                        retVal += "Not last name, first name";
                    }
                }
            }

            return retVal;
        }
 /// <summary>
 /// Constructs a new MarkupConstraint with the specified MarkupValidatorClient.
 /// </summary>
 /// <param name="options">flags to modify the behaviour of the validation constraint</param>
 /// <param name="client">the client to use</param>
 public MarkupConstraint(ValidationOptions options, MarkupValidatorClient client)
 {
     _options = options;
     _client = client;
 }
        private static async Task ValidateMethodWithScenarioAsync(
            MethodDefinition method,
            ScenarioDefinition scenario,
            IServiceAccount primaryAccount,
            IServiceAccount secondaryAccount,
            ValidationResults results,
            ValidationOptions options = null)
        {
            if (null == method)
            {
                throw new ArgumentNullException("method");
            }
            if (null == scenario)
            {
                throw new ArgumentNullException("scenario");
            }
            if (null == primaryAccount)
            {
                throw new ArgumentNullException("primaryAccount");
            }
            if (null == results)
            {
                throw new ArgumentNullException("results");
            }

            var actionName = scenario.Description;

            // Check to see if the account + scenario scopes are aligned

            string[] requiredScopes = method.RequiredScopes.Union(scenario.RequiredScopes).ToArray();

            if (!primaryAccount.Scopes.ProvidesScopes(requiredScopes, options.IgnoreRequiredScopes))
            {
                var missingScopes = from scope in requiredScopes where !primaryAccount.Scopes.Contains(scope) select scope;

                results.AddResult(actionName,
                                  new ValidationWarning(ValidationErrorCode.RequiredScopesMissing,
                                                        null,
                                                        "Scenario was not run. Scopes required were not available: {0}", missingScopes.ComponentsJoinedByString(",")));
                return;
            }

            string[] requiredApiVersions = method.RequiredApiVersions.Union(scenario.RequiredApiVersions).ToArray();

            if (!primaryAccount.ApiVersions.ProvidesApiVersions(requiredApiVersions))
            {
                var missingApiVersions = from apiVersion in requiredApiVersions where !primaryAccount.ApiVersions.Contains(apiVersion) select apiVersion;

                results.AddResult(actionName,
                                  new ValidationWarning(ValidationErrorCode.RequiredApiVersionsMissing,
                                                        null,
                                                        "Scenario was not run. Api Versions required were not available: {0}", missingApiVersions.ComponentsJoinedByString(",")));
                return;
            }

            string[] requiredTags = method.RequiredTags.Union(scenario.RequiredTags).ToArray();

            if (!primaryAccount.Tags.ProvidesTags(requiredTags))
            {
                var missingTags = from tag in requiredTags where !primaryAccount.Tags.Contains(tag) select tag;

                results.AddResult(actionName,
                                  new ValidationWarning(ValidationErrorCode.RequiredTagsMissing,
                                                        null,
                                                        "Scenario was not run. Tags required were not available: {0}", missingTags.ComponentsJoinedByString(",")));
                return;
            }

            // Generate the tested request by "previewing" the request and executing
            // all test-setup procedures
            long startTicks           = DateTimeOffset.UtcNow.Ticks;
            var  requestPreviewResult = await method.GenerateMethodRequestAsync(scenario, method.SourceFile.Parent, primaryAccount, secondaryAccount);

            TimeSpan generateMethodDuration = new TimeSpan(DateTimeOffset.UtcNow.Ticks - startTicks);

            // Check to see if an error occured building the request, and abort if so.
            var generatorResults = results[actionName /*+ " [test-setup requests]"*/];

            generatorResults.AddResults(requestPreviewResult.Messages, requestPreviewResult.IsWarningOrError ? ValidationOutcome.Error :  ValidationOutcome.Passed);
            generatorResults.Duration = generateMethodDuration;

            if (requestPreviewResult.IsWarningOrError)
            {
                return;
            }

            // We've done all the test-setup work, now we have the real request to make to the service
            HttpRequest requestPreview = requestPreviewResult.Value;

            results.AddResult(
                actionName,
                new ValidationMessage(null, "Generated Method HTTP Request:\r\n{0}", requestPreview.FullHttpText()));

            var          issues           = new IssueLogger();
            HttpResponse expectedResponse = null;

            if (!string.IsNullOrEmpty(method.ExpectedResponse))
            {
                HttpParser.TryParseHttpResponse(method.ExpectedResponse, out expectedResponse, issues);
            }

            // Execute the actual tested method (the result of the method preview call, which made the test-setup requests)
            startTicks = DateTimeOffset.UtcNow.Ticks;
            var actualResponse = await requestPreview.GetResponseAsync(primaryAccount, issues);

            TimeSpan actualMethodDuration = new TimeSpan(DateTimeOffset.UtcNow.Ticks - startTicks);

            var requestResults = results[actionName];

            if (actualResponse.RetryCount > 0)
            {
                requestResults.AddResults(
                    new ValidationError[]
                    { new ValidationWarning(ValidationErrorCode.RequestWasRetried, null, "HTTP request was retried {0} times.", actualResponse.RetryCount) });
            }

            requestResults.AddResults(
                new ValidationError[]
                { new ValidationMessage(null, "HTTP Response:\r\n{0}", actualResponse.FullText(false)) });
            requestResults.Duration = actualMethodDuration;

            // Perform validation on the method's actual response
            method.ValidateResponse(actualResponse, expectedResponse, scenario, issues, options);

            requestResults.AddResults(issues.Issues.ToArray());

            // TODO: If the method is defined as a long running operation, we need to go poll the status
            // URL to make sure that the operation finished and the response type is valid.

            if (issues.Issues.WereErrors())
            {
                results.SetOutcome(actionName, ValidationOutcome.Error);
            }
            else if (issues.Issues.WereWarnings())
            {
                results.SetOutcome(actionName, ValidationOutcome.Warning);
            }
            else
            {
                results.SetOutcome(actionName, ValidationOutcome.Passed);
            }
        }
        /// <summary>
        /// Performs validation of a method (request/response) with a given service
        /// target and zero or more test scenarios
        /// </summary>
        /// <param name="method"></param>
        /// <param name="account"></param>
        /// <param name="credentials"></param>
        /// <returns></returns>
        public static async Task <ValidationResults> ValidateServiceResponseAsync(
            this MethodDefinition method,
            ScenarioDefinition[] scenarios,
            IServiceAccount primaryAccount,
            IServiceAccount secondaryAccount,
            ValidationOptions options = null)
        {
            if (null == method)
            {
                throw new ArgumentNullException("method");
            }
            if (null == primaryAccount)
            {
                throw new ArgumentNullException("primaryAccount");
            }

            ValidationResults results = new ValidationResults();

            if (scenarios.Length == 0)
            {
                // If no descenarios are defined for this method, add a new default scenario
                scenarios = new ScenarioDefinition[] {
                    new ScenarioDefinition {
                        Description         = "verbatim",
                        Enabled             = true,
                        MethodName          = method.Identifier,
                        RequiredScopes      = method.RequiredScopes,
                        RequiredApiVersions = method.RequiredApiVersions,
                        RequiredTags        = method.RequiredTags
                    }
                };
            }

            if (scenarios.Any() && !scenarios.Any(x => x.Enabled))
            {
                results.AddResult("init",
                                  new ValidationWarning(ValidationErrorCode.AllScenariosDisabled, null, "All scenarios for method {0} were disabled.", method.Identifier),
                                  ValidationOutcome.Skipped);

                return(results);
            }

            foreach (var scenario in scenarios.Where(x => x.Enabled))
            {
                try
                {
                    await ValidateMethodWithScenarioAsync(method, scenario, primaryAccount, secondaryAccount, results, options);
                }
                catch (Exception ex)
                {
                    results.AddResult(
                        "validation",
                        new ValidationError(
                            ValidationErrorCode.ExceptionWhileValidatingMethod,
                            method.SourceFile.DisplayName,
                            ex.Message));
                }
            }

            return(results);
        }
Esempio n. 10
0
        private static bool _TryValidateValueBase(string type, string subject, string objName, string val, List <string> invalidStartStrings, ValidationOptions options, out string msg)
        {
            #region "Analysis of System.Configuration Source:"

            /*
             * From http://www.w3.org/Addressing/
             *
             * reserved    = ';' | '/' | '?' | ':' | '@' | '&' | '=' | '+' | '$' | ','
             *
             * From Platform SDK
             *
             * reserved    = '\' |  '/' | '|' | ':' |  '"' |  '<' | '>'
             *
             */
            /*
             * Analysis of System.Configuration Source:
             *
             * NOTE: Element/section names themselves have no known reserved word restrictions. Restrictions are only present
             *      in property name definitions. However, I will still present my findings below. We will need to revisit
             *      the System.Configuration source to confirm.
             *
             * For section and element names, these are not allowed.
             * "configProtectedData", // Implicit is not allowed, and that is an "implicit" name.
             *  "location", // Implicit is not allowed, and can only start with "location" for implicit names.
             *  "config"}, // Implicit is not allowed, and can only start with "config" for implicit names.
             *
             * For property names, these are not allowed.
             * "lock",
             *  "config"}, // Implicit is not allowed, and can only start with "config" for implicit names.
             *
             */

            /* SECTION NAME CHECKS
             *
             * if (String.IsNullOrEmpty(name)) {
             *  throw new ConfigurationErrorsException(SR.GetString(SR.Config_tag_name_invalid), errorInfo);
             * }
             *
             * // must be a valid name in xml, so that it can be used as an element
             * // n.b. - it also excludes forward slash '/'
             * try {
             *  XmlConvert.VerifyName(name);
             * }
             * // Do not let the exception propagate as an XML exception,
             * // for we want errors in the section name to be treated as local errors,
             * // not global ones.
             * catch (Exception e) {
             *  throw ExceptionUtil.WrapAsConfigException(SR.GetString(SR.Config_tag_name_invalid), e, errorInfo);
             * }
             *
             * // Checks if == "configProtectedData"
             * if (IsImplicitSection(name)) {
             *  if (allowImplicit) {
             *      // avoid test below for strings starting with "config"
             *      return;
             *  }
             *  else {
             *      throw new ConfigurationErrorsException(SR.GetString(SR.Cannot_declare_or_remove_implicit_section, name), errorInfo);
             *  }
             * }
             *
             * if (StringUtil.StartsWith(name, "config")) {
             *  throw new ConfigurationErrorsException(SR.GetString(SR.Config_tag_name_cannot_begin_with_config), errorInfo);
             * }
             * // Checks if == "location"
             * if (name == KEYWORD_LOCATION) {
             *  throw new ConfigurationErrorsException(SR.GetString(SR.Config_tag_name_cannot_be_location), errorInfo);
             * }
             *
             */

            #endregion

            msg = "";

            string messageBuilder = "";

            if (options.HasFlag(ValidationOptions.IsXml))
            {
                subject = "'Xml " + subject + "'";
            }
            messageBuilder = "The " + type + " " + subject;
            // Fix redundant messaging.
            if (objName != val)
            {
                messageBuilder += " for " + objName + " '" + val + "'";
            }
            else
            {
                messageBuilder += " '" + val + "'";
            }
            //EXAMPLE: context.LogError("The Xml Section Name is required and cannot be an empty string.", "RequiredProperty", this);

            /**
             * Required Check.
             * */

            if (options.HasFlag(ValidationOptions.IsRequired) && string.IsNullOrEmpty(val))
            {
                msg = messageBuilder + " cannot be empty.";
                return(false);
            }

            /**
             * Reserved Word Check.
             * */

            // + Cannot be named "configProtectedData", "location", "config" (Implicit is not allowed, and that is an "implicit" name).
            bool hasInvalidWord = false;
            if (invalidStartStrings != null && invalidStartStrings.Count > 0)
            {
                string adj          = "";
                string reservedWord = "";
                foreach (string inv in invalidStartStrings)
                {
                    if (inv.Substring(0, 1) == "^")
                    {
                        adj          = "start with";
                        reservedWord = inv.Substring(1);
                        if (val.ToLower().StartsWith(reservedWord.ToLower()))
                        {
                            hasInvalidWord = true;
                        }
                    }
                    else
                    {
                        adj = "equal";
                        if (val.ToLower() == inv.ToLower())
                        {
                            hasInvalidWord = true;
                            reservedWord   = inv.ToLower();
                        }
                    }
                    if (hasInvalidWord)
                    {
                        break;
                    }
                }
                if (hasInvalidWord)
                {
                    msg = messageBuilder + " cannot " + adj + " reserved word '" + reservedWord + "'"; // String.Join(", ", invalidStartStrings);
                    return(false);
                }
            }

            /**
             * Invalid chars Check.
             * */
            if (!string.IsNullOrEmpty(val))
            {
                // We have a special validation method in System.Xml to handle XML names.
                if (!options.HasFlag(ValidationOptions.IsNamespace) && options.HasFlag(ValidationOptions.IsXml))
                {
                    try
                    {
                        XmlConvert.VerifyName(val);
                    }
                    catch (Exception e)
                    {
                        msg = messageBuilder + " must be a valid XML name: " + e.Message;
                        return(false);
                    }
                }
                else
                {
                    string regexStrStart       = "^[^0-9\\.][";
                    string regexStrAllowedChar = "a-zA-Z0-9_";
                    string regexStrEnd         = "]+[\\`]?$";
                    string regexFriendly       = "alphanumeric, start with a letter, cannot have special characters or spaces";

                    if (options.HasFlag(ValidationOptions.IsNamespace))
                    {
                        // Allow dots.
                        regexStrAllowedChar += "\\.";

                        //if (((options | ValidationOptions.IsXml) == ValidationOptions.IsXml))
                        if (options.HasFlag(ValidationOptions.IsXml))
                        {
                            // Allow URN: for XML namespace.
                            regexStrAllowedChar += "\\:";
                            regexFriendly       += ", must be valid XML namespace";
                        }
                        else
                        {
                            regexFriendly += ", must be valid namespace";
                        }
                    }
                    Regex re = new Regex(regexStrStart + regexStrAllowedChar + regexStrEnd);
                    if (!re.IsMatch(val))
                    {
                        msg = messageBuilder + " must be " + regexFriendly + ".";
                        return(false);
                    }
                }
            }
            return(true);
        }
Esempio n. 11
0
        private static IEnumerable <TestCaseData> GetTests(string draftFolder)
        {
            var testsPath = Path.Combine(TestContext.CurrentContext.WorkDirectory, _testCasesPath, $"{draftFolder}/")
                            .AdjustForPlatform();

            if (!Directory.Exists(testsPath))
            {
                return(Enumerable.Empty <TestCaseData>());
            }

            var fileNames = Directory.GetFiles(testsPath, "*.json", SearchOption.AllDirectories);
            var options   = new ValidationOptions
            {
                OutputFormat = OutputFormat.Verbose
            };

            switch (draftFolder)
            {
            case "draft6":
                options.ValidateAs = Draft.Draft6;
                break;

            case "draft7":
                options.ValidateAs = Draft.Draft7;
                break;

            case "draft2019-09":
                options.ValidateAs = Draft.Draft201909;
                break;

            case "draft2020-12":
                // will set this when implementing the next draft
                //options.ValidateAs = Draft.Draft202012;
                break;
            }

            var allTests = new List <TestCaseData>();

            foreach (var fileName in fileNames)
            {
                var shortFileName = Path.GetFileNameWithoutExtension(fileName);
                var contents      = File.ReadAllText(fileName);
                var collections   = JsonSerializer.Deserialize <List <TestCollection> >(contents, new JsonSerializerOptions
                {
                    PropertyNameCaseInsensitive = true
                });

                foreach (var collection in collections)
                {
                    collection.IsOptional = fileName.Contains("optional");
                    foreach (var test in collection.Tests)
                    {
                        var optional = collection.IsOptional ? "(optional)/" : null;
                        var name     = $"{draftFolder}/{optional}{collection.Description.Kebaberize()}/{test.Description.Kebaberize()}";
                        allTests.Add(new TestCaseData(collection, test, shortFileName, options)
                        {
                            TestName = name
                        });
                    }
                }
            }

            return(allTests);
        }
Esempio n. 12
0
 /// <summary>
 /// Only basic validation for objects that have unknown validation requirements.
 /// </summary>
 /// <param name="typeBase">Reference to the ModelElement so we can find it's name.</param>
 /// <param name="name"></param>
 /// <param name="msg"></param>
 /// <returns></returns>
 internal static bool TryValidateBaseName(ModelElement typeBase, string name, ValidationOptions options, out string msg)
 {
     return(_TryValidateValueBase(typeBase.GetType().Name, "Name", name, name, null, ValidationOptions.None, out msg));
 }
Esempio n. 13
0
        /*
         * internal static bool TryValidateSectionName(string sectName, string name, out string msg)
         * {
         *  // TODO: This may be similar to Element, where there is actually no reserved word restriction. Investigate and update.
         *  //return _TryValidateValueBase(type, "name", name, invalidStartStrings, options, out msg);
         *
         *  return _TryValidateValueBase("Section", "Name", sectName, name, new List<string>(){
         *      "configProtectedData", // Implicit is not allowed, and that is an "implicit" name.
         *      "location", // Implicit is not allowed, and can only start with "location" for implicit names.
         *      "config"}, // Implicit is not allowed, and can only start with "config" for implicit names.
         *      ValidationOptions.None,
         *      out msg);
         * }
         */
        /*
         * internal static bool TryValidatePropertyNameForElement(string name, out string msg)
         * {
         *  return _TryValidateNameBase("Element", name, new List<string>(){
         *      "configProtectedData", // Implicit is not allowed, and that is an "implicit" name.
         *      "location", // Implicit is not allowed, and can only start with "location" for implicit names.
         *      "config"}, // Implicit is not allowed, and can only start with "config" for implicit names.
         *  out msg);
         * }
         */

        /// <summary>
        /// Validate a name property from an object in 'Attributes' part.
        /// </summary>
        /// <remarks>
        /// Not certain all of the restrictions are covered here, as it was difficult to find in .NET ref source.
        /// </remarks>
        /// <param name="name"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        internal static bool TryValidateAttributesItemNameProperty(string objName, string name, ValidationOptions options, out string msg)
        {
            #region "Analysis of System.Configuration Source:"

            // NOTE: Only validate prop name when IsDefaultCollection and name is empty.

            /*
             * if ((options & ConfigurationPropertyOptions.IsDefaultCollection) != 0 &&
             *  String.IsNullOrEmpty(name)) {
             *  name = DefaultCollectionPropertyName;
             * }
             * else {
             *  ValidatePropertyName(name);
             * }
             */



            /*
             *
             * ValidatePropertyName(name) {
             *   if (string.IsNullOrEmpty(name)) {
             *      throw new ArgumentException(SR.GetString(SR.String_null_or_empty), "name");
             *  }
             *
             *  if (BaseConfigurationRecord.IsReservedAttributeName(name)) {
             *      throw new ArgumentException(SR.GetString(SR.Property_name_reserved, name));
             *  }
             * }
             */


            /*
             * // We reserve all attribute names starting with config or lock
             * internal static bool IsReservedAttributeName(string name) {
             *  if (StringUtil.StartsWith(name, "config") ||
             *      StringUtil.StartsWith(name, "lock")) {
             *      return true;
             *  }
             *  else {
             *      return false;
             *  }
             * }
             */
            #endregion

            return(_TryValidateValueBase("Property", "Name", objName, name, new List <string>()
            {
                "^lock",    // SR.Property_name_reserved.
                "^config"
            },              // SR.Property_name_reserved.
                                         options,
                                         out msg));
        }
Esempio n. 14
0
		private static string Validate(string contents, ValidationOptions validationOptions, bool shouldPass)
		{
			string f = Path.GetTempFileName();
			File.WriteAllText(f, contents);
			string errors;
			try
			{
				errors = Validator.GetAnyValidationErrors(f, new NullValidationProgress(),  validationOptions);
				if (shouldPass)
				{
					if (errors != null)
					{
						Console.WriteLine(errors);
					}
					Assert.IsNullOrEmpty(errors);
				}
				else
				{
					Assert.Greater(errors.Length,0);
				}
			}
			finally
			{
				File.Delete(f);
			}
			return errors;
		}
Esempio n. 15
0
		///<summary>
		/// Parse the given LIFT file and return a string containing all the validation errors
		/// (if any).  Progress reporting is supported.
		///</summary>
		static public string GetAnyValidationErrors(string path, IValidationProgress progress, ValidationOptions validationOptions)
		{
			string errors = "";
			if ((validationOptions & ValidationOptions.CheckLIFT) != null)
			{
				errors += GetSchemaValidationErrors(path, progress);
			}

			if ((validationOptions & ValidationOptions.CheckGUIDs)!=null)
			{
				errors += GetDuplicateGuidErrors(path, progress);
			}

			return errors;
		}
Esempio n. 16
0
        /// <summary>
        /// Validates that a particular HttpResponse matches the method definition and optionally the expected response.
        /// </summary>
        /// <param name="method">Method definition that was used to generate a request.</param>
        /// <param name="actualResponse">Actual response from the service (this is what we validate).</param>
        /// <param name="expectedResponse">Prototype response (expected) that shows what a valid response should look like.</param>
        /// <param name="scenario">A test scenario used to generate the response, which may include additional parameters to verify.</param>
        /// <param name="issues">A collection of errors, warnings, and verbose messages generated by this process.</param>
        public void ValidateResponse(HttpResponse actualResponse, HttpResponse expectedResponse, ScenarioDefinition scenario, IssueLogger issues, ValidationOptions options = null)
        {
            if (null == actualResponse)
            {
                throw new ArgumentNullException("actualResponse");
            }

            // Verify the request is valid (headers, etc)
            this.VerifyRequestFormat(issues);

            // Verify that the expected response headers match the actual response headers
            if (null != expectedResponse)
            {
                expectedResponse.ValidateResponseHeaders(actualResponse, issues, (null != scenario) ? scenario.AllowedStatusCodes : null);
            }

            // Verify the actual response body is correct according to the schema defined for the response
            this.VerifyResponseBody(actualResponse, expectedResponse, issues, options);

            // Verify any expectations in the scenario are met
            if (null != scenario)
            {
                scenario.ValidateExpectations(actualResponse, issues);
            }
        }
Esempio n. 17
0
        private void AddPropertyToPropertiesGrid(ComponentPropertyImpl property)
        {
            SlyceTreeGridItem gridItem = new SlyceTreeGridItem();

            gridItem.Tag = property;
            gridItem.SubItems.Add(new SlyceTreeGridCellItem(property.Name));
            gridItem.SubItems.Add(new SlyceTreeGridCellItem(property.Type));

            foreach (ArchAngel.Interfaces.ITemplate.IUserOption uo in property.Ex)
            {
                if (uo.DataType == typeof(bool?))
                {
                    bool?nullableBoolValue = (bool?)uo.Value;
                    gridItem.SubItems.Add(new SlyceTreeGridCellItem(false, true, nullableBoolValue.HasValue ? nullableBoolValue.Value : false));
                }
                else if (uo.DataType == typeof(string))
                {
                    gridItem.SubItems.Add(new SlyceTreeGridCellItem((string)uo.Value));
                }
                else if (uo.DataType == typeof(int))
                {
                    gridItem.SubItems.Add(new SlyceTreeGridCellItem((int)uo.Value));
                }
                else if (uo.DataType == typeof(bool))
                {
                    gridItem.SubItems.Add(new SlyceTreeGridCellItem((bool)uo.Value));
                }
                else
                {
                    throw new NotImplementedException("Type not handled yet: " + uo.DataType.Name);
                }
            }
            gridItem.SubItems.Add(CreateNewNullableCell(property, property.ValidationOptions.FractionalDigits, ApplicableOptions.Digits));
            gridItem.SubItems.Add(CreateNewNullableCell(property, property.ValidationOptions.FutureDate, ApplicableOptions.Date));
            gridItem.SubItems.Add(CreateNewNullableCell(property, property.ValidationOptions.IntegerDigits, ApplicableOptions.Digits));
            gridItem.SubItems.Add(CreateNewNullableCell(property, property.ValidationOptions.MaximumLength, ApplicableOptions.Length));
            gridItem.SubItems.Add(CreateNewNullableCell(property, property.ValidationOptions.MinimumLength, ApplicableOptions.Length));
            gridItem.SubItems.Add(CreateNewNullableCell(property, property.ValidationOptions.MaximumValue, ApplicableOptions.Value));
            gridItem.SubItems.Add(CreateNewNullableCell(property, property.ValidationOptions.MinimumValue, ApplicableOptions.Value));
            gridItem.SubItems.Add(CreateNewNullableCell(property, property.ValidationOptions.NotEmpty, ApplicableOptions.NotEmpty));
            gridItem.SubItems.Add(CreateNewNullableCell(property, property.ValidationOptions.Nullable, ApplicableOptions.Nullable));
            gridItem.SubItems.Add(CreateNewNullableCell(property, property.ValidationOptions.PastDate, ApplicableOptions.Date));
            gridItem.SubItems.Add(CreateNewNullableCell(property, property.ValidationOptions.RegexPattern, ApplicableOptions.RegexPattern));
            gridItem.SubItems.Add(new SlyceTreeGridCellItem(property.ValidationOptions.Validate, (ValidationOptions.GetApplicableValidationOptionsForType(property.Type) & ApplicableOptions.Validate) != ApplicableOptions.Validate));

            slyceGrid1.Items.Add(gridItem);
        }
Esempio n. 18
0
        /// <summary>
        /// Verify that the body of the actual response is consistent with the method definition and expected response parameters
        /// </summary>
        /// <param name="method">The MethodDefinition that generated the response.</param>
        /// <param name="actualResponse">The actual response from the service to validate.</param>
        /// <param name="expectedResponse">The prototype expected response from the service.</param>
        /// <param name="issues">A collection of errors that will be appended with any detected errors</param>
        private void VerifyResponseBody(HttpResponse actualResponse, HttpResponse expectedResponse, IssueLogger issues, ValidationOptions options = null)
        {
            if (string.IsNullOrEmpty(actualResponse.Body) &&
                ((expectedResponse != null && !string.IsNullOrEmpty(expectedResponse.Body)) ||
                 (this.ExpectedResponseMetadata != null && this.ExpectedResponseMetadata.ResourceType != null)))
            {
                issues.Error(ValidationErrorCode.HttpBodyExpected, "Body missing from response (expected response includes a body or a response type was provided).");
            }
            else if (!string.IsNullOrEmpty(actualResponse.Body))
            {
                if (this.ExpectedResponseMetadata == null ||
                    (string.IsNullOrEmpty(this.ExpectedResponseMetadata.ResourceType) &&
                     (expectedResponse != null && !string.IsNullOrEmpty(expectedResponse.Body))))
                {
                    issues.Error(ValidationErrorCode.ResponseResourceTypeMissing, $"Expected a response, but resource type on method is missing: {this.Identifier}");
                }
                else
                {
                    var otherResources = this.SourceFile.Parent.ResourceCollection;
                    otherResources.ValidateResponseMatchesSchema(
                        this,
                        actualResponse,
                        expectedResponse,
                        issues,
                        options);
                }

                var responseValidation = actualResponse.IsResponseValid(
                    this.SourceFile.DisplayName,
                    this.SourceFile.Parent.Requirements,
                    issues);
            }
        }
Esempio n. 19
0
 /// <summary>
 /// Run data type and field length validation on a specific value.
 /// Certain types of validators obviate the need to specify a minimum or maximum length,
 /// like ValidationOptions.Email.
 /// <example>
 /// <code>
 /// using Mezzocode.Halide3;
 /// ...
 /// string result = h3Identify.Validate(
 ///		value,
 ///		h3Identify.ValidationOptions.Email);
 /// </code>
 /// </example>
 /// <para>A common practice is to add error message fields underneath each of your form fields,
 /// and then use a single line to validate the input and display the error on the form, as well
 /// as set a global flag that identifies that there has been an error.</para>
 /// <example>
 /// <code>
 /// using Mezzocode.Halide3;
 /// ...
 /// errorFlag +=
 ///		EmailFieldErrorMessage.InnerHtml =
 ///			h3Identify.Validate(
 ///				EmailField.Value,
 ///				h3Identify.ValidationOptions.Email);
 /// </code>
 /// </example>
 /// <para>In this way, you can check "errorFlag" to see if it's empty or null, in which case,
 /// there were no validation errors, otherwise, you know one or more validations failed.
 /// And in the same line, the error message for each field is filled with the error message,
 /// since ValidateItem() returns an empty string if the validation is successful, or a friendly
 /// error string if it fails.</para>
 /// </summary>
 /// <param name="value">Value to validate.</param>
 /// <param name="valType">Constant determining what type of validation.</param>
 /// <returns>Empty string if validation succeeds, error message on failure.</returns>
 public static String Validate(string value, ValidationOptions valType)
 {
     return Validate(value, valType, 0, 0, false);
 }
Esempio n. 20
0
 /// <summary>
 /// Returns a constraint that checks a document for valid markup.
 /// </summary>
 public static Constraint Markup(ValidationOptions options)
 {
     return new MarkupConstraint(options);
 }
        static Project0RepoLayer p0Context = new Project0RepoLayer(); // create the context here to acceess it in all methods of this class
        static void Main(string[] args)


        {
            // p0Context.ManualCreateFloor();

            // variables
            Console.Clear();
            string usrChoice;

            do  //enter program

            //greet user and see where they need to go. quit if an option listed isn't inputted
            {
                Console.WriteLine
                    ("Welcome to the Abstract Museum, where we abstract out abstract art! What would you like to do?\n" +
                    "1. Create User \n2. Login\n-1. Quit");

                usrChoice = Console.ReadLine();//get user choice

                //initializing user inputs
                string un = "0"; //globawe uname outside loop to use later


                while (usrChoice == "1")
                {
                    //init ui
                    string fn = "0";
                    string ln = "0";
                    while (usrChoice != "-2")
                    {
                        while ((un == "0" || fn == "0" || ln == "0") && (usrChoice != "-2"))
                        {
                            //loop create player until acceptable values are given
                            ///prompt for information to create player
                            Console.Clear();
                            Console.WriteLine("We need some information before we can proceed: " +
                                              "\nPlease make sure that that all three inputs contain at least 3 characters and no more than 20!");

                            Console.Write("\nEnter a unique username: "******"\nEnter your first name: ");
                            fn = ValidationOptions.ValidateInput(Console.ReadLine());
                            Console.Write("\nEnter your last name: ");
                            ln = ValidationOptions.ValidateInput(Console.ReadLine());

                            Console.Write("\nIf you entered less than 2 or more than 20 characters for any inputs, we will prompt you to enter your information again. \nPress enter to continue...");
                            Console.ReadLine();

                            Console.Clear();
                            Console.WriteLine("We are creating user with" +
                                              $"\nUsername: {un} \nFirst Name: {fn} \nLast Name: {ln}");

                            Console.Write("\nIf you'd like to cancel, enter -2:");
                            usrChoice = Console.ReadLine();
                            if (usrChoice == "-2")
                            {
                                un = "0";
                                ln = "0";
                                fn = "0";
                            }
                        }
                        usrChoice = "-2";
                    }



                    if (un != "0" || fn != "0" || ln != "0")
                    {
                        User user = p0Context.CreateUser(un, fn, ln);
                        usrChoice = SignedIn.FirstMenu(user);
                    }
                }//end choice 1


                while (usrChoice == "2")
                {
                    Console.Write("Great to see you again! You can quit to the main menu by entering '-1'. Enter your unique username: "******"-1")
                    {
                        try
                        {
                            un = ValidationOptions.ValidateInput(un);
                            User user = p0Context.FindUser(un);

                            usrChoice = SignedIn.FirstMenu(user);
                        }
                        catch (System.Exception)
                        {
                            Console.Clear();
                            Console.WriteLine("We were not able to locate that user.\n We will return you to the previous screen. Press enter to continue: ");
                            Console.ReadLine();
                            usrChoice = "2";
                        }
                    }
                    else
                    {
                        Console.Clear();
                        usrChoice = "-1";
                    }
                }
            }while(usrChoice != "-1");//end program

            Console.Clear();
            Console.Write("Thank you for your virtual stay at the Abstract Museum!");
        }//end main
Esempio n. 22
0
			private static bool IsOptionSet(ValidationOptions options, ValidationOptions flag)
			{
				return (options & flag) == flag;
			}
Esempio n. 23
0
 public LengthShould16Validator()
     : base("LengthShould16Validator")
 {
     _options = new ValidationOptions();
 }
Esempio n. 24
0
        /// <summary>
        /// Run data type and field length validation on a specific value.
        /// Certain types of validators obviate the need to specify a minimum or maximum length,
        /// like ValidationOptions.Email.
        /// </summary>
        /// <param name="value">Value to validate.</param>
        /// <param name="valType">Constant determining what type of validation.</param>
        /// <param name="minLength">Minimum length alowed.</param>
        /// <param name="maxLength">Maximum length allowed.</param>
        /// <param name="optional">Field is optional. Zero length validates, otherwise, full validation occurs.</param>
        /// <returns>Empty string if validation succeeds, error message on failure.</returns>
        public static string ValidateText(this string value, ValidationOptions valType, int minLength, int maxLength, bool optional)
        {
            string result = "";

            if (optional && value.Length < 1)
            {
                return(result);
            }

            // Evaluate length of value if minLength and maxLengths are non-zero
            if (minLength > 0 && maxLength > 0)
            {
                if (value.Length > maxLength)
                {
                    result += "Must be " + maxLength.ToString() + " character(s) long";
                }
                else
                {
                    if (value.Length < minLength)
                    {
                        result += "Must be " + minLength.ToString() + " character(s) or longer";
                    }
                }
            }

            // If no length errors, validate data is of a specific format
            if (result == "")
            {
                if (valType == ValidationOptions.USStateAbbreviation)
                {
                    bool flag = Geography.StatesAbbreviations.Contains(value, new StringComparer(false));

                    if (!flag)
                    {
                        result += "Not a state";
                    }
                }

                if (valType == ValidationOptions.Email)
                {
                    if (!IsEmail(value))
                    {
                        result += "Invalid email address format";
                    }
                }

                if (valType == ValidationOptions.EmailList)
                {
                    // Invalid string
                    if (value.Length < 6)
                    {
                        result += "Invalid email address format";
                    }
                    else
                    {
                        // Only one email address? If not, check for multiple.
                        if (!IsEmail(value))
                        {
                            string delim = "";

                            if (delim == "" && value.IndexOf(",") > 0)
                            {
                                delim = ",";
                            }
                            if (delim == "" && value.IndexOf("|") > 0)
                            {
                                delim = "|";
                            }
                            if (delim == "" && value.IndexOf(";") > 0)
                            {
                                delim = ";";
                            }
                            if (delim == "" && value.IndexOf("/") > 0)
                            {
                                delim = "/";
                            }
                            if (delim == "" && value.IndexOf(" ") > 0)
                            {
                                delim = " ";
                            }

                            if (delim != "")
                            {
                                value = value.Replace(delim, ",");
                                value = value.Replace(" ", "");

                                while (value.IndexOf(",,") > 0)
                                {
                                    value = value.Replace(",,", ",");
                                }

                                string[] addresses = value.Split(',');

                                for (int x = 0; x < addresses.Length; x++)
                                {
                                    if (!IsEmail(addresses[x]))
                                    {
                                        result += "One or more email addresses are invalid";
                                    }
                                }
                            }
                            else
                            {
                                result += "Must have one or more email addresses";
                            }
                        }
                    }
                }

                if (valType == ValidationOptions.Number)
                {
                    if (!IsNumeric(value))
                    {
                        result += "Not a numeric value";
                    }
                }

                if (valType == ValidationOptions.PureNumber)
                {
                    if (!IsPureNumeric(value))
                    {
                        result += "Must only contain numbers";
                    }
                }

                if (valType == ValidationOptions.NonZero)
                {
                    if (!IsPureNumeric(value))
                    {
                        result += "Must only contain numbers";
                    }
                    else
                    {
                        if (Convert.ToInt32(value) <= 0)
                        {
                            result += "Must be greater than zero";
                        }
                    }
                }

                if (valType == ValidationOptions.Currency)
                {
                    if (!IsCurrency(value))
                    {
                        result += "Not a currency value";
                    }
                }

                if (valType == ValidationOptions.Date)
                {
                    if (!IsDate(value))
                    {
                        result += "Not a date";
                    }
                }

                if (valType == ValidationOptions.Telephone)
                {
                    if (!MatchesPattern(value, RegularExpressions.TelephoneUS))
                    {
                        result += "Not a telephone number";
                    }
                }

                if (valType == ValidationOptions.Telephone10)
                {
                    if (!MatchesPattern(value, RegularExpressions.Telephone10))
                    {
                        result += "Not a telephone number with area code";
                    }
                }

                if (valType == ValidationOptions.CreditCard)
                {
                    if (!MatchesPattern(value, RegularExpressions.ValidCreditCardNumber))
                    {
                        result += "Not a credit card number";
                    }
                }

                if (valType == ValidationOptions.ZipCode)
                {
                    if (!MatchesPattern(value, RegularExpressions.ZipCode))
                    {
                        result += "Not a 5-digit zip code";
                    }
                }

                if (valType == ValidationOptions.Url)
                {
                    if (!MatchesPattern(value, RegularExpressions.Url))
                    {
                        result += "Not a URL";
                    }
                }

                if (valType == ValidationOptions.IPv4Address)
                {
                    if (!MatchesPattern(value, RegularExpressions.IPv4Address))
                    {
                        result += "Not an IP address";
                    }
                }

                if (valType == ValidationOptions.Ssn)
                {
                    if (!MatchesPattern(value, RegularExpressions.SocialSecurityNumber))
                    {
                        result += "Not a social security number";
                    }
                }

                if (valType == ValidationOptions.Time)
                {
                    if (!MatchesPattern(value, RegularExpressions.Time) && !MatchesPattern(value, RegularExpressions.TimeMilitary))
                    {
                        result += "Not a time of day";
                    }
                }

                if (valType == ValidationOptions.Domain)
                {
                    if (!MatchesPattern(value, RegularExpressions.DomainName))
                    {
                        result += "Not a domain name";
                    }
                }

                if (valType == ValidationOptions.FullNameWithComma)
                {
                    if (!MatchesPattern(value, RegularExpressions.FullNameWithComma))
                    {
                        result += "Not last name, first name";
                    }
                }
            }

            return(result);
        }
Esempio n. 25
0
        /// <summary>
        /// Validates that a particular HttpResponse matches the method definition and optionally the expected response.
        /// </summary>
        /// <param name="method">Method definition that was used to generate a request.</param>
        /// <param name="actualResponse">Actual response from the service (this is what we validate).</param>
        /// <param name="expectedResponse">Prototype response (expected) that shows what a valid response should look like.</param>
        /// <param name="scenario">A test scenario used to generate the response, which may include additional parameters to verify.</param>
        /// <param name="errors">A collection of errors, warnings, and verbose messages generated by this process.</param>
        public void ValidateResponse(HttpResponse actualResponse, HttpResponse expectedResponse, ScenarioDefinition scenario, out ValidationError[] errors, ValidationOptions options = null)
        {
            if (null == actualResponse)
            {
                throw new ArgumentNullException("actualResponse");
            }

            List <ValidationError> detectedErrors = new List <ValidationError>();

            // Verify the request is valid (headers, etc)
            this.VerifyRequestFormat(detectedErrors);

            // Verify that the expected response headers match the actual response headers
            ValidationError[] httpErrors;
            if (null != expectedResponse && !expectedResponse.ValidateResponseHeaders(actualResponse, out httpErrors, (null != scenario) ? scenario.AllowedStatusCodes : null))
            {
                detectedErrors.AddRange(httpErrors);
            }

            // Verify the actual response body is correct according to the schema defined for the response
            ValidationError[] bodyErrors;
            this.VerifyResponseBody(actualResponse, expectedResponse, out bodyErrors, options);
            detectedErrors.AddRange(bodyErrors);

            // Verify any expectations in the scenario are met
            if (null != scenario)
            {
                scenario.ValidateExpectations(actualResponse, detectedErrors);
            }

            errors = detectedErrors.ToArray();
        }
Esempio n. 26
0
 /// <summary>
 /// Run data type and field length validation on a specific value.
 /// Certain types of validators obviate the need to specify a minimum or maximum length,
 /// like ValidationOptions.Email.
 /// </summary>
 /// <param name="value">Value to validate.</param>
 /// <param name="valType">Constant determining what type of validation.</param>
 /// <param name="minLength">Minimum length alowed.</param>
 /// <param name="maxLength">Maximum length allowed.</param>
 /// <returns>Empty string if validation succeeds, error message on failure.</returns>
 public static string ValidateText(this string value, ValidationOptions valType, int minLength, int maxLength)
 {
     return(ValidateText(value, valType, minLength, maxLength, false));
 }
    public IEnumerable <IDocumentValidatorRule> GetRules(string schemaName)
    {
        ValidationOptions options = _optionsCache.GetOrAdd(schemaName, CreateOptions);

        return(options.Rules);
    }
Esempio n. 28
0
 /// <summary>
 /// Run data type and field length validation on a specific value.
 /// Certain types of validators obviate the need to specify a minimum or maximum length,
 /// like ValidationOptions.Email.
 /// </summary>
 /// <param name="value">Value to validate.</param>
 /// <param name="valType">Constant determining what type of validation.</param>
 /// <returns>Empty string if validation succeeds, error message on failure.</returns>
 public static string ValidateText(this string value, ValidationOptions valType)
 {
     return(ValidateText(value, valType, 0, 0, false));
 }
Esempio n. 29
0
        public void ValidationOneWithDataAnnotationAndShouldBeFailureTest()
        {
            var options = new ValidationOptions();

            options.AnnotationEnabled        = false;
            options.FailureIfInstanceIsNull  = true;
            options.FailureIfProjectNotMatch = false;
            options.CustomValidatorEnabled   = true;

            var provider = new ValidationProvider(ValidationProjectManager, VerifiableObjectResolver, options);

            ValidationRegistrar.ForProvider(provider, "UT_ValidationOneWithDataAnnotationAndShouldBeFailureTest")
            .ForDataAnnotationSupport()
            .Build();

            var validator = ValidationMe.Use("UT_ValidationOneWithDataAnnotationAndShouldBeFailureTest").Resolve <GoodJob>();

            var model1 = new GoodJob()
            {
                Name = "", Cost = 11
            };
            var model2 = new GoodJob()
            {
                Name = "11111111111", Cost = 11
            };
            var model3 = new GoodJob()
            {
                Name = "Good", Cost = 9
            };
            var model4 = new GoodJob()
            {
                Name = "", Cost = -9
            };

            validator.VerifyOne(x => x.Name, model1.Name).IsValid.Should().BeFalse();
            validator.VerifyOne(model1.Name, "Name").IsValid.Should().BeFalse();
            validator.VerifyOne(typeof(GoodJob), model1.Name, "Name").IsValid.Should().BeFalse();

            validator.VerifyOne(x => x.Cost, model1.Cost).IsValid.Should().BeTrue();
            validator.VerifyOne(model1.Cost, "Cost").IsValid.Should().BeTrue();
            validator.VerifyOne(typeof(GoodJob), model1.Cost, "Cost").IsValid.Should().BeTrue();


            validator.VerifyOne(x => x.Name, model2.Name).IsValid.Should().BeFalse();
            validator.VerifyOne(model2.Name, "Name").IsValid.Should().BeFalse();
            validator.VerifyOne(typeof(GoodJob), model2.Name, "Name").IsValid.Should().BeFalse();

            validator.VerifyOne(x => x.Cost, model2.Cost).IsValid.Should().BeTrue();
            validator.VerifyOne(model2.Cost, "Cost").IsValid.Should().BeTrue();
            validator.VerifyOne(typeof(GoodJob), model2.Cost, "Cost").IsValid.Should().BeTrue();


            validator.VerifyOne(x => x.Name, model3.Name).IsValid.Should().BeTrue();
            validator.VerifyOne(model3.Name, "Name").IsValid.Should().BeTrue();
            validator.VerifyOne(typeof(GoodJob), model3.Name, "Name").IsValid.Should().BeTrue();

            validator.VerifyOne(x => x.Cost, model3.Cost).IsValid.Should().BeFalse();
            validator.VerifyOne(model3.Cost, "Cost").IsValid.Should().BeFalse();
            validator.VerifyOne(typeof(GoodJob), model3.Cost, "Cost").IsValid.Should().BeFalse();


            validator.VerifyOne(x => x.Name, model4.Name).IsValid.Should().BeFalse();
            validator.VerifyOne(model4.Name, "Name").IsValid.Should().BeFalse();
            validator.VerifyOne(typeof(GoodJob), model4.Name, "Name").IsValid.Should().BeFalse();

            validator.VerifyOne(x => x.Cost, model4.Cost).IsValid.Should().BeFalse();
            validator.VerifyOne(model4.Cost, "Cost").IsValid.Should().BeFalse();
            validator.VerifyOne(typeof(GoodJob), model4.Cost, "Cost").IsValid.Should().BeFalse();
        }
Esempio n. 30
0
 /// <summary>
 /// Run data type validation on a specific value.
 /// </summary>
 /// <param name="value">Value to validate.</param>
 /// <param name="valType">Constant determining what type of validation.</param>
 /// <param name="optional">Field is optional. Zero length validates, otherwise, full validation occurs.</param>
 /// <returns>Empty string if validation succeeds, error message on failure.</returns>
 public static string ValidateText(this string value, ValidationOptions valType, bool optional)
 {
     return(ValidateText(value, valType, 0, 0, optional));
 }
Esempio n. 31
0
 public ValidationHandler TempBuild(IVerifiableObjectResolver objectResolver, ValidationOptions options)
 {
     BuildMySelf();
     return(_parentRegistrar.TempBuild(objectResolver, options));
 }
 public ValidationHandler TempBuild(ValidationOptions options)
 {
     return(WithMessage(string.Empty).TempBuild(options));
 }
 /// <summary>
 /// Override the configuration of the validator.
 /// </summary>
 /// <param name="options"></param>
 void IValidationProvider.UpdateOptions(ValidationOptions options)
 {
 }
 public ValidationHandler TempBuild(IVerifiableObjectResolver objectResolver, ValidationOptions options)
 {
     return(WithMessage(string.Empty).TempBuild(objectResolver, options));
 }
Esempio n. 35
0
        public void Benchmark(TestCollection collection, TestCase test, string fileName, ValidationOptions options)
        {
            if (!InstanceIsDeserializable(test.Data))
            {
                Assert.Inconclusive("Instance not deserializable");
            }

            options.OutputFormat = OutputFormat.Flag;
            var result = collection.Schema.Validate(test.Data, options);

            if (collection.IsOptional && result?.IsValid != test.Valid)
            {
                Assert.Inconclusive("Test optional");
            }
            Assert.AreEqual(test.Valid, result.IsValid);
        }
        public static async Task <ValidationResult> Validate(string sbom, SchemaVersion schemaVersion)
        {
            if (schemaVersion == SchemaVersion.v1_0 || schemaVersion == SchemaVersion.v1_1)
            {
                throw new UnsupportedSchemaVersionException($"JSON format is not supported by schema {schemaVersion}");
            }

            var validationMessages = new List <string>();

            var schemaVersionString = schemaVersion.ToString().Substring(1).Replace('_', '.');
            var assembly            = typeof(JsonBomValidator).GetTypeInfo().Assembly;

            using (var schemaStream = assembly.GetManifestResourceStream($"CycloneDX.Json.Schemas.bom-{schemaVersionString}.schema.json"))
                using (var spdxStream = assembly.GetManifestResourceStream("CycloneDX.Json.Schemas.spdx.schema.json"))
                {
                    var schema = await JsonSchema.FromStream(schemaStream);

                    var spdxSchema = await JsonSchema.FromStream(spdxStream);

                    SchemaRegistry.Global.Register(new Uri("file://spdx.schema.json"), spdxSchema);

                    var jsonDocument      = JsonDocument.Parse(sbom);
                    var validationOptions = new ValidationOptions
                    {
                        OutputFormat            = OutputFormat.Detailed,
                        RequireFormatValidation = true
                    };

                    var result = schema.Validate(jsonDocument.RootElement, validationOptions);

                    if (result.IsValid)
                    {
                        foreach (var properties in jsonDocument.RootElement.EnumerateObject())
                        {
                            if (properties.Name == "specVersion")
                            {
                                var specVersion = properties.Value.GetString();
                                if (specVersion != schemaVersionString)
                                {
                                    validationMessages.Add($"Incorrect schema version: expected {schemaVersionString} actual {specVersion}");
                                }
                            }
                        }
                    }
                    else
                    {
                        validationMessages.Add($"Validation failed: {result.Message}");
                        validationMessages.Add(result.SchemaLocation.ToString());

                        if (result.NestedResults != null)
                        {
                            var nestedResults = new Queue <ValidationResults>(result.NestedResults);

                            while (nestedResults.Count > 0)
                            {
                                var nestedResult = nestedResults.Dequeue();

                                if (
                                    !string.IsNullOrEmpty(nestedResult.Message) &&
                                    nestedResult.NestedResults != null &&
                                    nestedResult.NestedResults.Count > 0)
                                {
                                    validationMessages.Add($"{nestedResult.InstanceLocation}: {nestedResult.Message}");
                                }

                                if (nestedResult.NestedResults != null)
                                {
                                    foreach (var newNestedResult in nestedResult.NestedResults)
                                    {
                                        nestedResults.Enqueue(newNestedResult);
                                    }
                                }
                            }
                        }
                    }
                }

            return(new ValidationResult
            {
                Valid = validationMessages.Count == 0,
                Messages = validationMessages
            });
        }
Esempio n. 37
0
 /// <summary>
 /// Run data type and field length validation on a specific value.
 /// Certain types of validators obviate the need to specify a minimum or maximum length,
 /// like ValidationOptions.Email.
 /// <example>
 /// <code>
 /// using Mezzocode.Halide3;
 /// ...
 /// string result = h3Identify.Validate(
 ///		value,
 ///		h3Identify.ValidationOptions.Email,
 ///		0,
 ///		0);
 /// </code>
 /// </example>
 /// <para>A common practice is to add error message fields underneath each of your form fields,
 /// and then use a single line to validate the input and display the error on the form, as well
 /// as set a global flag that identifies that there has been an error.</para>
 /// <example>
 /// <code>
 /// using Mezzocode.Halide3;
 /// ...
 /// errorFlag +=
 ///		EmailFieldErrorMessage.InnerHtml =
 ///			h3Identify.Validate(
 ///				EmailField.Value,
 ///				h3Identify.ValidationOptions.Email,
 ///				0,
 ///				0);
 /// </code>
 /// </example>
 /// <para>In this way, you can check "errorFlag" to see if it's empty or null, in which case,
 /// there were no validation errors, otherwise, you know one or more validations failed.
 /// And in the same line, the error message for each field is filled with the error message,
 /// since ValidateItem() returns an empty string if the validation is successful, or a friendly
 /// error string if it fails.</para>
 /// </summary>
 /// <param name="value">Value to validate.</param>
 /// <param name="valType">Constant determining what type of validation.</param>
 /// <param name="minLength">Minimum length alowed.</param>
 /// <param name="maxLength">Maximum length allowed.</param>
 /// <returns>Empty string if validation succeeds, error message on failure.</returns>
 public static String Validate(string value, ValidationOptions valType, int minLength, int maxLength)
 {
     return Validate(value, valType, minLength, maxLength, false);
 }
            public static string FirstMenu(User u)
            {
                string usrChoice;

                do
                {
                    Console.Clear();
                    Console.WriteLine($"Welcome {u.Username}! Enter -1 to quit. " +
                                      "What would you like to do?" +
                                      "\n3. View Floor" +
                                      "\n4. Book a tour" +
                                      "\n-1. Logout");
                    usrChoice = Console.ReadLine();

                    if (usrChoice == "3") //if user wants matrix printed
                    {
                        Console.WriteLine("How many rows does the floor you want to look at have? No more than 6! ");
                        int n = ValidationOptions.ValidateStringToInt(Console.ReadLine());
                        Console.Clear();
                        if (n < 7 && n > 0)
                        {
                            Print2DArray(generateMatrix(n));
                        }

                        Console.WriteLine("Press Enter to continue");
                        Console.ReadLine();
                        usrChoice = "0";
                    } //end print 2d matrix
                    if (usrChoice == "4")//if user wants to go on tour

                    {
                        Console.WriteLine("Which floor would you like to go?");
                        List <string> lst   = p0Context.FindAllFloors();
                        int           count = 0;
                        foreach (string str in lst)
                        {
                            Console.WriteLine($"\n{++count}. {str}");
                        }
                        int    floorNumberChoice = ValidationOptions.ValidateStringToInt(Console.ReadLine());
                        string floorName         = lst[--floorNumberChoice];

                        Console.WriteLine("What row of the museum floor would you like to visit? Please be nice and enter within expected range....for now.");
                        int usrRowChoice = ValidationOptions.ValidateStringToInt(Console.ReadLine());

                        Tour tour = new Tour();
                        tour = p0Context.FindTour(floorName, usrRowChoice);

                        bool tbool = p0Context.UserGoesOnTour(floorName);

                        if (tbool && tour != null)
                        {
                            Console.Clear();
                            p0Context.CreateFloorTourUsrLine(floorName, tour.TourID, u.UserID);
                            Console.WriteLine("Tour completed! We hope your pointer had fun!");
                        }

                        Console.WriteLine("\n\nPress enter to continue");
                        Console.ReadLine();//end decision 4
                    }//end go on tour
                }while(usrChoice != "-1");

                return("-2");
            }
Esempio n. 39
0
 /// <summary>
 /// Run data type validation on a specific value.
 /// <example>
 /// <code>
 /// using Mezzocode.Halide3;
 /// ...
 /// string result = h3Identify.Validate(
 ///		value,
 ///		h3Identify.ValidationOptions.Email,
 ///		false);
 /// </code>
 /// </example>
 /// <para>A common practice is to add error message fields underneath each of your form fields,
 /// and then use a single line to validate the input and display the error on the form, as well
 /// as set a global flag that identifies that there has been an error.</para>
 /// <example>
 /// <code>
 /// using Mezzocode.Halide3;
 /// ...
 /// errorFlag +=
 ///		EmailFieldErrorMessage.InnerHtml =
 ///			h3Identify.Validate(
 ///				EmailField.Value,
 ///				h3Identify.ValidationOptions.Email,
 ///				false);
 /// </code>
 /// </example>
 /// <para>In this way, you can check "errorFlag" to see if it's empty or null, in which case,
 /// there were no validation errors, otherwise, you know one or more validations failed.
 /// And in the same line, the error message for each field is filled with the error message,
 /// since ValidateItem() returns an empty string if the validation is successful, or a friendly
 /// error string if it fails.</para>
 /// </summary>
 /// <param name="value">Value to validate.</param>
 /// <param name="valType">Constant determining what type of validation.</param>
 /// <param name="opt">Field is optional. Zero length validates, otherwise, full validation occurs.</param>
 /// <returns>Empty string if validation succeeds, error message on failure.</returns>
 public static String Validate(string value, ValidationOptions valType, Boolean opt)
 {
     return Validate(value, valType, 0, 0, opt);
 }
 /// <summary>
 /// Constructs a new MarkupConstraint with the default MarkupValidatorClient settings.
 /// </summary>
 public MarkupConstraint(ValidationOptions options) : this(options, new MarkupValidatorClient()) { }