public void RaiseError(ValidationError error)
        {
            // shared cache information that could be read/populated from multiple threads
            // lock to ensure that only one thread writes known schemas
            if (!_knownSchemasPopulated)
            {
                lock (Schema.KnownSchemas)
                {
                    if (!_knownSchemasPopulated)
                    {
                        if (Schema.KnownSchemas.Count == 0)
                        {
                            JSchemaDiscovery discovery = new JSchemaDiscovery(Schema, Schema.KnownSchemas, KnownSchemaState.External);
                            discovery.Discover(Schema, null);
                        }

                        _knownSchemasPopulated = true;
                    }
                }
            }

            PopulateSchemaId(error);

            SchemaValidationEventHandler handler = ValidationEventHandler;

            if (handler != null)
            {
                handler(_publicValidator, new SchemaValidationEventArgs(error));
            }
            else
            {
                throw JSchemaValidationException.Create(error);
            }
        }
        private static bool Validate <T>(T jServants, out string message)
        {
            IList <string> comments = new List <string>();

            StringWriter            stringWriter     = new StringWriter();
            JsonTextWriter          writer           = new JsonTextWriter(stringWriter);
            JSchemaValidatingWriter validatingWriter = new JSchemaValidatingWriter(writer);

            validatingWriter.Schema = Schema;
            JsonSerializer serializer = new JsonSerializer();

            List <string> messages = new List <string>();
            SchemaValidationEventHandler handler =
                delegate(object sender, SchemaValidationEventArgs e)
            {
                if (e.Message.StartsWith("Value null is not defined in enum"))
                {
                    return;
                }
                messages.Add(e.Message);
            };

            validatingWriter.ValidationEventHandler += handler;

            serializer.Serialize(validatingWriter, jServants);


            bool res = messages.Count == 0;

            message = string.Join(" ", messages);
            return(res);
        }
Beispiel #3
0
        public void RaiseError(IFormattable message, ErrorType errorType, JSchema schema, object value, IList <ValidationError> childErrors)
        {
            ValidationError error = CreateError(message, errorType, schema, value, childErrors);

            // shared cache information that could be read/populated from multiple threads
            // lock to ensure that only one thread writes known schemas
            if (Schema.KnownSchemas.Count == 0)
            {
                lock (Schema.KnownSchemas)
                {
                    if (Schema.KnownSchemas.Count == 0)
                    {
                        JSchemaDiscovery discovery = new JSchemaDiscovery(Schema.KnownSchemas, KnownSchemaState.External);
                        discovery.Discover(Schema, null);
                    }
                }
            }

            PopulateSchemaId(error);

            SchemaValidationEventHandler handler = ValidationEventHandler;

            if (handler != null)
            {
                handler(_publicValidator, new SchemaValidationEventArgs(error));
            }
            else
            {
                throw JSchemaValidationException.Create(error);
            }
        }
Beispiel #4
0
        public void Validate()
        {
            List <string> errors = null;

            SchemaValidationEventHandler handler = new SchemaValidationEventHandler(HandleEvent);

            if (!string.IsNullOrEmpty(schemaNoPrefix))
            {
                JObject xSchemaToken = JObject.Parse(schemaNoPrefix);
                JSchema schema       = JSchema.Parse(JsonConvert.SerializeObject(xSchemaToken));
                JObject json         = JObject.Parse(inputJsonString);
                try
                {
                    json.Validate(schema, handler);
                }
                catch (Exception e)
                {
                    if (errors == null)
                    {
                        errors = new List <string>();
                    }
                    errors.Add(e.Message);
                }
            }
            if (schemaCollection != null)
            {
                foreach (KeyValuePair <string, string> schemaPair in schemaCollection)
                {
                    JObject xSchemaToken = JObject.Parse(schemaPair.Value);
                    PrefixKey(xSchemaToken, schemaPair.Key);
                    JSchema schema = JSchema.Parse(JsonConvert.SerializeObject(xSchemaToken));
                    JObject json   = JObject.Parse(inputJsonString);
                    try
                    {
                        json.Validate(schema, handler);
                    }
                    catch (Exception e)
                    {
                        if (errors == null)
                        {
                            errors = new List <string>();
                        }
                        errors.Add(e.Message);
                    }
                }
            }

            if (errors != null)
            {
                throw new Exception(string.Join(" AND ", errors.ToArray()));
            }
        }
        private void ValidateObject(object obj, JSchema schema, SchemaValidationEventHandler validationEventHandler)
        {
            var jsonReader = obj is JObject jo?jo.CreateReader() : new IgnoreStrongTypeObjectJsonReader(obj);

            using var reader = new JSchemaValidatingReader(jsonReader);
            reader.Schema    = schema;
            if (validationEventHandler != null)
            {
                reader.ValidationEventHandler += validationEventHandler;
            }
            while (reader.Read())
            {
            }
        }
Beispiel #6
0
 private void ValidateObject(object obj, SchemaValidationEventHandler validationEventHandler)
 {
     using (var reader = new JSchemaValidatingReader(new ObjectJsonReader(obj)))
     {
         reader.Schema = _jSchema;
         if (validationEventHandler != null)
         {
             reader.ValidationEventHandler += validationEventHandler;
         }
         while (reader.Read())
         {
         }
     }
 }
        public void RaiseError(string message, ErrorType errorType, JSchema schema, object value, IList <ValidationError> childErrors)
        {
            ValidationError error = CreateError(message, errorType, schema, value, childErrors);

            SchemaValidationEventHandler handler = ValidationEventHandler;

            if (handler != null)
            {
                handler(_publicValidator, new SchemaValidationEventArgs(error));
            }
            else
            {
                throw JSchemaException.Create(message, error);
            }
        }
        /// <summary>
        /// Validates the specified <see cref="JToken"/>.
        /// </summary>
        /// <param name="source">The source <see cref="JToken"/> to test.</param>
        /// <param name="schema">The schema to test with.</param>
        /// <param name="validationEventHandler">The validation event handler.</param>
        public static void Validate(this JToken source, JSchema schema, SchemaValidationEventHandler validationEventHandler)
        {
            ValidationUtils.ArgumentNotNull(source, "source");
            ValidationUtils.ArgumentNotNull(schema, "schema");

            using (JSchemaValidatingReader reader = new JSchemaValidatingReader(source.CreateReader()))
            {
                reader.Schema = schema;
                if (validationEventHandler != null)
                    reader.ValidationEventHandler += validationEventHandler;

                while (reader.Read())
                {
                }
            }
        }
Beispiel #9
0
        public JSchemaReader(JSchemaReaderSettings settings)
        {
            Cache           = new Dictionary <Uri, JSchema>(UriComparer.Instance);
            _deferedSchemas = new List <DeferedSchema>();
            _schemaStack    = new Stack <JSchema>();

            _resolver               = settings.Resolver ?? JSchemaDummyResolver.Instance;
            _baseUri                = settings.BaseUri;
            _validateSchema         = settings.ValidateVersion;
            _schemaDiscovery        = new JSchemaDiscovery();
            _validationEventHandler = settings.GetValidationEventHandler();

            if (_validationEventHandler != null)
            {
                _validationErrors = new List <ValidationError>();
                _schemaDiscovery.ValidationErrors = _validationErrors;
            }
        }
Beispiel #10
0
        /// <summary>
        /// Validates the specified <see cref="JToken"/>.
        /// </summary>
        /// <param name="source">The source <see cref="JToken"/> to test.</param>
        /// <param name="schema">The schema to test with.</param>
        /// <param name="validationEventHandler">The validation event handler.</param>
        public static void Validate(this JToken source, JSchema schema, SchemaValidationEventHandler validationEventHandler)
        {
            ValidationUtils.ArgumentNotNull(source, nameof(source));
            ValidationUtils.ArgumentNotNull(schema, nameof(schema));

            using (JSchemaValidatingReader reader = new JSchemaValidatingReader(source.CreateReader()))
            {
                reader.Schema = schema;
                if (validationEventHandler != null)
                {
                    reader.ValidationEventHandler += validationEventHandler;
                }

                while (reader.Read())
                {
                }
            }
        }
Beispiel #11
0
 public JsonTree(MainWindow window)
     : base(window)
 {
     _jsonSerializer.Formatting = Formatting.Indented;
     _jsonSerializer.Converters.Add(new JsonNodeConverter());
     _validationEventHandler = (sender, args) =>
     {
         ImGui.PushStyleColor(ColorTarget.Text, new System.Numerics.Vector4(1, 0, 0, 1));
         ImGui.SameLine(ImGui.GetColumnWidth(0) - 16 - ImGui.GetStyle().FramePadding.X);
         ImGui.Text(FontAwesome5.ExclamationCircle);
         if (ImGui.IsItemHovered(HoveredFlags.Default))
         {
             ImGuiNative.igBeginTooltip();
             ImGui.Text(ValidationErrorStringConverter.Convert(args.ValidationErrors[0], args.Node));
             ImGuiNative.igEndTooltip();
         }
         ImGui.PopStyleColor();
     };
 }
Beispiel #12
0
        public void Example()
        {
            #region Usage
            string schemaJson = @"{
              'description': 'A person',
              'type': 'object',
              'properties': {
                'name': {'type':'string'},
                'hobbies': {
                  'type': 'array',
                  'items': {'type':'string'}
                }
              }
            }";

            JSchema schema = JSchema.Parse(schemaJson);

            JObject person = JObject.Parse(@"{
              'name': null,
              'hobbies': ['Invalid content', 0.123456789]
            }");

            IList <string> messages = new List <string>();
            SchemaValidationEventHandler validationEventHandler = (sender, args) => messages.Add(args.Message);

            person.Validate(schema, validationEventHandler);

            foreach (string message in messages)
            {
                Console.WriteLine(message);
            }
            // Invalid type. Expected String but got Null. Line 2, position 21.
            // Invalid type. Expected String but got Float. Line 3, position 51.
            #endregion

            Assert.AreEqual(2, messages.Count);
        }
Beispiel #13
0
 internal void SetValidationEventHandler(SchemaValidationEventHandler handler)
 {
     _validationEventHandler = handler;
 }
 internal void SetValidationEventHandler(SchemaValidationEventHandler handler)
 {
     _validationEventHandler = handler;
 }