public void IsValidMessages()
        {
            string schemaJson = @"{
              'description': 'A person',
              'type': 'object',
              'properties': {
                'name': {'type': 'string'},
                'hobbies': {
                  'type': 'array',
                  'items': {'type': 'string'}
                }
              }
            }";

            #region IsValidMessages
            JSchema schema = JSchema.Parse(schemaJson);

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

            IList <string> messages;
            bool           valid = person.IsValid(schema, out messages);
            // Invalid type. Expected String but got Null. Line 2, position 21.
            // Invalid type. Expected String but got Number. Line 3, position 51.
            #endregion

            Assert.IsFalse(valid);
        }
        public void JSchemaValidatingWriter()
        {
            string schemaJson = "{}";

            #region JSchemaValidatingWriter
            Person person = new Person
            {
                Name    = "James",
                Hobbies = new List <string>
                {
                    ".NET", "Blogging", "Reading", "Xbox", "LOLCATS"
                }
            };

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

            JSchemaValidatingWriter validatingWriter = new JSchemaValidatingWriter(writer);
            validatingWriter.Schema = JSchema.Parse(schemaJson);

            IList <string> messages = new List <string>();
            validatingWriter.ValidationEventHandler += (o, a) => messages.Add(a.Message);

            JsonSerializer serializer = new JsonSerializer();
            serializer.Serialize(validatingWriter, person);
            #endregion

            Assert.AreEqual(0, messages.Count);
        }
        public void IsValidBasic()
        {
            #region IsValidBasic
            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': 'James',
              'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS']
            }");

            bool valid = person.IsValid(schema);
            // true
            #endregion

            Assert.IsTrue(valid);
        }
        public void SchemaIdGenerationHandlingTest()
        {
            #region SchemaIdGenerationHandling
            JSchemaGenerator generator = new JSchemaGenerator();

            // types with no defined ID have their type name as the ID
            generator.SchemaIdGenerationHandling = SchemaIdGenerationHandling.TypeName;

            JSchema schema = generator.Generate(typeof(Person));
            //{
            //  "id": "Person",
            //  "type": "object",
            //  "properties": {
            //    "name": {
            //      "type": [ "string", "null" ]
            //    },
            //    "age": { "type": "integer" }
            //  },
            //  "required": [ "name", "age" ]
            //}
            #endregion

            Assert.AreEqual(JSchemaType.Object, schema.Type);
            Assert.AreEqual("Person", schema.Id.OriginalString);
        }
        public void IsValidValidationError()
        {
            #region IsValidValidationError
            string schemaJson = @"{
              'description': 'Collection of non-primary colors',
              'type': 'array',
              'items': {
                'allOf': [ { '$ref': '#/definitions/hexColor' } ],
                'not': {
                  'enum': ['#FF0000','#00FF00','#0000FF']
                }
              },
              'definitions': {
                'hexColor': {
                  'type': 'string',
                  'pattern': '^#[A-Fa-f0-9]{6}$'
                }
              }
            }";

            JSchema schema = JSchema.Parse(schemaJson);

            JArray colors = JArray.Parse(@"[
              '#DAA520', // goldenrod
              '#FF69B4', // hot pink
              '#0000FF', // blue
              'Black'
            ]");

            IList <ValidationError> errors;
            bool valid = colors.IsValid(schema, out errors);
            // Message - JSON is valid against schema from 'not'. Path '[2]', line 4, position 24.
            // SchemaId - #/items/0

            // Message - JSON does not match all schemas from 'allOf'. Invalid schema indexes: 0. Path '[3]', line 5, position 22.
            // SchemaId - #/items/0
            //   Message - String 'Black' does not match regex pattern '^#[A-Fa-f0-9]{6}$'. Path '[3]', line 5, position 22.
            //   SchemaId - #/definitions/hexColor
            #endregion

            Assert.IsFalse(valid);
        }
        public void JSchemaGenerationProvider()
        {
            #region JSchemaGenerationProvider
            JSchemaGenerator generator = new JSchemaGenerator();

            JSchema schema = generator.Generate(typeof(BuildingReport));
            //{
            //  "type": "object",
            //  "properties": {
            //    "Date": {
            //      "type": "string"
            //    },
            //    "Zone": {
            //      "type": "integer",
            //      "enum": [ 0, 1, 2 ]
            //    }
            //  },
            //  "required": [ "Date", "Zone" ]
            //}

            // change Zone enum to generate a string property
            JSchemaGenerator stringEnumGenerator = new JSchemaGenerator();
            stringEnumGenerator.GenerationProviders.Add(new StringEnumGenerationProvider());

            JSchema stringEnumSchema = stringEnumGenerator.Generate(typeof(BuildingReport));
            //{
            //  "type": "object",
            //  "properties": {
            //    "Date": {
            //      "type": "string"
            //    },
            //    "Zone": {
            //      "type": "string",
            //      "enum": [ "Residential", "Commercial", "Industrial" ]
            //    }
            //  },
            //  "required": [ "Date", "Zone" ]
            //}
            #endregion

            Assert.AreEqual(JSchemaType.Object, schema.Type);
        }
        public void BasicGeneration()
        {
            #region BasicGeneration
            JSchemaGenerator generator = new JSchemaGenerator();

            JSchema schema = generator.Generate(typeof(Person));
            //{
            //  "type": "object",
            //  "properties": {
            //    "Name": {
            //      "type": [ "string", "null" ]
            //    },
            //    "Age": { "type": "integer" }
            //  },
            //  "required": [ "Name", "Age" ]
            //}
            #endregion

            Assert.AreEqual(JSchemaType.Object, schema.Type);
        }
        public void JSchemaValidatingReader()
        {
            string schemaJson = "{}";

            #region JSchemaValidatingReader
            string json = @"{
              'name': 'James',
              'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS']
            }";

            JsonTextReader reader = new JsonTextReader(new StringReader(json));

            JSchemaValidatingReader validatingReader = new JSchemaValidatingReader(reader);
            validatingReader.Schema = JSchema.Parse(schemaJson);

            IList <string> messages = new List <string>();
            validatingReader.ValidationEventHandler += (o, a) => messages.Add(a.Message);

            JsonSerializer serializer = new JsonSerializer();
            Person         p          = serializer.Deserialize <Person>(validatingReader);
            #endregion

            Assert.AreEqual(0, messages.Count);
        }
        public void IContractResolver()
        {
            #region IContractResolver
            JSchemaGenerator generator = new JSchemaGenerator();

            // change contract resolver so property names are camel case
            generator.ContractResolver = new CamelCasePropertyNamesContractResolver();

            JSchema schema = generator.Generate(typeof(Person));
            //{
            //  "type": "object",
            //  "properties": {
            //    "name": {
            //      "type": [ "string", "null" ]
            //    },
            //    "age": { "type": "integer" }
            //  },
            //  "required": [ "name", "age" ]
            //}
            #endregion

            Assert.AreEqual(JSchemaType.Object, schema.Type);
            Assert.AreEqual(true, schema.Properties.ContainsKey("name"));
        }
        public void DataAnnotations()
        {
            #region DataAnnotations
            JSchemaGenerator generator = new JSchemaGenerator();

            JSchema schema = generator.Generate(typeof(Building));
            //{
            //  "type": "object",
            //  "properties": {
            //    "Name": {
            //      "type": "string",
            //      "maxLength": 100
            //    },
            //    "PhoneNumber": {
            //      "type": "string",
            //      "format": "phone"
            //    },
            //    "Zone": {
            //      "type": "string",
            //      "enum": [
            //        "Residential",
            //        "Commercial",
            //        "Industrial"
            //      ]
            //    }
            //  },
            //  "required": [
            //    "Name",
            //    "PhoneNumber",
            //    "Zone"
            //  ]
            //}
            #endregion

            Assert.AreEqual(JSchemaType.Object, schema.Type);
        }
        public void ParseString()
        {
            #region ParseString
            string schemaJson = @"{
              'description': 'A person',
              'type': 'object',
              'properties':
              {
                'name': {'type':['string','null']},
                'hobbies': {
                  'type': 'array',
                  'items': {'type':'string'}
                }
              }
            }";

            JSchema schema = JSchema.Parse(schemaJson);

            // validate JSON
            #endregion

            Assert.AreEqual(JSchemaType.Object, schema.Type);
            Assert.AreEqual(JSchemaType.String | JSchemaType.Null, schema.Properties["name"].Type);
        }