private void Push(JsonSchema value)
 {
     _currentSchema = value;
     _stack.Add(value);
     _resolver.LoadedSchemas.Add(value);
     _documentSchemas.Add(value.Location, value);
 }
            public TypeSchema(Type type, JsonSchema schema)
            {
                ValidationUtils.ArgumentNotNull(type, "type");
                ValidationUtils.ArgumentNotNull(schema, "schema");

                Type = type;
                Schema = schema;
            }
        private JsonSchema Pop()
        {
            JsonSchema poppedSchema = _currentSchema;
            _stack.RemoveAt(_stack.Count - 1);
            _currentSchema = _stack.LastOrDefault();

            return poppedSchema;
        }
        /// <summary>
        /// Determines whether the <see cref="JToken"/> is valid.
        /// </summary>
        /// <param name="source">The source <see cref="JToken"/> to test.</param>
        /// <param name="schema">The schema to test with.</param>
        /// <param name="errorMessages">When this method returns, contains any error messages generated while validating. </param>
        /// <returns>
        ///     <c>true</c> if the specified <see cref="JToken"/> is valid; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsValid(this JToken source, JsonSchema schema, out IList<string> errorMessages)
        {
            IList<string> errors = new List<string>();

            source.Validate(schema, (sender, args) => errors.Add(args.Message));

            errorMessages = errors;
            return (errorMessages.Count == 0);
        }
 private void ReferenceOrWriteSchema(JsonSchema schema)
 {
     if (schema.Id != null && _resolver.GetSchema(schema.Id) != null)
     {
         _writer.WriteStartObject();
         _writer.WritePropertyName(JsonTypeReflector.RefPropertyName);
         _writer.WriteValue(schema.Id);
         _writer.WriteEndObject();
     }
     else
     {
         WriteSchema(schema, false);
     }
 }
 /// <summary>
 /// Determines whether the <see cref="JToken"/> is valid.
 /// </summary>
 /// <param name="source">The source <see cref="JToken"/> to test.</param>
 /// <param name="schema">The schema to test with.</param>
 /// <returns>
 ///     <c>true</c> if the specified <see cref="JToken"/> is valid; otherwise, <c>false</c>.
 /// </returns>
 public static bool IsValid(this JToken source, JsonSchema schema)
 {
     bool valid = true;
     source.Validate(schema, (sender, args) => { valid = false; });
     return valid;
 }
 private void Push(TypeSchema typeSchema)
 {
     _currentSchema = typeSchema.Schema;
     _stack.Add(typeSchema);
     _resolver.LoadedSchemas.Add(typeSchema.Schema);
 }
        private void WriteItems(JsonSchema schema)
        {
            if (schema.Items == null && !schema.PositionalItemsValidation)
                return;

            _writer.WritePropertyName(JsonSchemaConstants.ItemsPropertyName);

            if (!schema.PositionalItemsValidation)
            {
                if (schema.Items != null && schema.Items.Count > 0)
                {
                    ReferenceOrWriteSchema(schema.Items[0]);
                }
                else
                {
                    _writer.WriteStartObject();
                    _writer.WriteEndObject();
                }
                return;
            }

            _writer.WriteStartArray();
            if (schema.Items != null)
            {
                foreach (JsonSchema itemSchema in schema.Items)
                {
                    ReferenceOrWriteSchema(itemSchema);
                }
            }
            _writer.WriteEndArray();
        }
        private TypeSchema Pop()
        {
            TypeSchema popped = _stack[_stack.Count - 1];
            _stack.RemoveAt(_stack.Count - 1);
            TypeSchema newValue = _stack.LastOrDefault();
            if (newValue != null)
            {
                _currentSchema = newValue.Schema;
            }
            else
            {
                _currentSchema = null;
            }

            return popped;
        }
        private IDictionary<string, JsonSchema> ProcessDependencies(JToken token)
        {
            IDictionary<string, JsonSchema> dependencies = new Dictionary<string, JsonSchema>();

            foreach (JProperty dependencyToken in token)
            {
                if (dependencies.ContainsKey(dependencyToken.Name))
                    throw new JsonException("Dependency {0} has already been defined in schema.".FormatWith(CultureInfo.InvariantCulture, dependencyToken.Name));

                switch (dependencyToken.Value.Type)
                {
                    case JTokenType.String:
                        JsonSchema singleProperty = new JsonSchema { Type = JsonSchemaType.Object };
                        singleProperty.Required = new List<string> { (string)dependencyToken.Value };
                        singleProperty.Properties = new Dictionary<string, JsonSchema>();
                        singleProperty.Properties.Add((string)dependencyToken.Value, new JsonSchema() { Type = JsonSchemaType.Any });
                        dependencies.Add(dependencyToken.Name, singleProperty);
                        break;
                    case JTokenType.Array:
                        JsonSchema multipleProperty = new JsonSchema { Type = JsonSchemaType.Object };
                        multipleProperty.Required = new List<string>();
                        multipleProperty.Properties = new Dictionary<string, JsonSchema>();
                        foreach (JToken schemaToken in dependencyToken.Value)
                        {
                            multipleProperty.Required.Add((string)schemaToken);
                            multipleProperty.Properties.Add((string)schemaToken, new JsonSchema() { Type = JsonSchemaType.Any });
                        }
                        dependencies.Add(dependencyToken.Name, multipleProperty);
                        break;
                    case JTokenType.Object:
                        dependencies.Add(dependencyToken.Name, BuildSchema(dependencyToken.Value));
                        break;
                    default:
                        throw JsonException.Create(token, token.Path, "Expected string, array or JSON schema object, got {0}.".FormatWith(CultureInfo.InvariantCulture, token.Type));

                }
            }

            return dependencies;
        }
Beispiel #11
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>
 public static void Validate(this JToken source, JsonSchema schema)
 {
     source.Validate(schema, null);
 }
Beispiel #12
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, JsonSchema schema, ValidationEventHandler validationEventHandler)
        {
            ValidationUtils.ArgumentNotNull(source, "source");
            ValidationUtils.ArgumentNotNull(schema, "schema");

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

                while (reader.Read())
                {
                }
            }
        }
        private JsonSchema BuildSchema(JToken token)
        {
            JObject schemaObject = token as JObject;
            if (schemaObject == null)
                throw JsonException.Create(token, token.Path, "Expected object while parsing schema object, got {0}.".FormatWith(CultureInfo.InvariantCulture, token.Type));

            // Check for change of scope before processing
            JToken idToken;
            bool hasPushedScope = false;
            if (schemaObject.TryGetValue(JsonSchemaConstants.IdPropertyName, out idToken))
            {
                string subScope = (string)idToken;
                Uri scopeUri;

                hasPushedScope = true;

                if (string.IsNullOrEmpty(_currentResolutionScope))
                {
                    PushScope(subScope);
                }
                else
                {
                    scopeUri = new Uri(_currentResolutionScope, UriKind.RelativeOrAbsolute);
                    Uri subScopeUri = new Uri(subScope, UriKind.RelativeOrAbsolute);

                    if (subScopeUri.IsAbsoluteUri)
                    {
                        PushScope(subScopeUri.ToString());
                    }
                    else
                    {
                        Uri combinedUri = new Uri(scopeUri, subScope);
                        PushScope(combinedUri.ToString());
                    }
                }
            }

            JToken referenceToken;
            if (schemaObject.TryGetValue(JsonTypeReflector.RefPropertyName, out referenceToken))
            {
                JsonSchema deferredSchema = new JsonSchema();
                deferredSchema.DeferredReference = (string)referenceToken;
                deferredSchema.ResolutionScope = _currentResolutionScope;

                return deferredSchema;
            }

            string location = token.Path.Replace(".", "/").Replace("[", "/").Replace("]", string.Empty);
            if (!string.IsNullOrEmpty(location))
                location = "/" + location;

            location = _currentResolutionScope + "#" + location;

            JsonSchema existingSchema;
            if (_documentSchemas.TryGetValue(location, out existingSchema))
                return existingSchema;

            Push(new JsonSchema { Location = location });

            ProcessSchemaProperties(schemaObject);

            if (hasPushedScope)
                PopScope();

            return Pop();
        }
        public void WriteSchema(JsonSchema schema)
        {
            ValidationUtils.ArgumentNotNull(schema, "schema");

            WriteSchema(schema, true);
        }
        private bool IsPropertyDefinied(JsonSchema schema, string propertyName)
        {
            if (schema.Properties != null && schema.Properties.ContainsKey(propertyName))
                return true;

            if (schema.PatternProperties != null)
            {
                foreach (string pattern in schema.PatternProperties.Keys)
                {
                    if (Regex.IsMatch(propertyName, pattern))
                        return true;
                }
            }

            return false;
        }
 private void AddConditionalSchemas(IList<SchemaReport> currentSchemas, JsonSchema schema, SchemaReport parentResultSet)
 {
     AddConditionalSchemas(currentSchemas, schema.AllOf, SchemaConditionType.AllOf, parentResultSet);
     AddConditionalSchemas(currentSchemas, schema.OneOf, SchemaConditionType.OneOf, parentResultSet);
     AddConditionalSchemas(currentSchemas, schema.AnyOf, SchemaConditionType.AnyOf, parentResultSet);
     if (schema.NotOf != null)
     {
         AddConditionalSchemas(currentSchemas, new List<JsonSchema> { schema.NotOf }, SchemaConditionType.NotOf, parentResultSet);
     }
     if (schema.Dependencies != null)
     {
         foreach (KeyValuePair<string, JsonSchema> dep in schema.Dependencies)
         {
             SchemaReport childResultSet = new SchemaReport(dep.Value, new List<JsonSchemaException>(), SchemaConditionType.Dependency, parentResultSet, dep.Key);
             currentSchemas.Add(childResultSet);
             parentResultSet.SubResults.Add(childResultSet);
             AddConditionalSchemas(currentSchemas, dep.Value, childResultSet);
         }
     }
 }
 public SchemaReport(JsonSchema schema, IList<JsonSchemaException> messages, SchemaConditionType type, SchemaReport parent, string conditionalPropertyName)
 {
     Schema = schema;
     Messages = messages;
     ConditionType = type;
     ConditionalPropertyName = conditionalPropertyName;
     SubResults = new List<SchemaReport>();
     if (parent != null && parent.Messages != null)
         Parent = parent;
 }
        public void WriteSchema(JsonSchema schema, bool isRoot)
        {
            if (!_resolver.LoadedSchemas.Contains(schema))
                _resolver.LoadedSchemas.Add(schema);

            _writer.WriteStartObject();
            WritePropertyIfNotNull(_writer, JsonSchemaConstants.IdPropertyName, schema.Id);
            if (isRoot)
                WritePropertyIfNotNull(_writer, JsonSchemaConstants.SchemaTypePropertyName, JsonSchemaConstants.SchemaTypePropertyValue);
            WritePropertyIfNotNull(_writer, JsonSchemaConstants.TitlePropertyName, schema.Title);
            WritePropertyIfNotNull(_writer, JsonSchemaConstants.DescriptionPropertyName, schema.Description);
            WritePropertyIfNotNull(_writer, JsonSchemaConstants.ReadOnlyPropertyName, schema.ReadOnly);
            WritePropertyIfNotNull(_writer, JsonSchemaConstants.HiddenPropertyName, schema.Hidden);
            WritePropertyIfNotNull(_writer, JsonSchemaConstants.TransientPropertyName, schema.Transient);
            if (schema.Type != null)
                WriteType(JsonSchemaConstants.TypePropertyName, _writer, schema.Type.Value);
            if (!schema.AllowAdditionalProperties)
            {
                _writer.WritePropertyName(JsonSchemaConstants.AdditionalPropertiesPropertyName);
                _writer.WriteValue(schema.AllowAdditionalProperties);
            }
            else
            {
                if (schema.AdditionalProperties != null)
                {
                    _writer.WritePropertyName(JsonSchemaConstants.AdditionalPropertiesPropertyName);
                    ReferenceOrWriteSchema(schema.AdditionalProperties);
                }
            }
            if (!schema.AllowAdditionalItems)
            {
                _writer.WritePropertyName(JsonSchemaConstants.AdditionalItemsPropertyName);
                _writer.WriteValue(schema.AllowAdditionalItems);
            }
            else
            {
                if (schema.AdditionalItems != null)
                {
                    _writer.WritePropertyName(JsonSchemaConstants.AdditionalItemsPropertyName);
                    ReferenceOrWriteSchema(schema.AdditionalItems);
                }
            }
            WriteSchemaDictionaryIfNotNull(_writer, JsonSchemaConstants.PropertiesPropertyName, schema.Properties);
            if (schema.Required != null && schema.Required.Count > 0)
            {
                _writer.WritePropertyName(JsonSchemaConstants.RequiredPropertyName);
                _writer.WriteStartArray();
                foreach (string propertyName in schema.Required)
                {
                    _writer.WriteValue(propertyName);
                }
                _writer.WriteEndArray();
            }
            WriteSchemaDictionaryIfNotNull(_writer, JsonSchemaConstants.PatternPropertiesPropertyName, schema.PatternProperties);
            WriteItems(schema);
            WritePropertyIfNotNull(_writer, JsonSchemaConstants.MinimumPropertyName, schema.Minimum);
            WritePropertyIfNotNull(_writer, JsonSchemaConstants.MaximumPropertyName, schema.Maximum);
            WritePropertyIfNotNull(_writer, JsonSchemaConstants.MinimumPropertiesPropertyName, schema.MinimumProperties);
            WritePropertyIfNotNull(_writer, JsonSchemaConstants.MaximumPropertiesPropertyName, schema.MaximumProperties);
            WritePropertyIfNotNull(_writer, JsonSchemaConstants.ExclusiveMinimumPropertyName, schema.ExclusiveMinimum);
            WritePropertyIfNotNull(_writer, JsonSchemaConstants.ExclusiveMaximumPropertyName, schema.ExclusiveMaximum);
            WritePropertyIfNotNull(_writer, JsonSchemaConstants.MinimumLengthPropertyName, schema.MinimumLength);
            WritePropertyIfNotNull(_writer, JsonSchemaConstants.MaximumLengthPropertyName, schema.MaximumLength);
            WritePropertyIfNotNull(_writer, JsonSchemaConstants.MinimumItemsPropertyName, schema.MinimumItems);
            WritePropertyIfNotNull(_writer, JsonSchemaConstants.MaximumItemsPropertyName, schema.MaximumItems);
            WritePropertyIfNotNull(_writer, JsonSchemaConstants.MultipleOfPropertyName, schema.MultipleOf);
            WritePropertyIfNotNull(_writer, JsonSchemaConstants.FormatPropertyName, schema.Format);
            WritePropertyIfNotNull(_writer, JsonSchemaConstants.PatternPropertyName, schema.Pattern);
            if (schema.Enum != null)
            {
                _writer.WritePropertyName(JsonSchemaConstants.EnumPropertyName);
                _writer.WriteStartArray();
                foreach (JToken token in schema.Enum)
                {
                    token.WriteTo(_writer);
                }
                _writer.WriteEndArray();
            }
            if (schema.Default != null)
            {
                _writer.WritePropertyName(JsonSchemaConstants.DefaultPropertyName);
                schema.Default.WriteTo(_writer);
            }
            WriteSchemaDictionaryIfNotNull(_writer, JsonSchemaConstants.DependenciesPropertyName, schema.Dependencies);
            if (schema.AnyOf != null && schema.AnyOf.Count > 0)
            {
                _writer.WritePropertyName(JsonSchemaConstants.AnyOfPropertyName);
                _writer.WriteStartArray();
                foreach (JsonSchema jsonSchema in schema.AnyOf)
                {
                    ReferenceOrWriteSchema(jsonSchema);
                }
                _writer.WriteEndArray();
            }
            if (schema.AllOf != null && schema.AllOf.Count > 0)
            {
                _writer.WritePropertyName(JsonSchemaConstants.AllOfPropertyName);
                _writer.WriteStartArray();
                foreach (JsonSchema jsonSchema in schema.AllOf)
                {
                    ReferenceOrWriteSchema(jsonSchema);
                }
                _writer.WriteEndArray();
            }
            if (schema.OneOf != null && schema.OneOf.Count > 0)
            {
                _writer.WritePropertyName(JsonSchemaConstants.OneOfPropertyName);
                _writer.WriteStartArray();
                foreach (JsonSchema jsonSchema in schema.OneOf)
                {
                    ReferenceOrWriteSchema(jsonSchema);
                }
                _writer.WriteEndArray();
            }
            if (schema.NotOf != null)
            {
                _writer.WritePropertyName(JsonSchemaConstants.NotOfPropertyName);
                ReferenceOrWriteSchema(schema.NotOf);
            }
            if (schema.Links != null && schema.Links.Count > 0)
            {
                _writer.WritePropertyName(JsonSchemaConstants.LinksPropertyName);
                _writer.WriteStartArray();
                foreach (JsonSchemaLink link in schema.Links)
                {
                    _writer.WriteStartObject();
                    WritePropertyIfNotNull(_writer, JsonSchemaConstants.TitlePropertyName, link.Title);
                    WritePropertyIfNotNull(_writer, JsonSchemaConstants.RelationPropertyName, link.Relation);
                    WritePropertyIfNotNull(_writer, JsonSchemaConstants.HrefPropertyName, link.Href);
                    if (link.TargetSchema != null)
                    {
                        _writer.WritePropertyName(JsonSchemaConstants.TargetSchemaPropertyName);
                        ReferenceOrWriteSchema(link.TargetSchema);
                    }
                    WritePropertyIfNotNull(_writer, JsonSchemaConstants.MediaTypePropertyName, link.MediaType);
                    if (!JsonSchemaConstants.DefaultRequestMethod.Equals(link.Method, System.StringComparison.OrdinalIgnoreCase))
                        WritePropertyIfNotNull(_writer, JsonSchemaConstants.MethodPropertyName, link.Method);
                    if (!JsonSchemaConstants.JsonContentType.Equals(link.EncodingType, System.StringComparison.OrdinalIgnoreCase))
                        WritePropertyIfNotNull(_writer, JsonSchemaConstants.EncodingTypePropertyName, link.EncodingType);
                    if (link.Schema != null)
                    {
                        _writer.WritePropertyName(JsonSchemaConstants.SchemaPropertyName);
                        ReferenceOrWriteSchema(link.Schema);
                    }
                    _writer.WriteEndObject();
                }
                _writer.WriteEndArray();

            }
            if (!JsonSchemaConstants.JsonPointerProtocol.Equals(schema.FragmentResolution, System.StringComparison.OrdinalIgnoreCase))
                WritePropertyIfNotNull(_writer, JsonSchemaConstants.FragmentResolutionPropertyName, schema.FragmentResolution);
            if (schema.Media != null)
            {
                _writer.WritePropertyName(JsonSchemaConstants.MediaPropertyName);
                _writer.WriteStartObject();
                WritePropertyIfNotNull(_writer, JsonSchemaConstants.BinaryEncodingPropertyName, schema.Media.BinaryEncoding);
                WritePropertyIfNotNull(_writer, JsonSchemaConstants.TypePropertyName, schema.Media.Type);
                _writer.WriteEndObject();
            }
            WritePropertyIfNotNull(_writer, JsonSchemaConstants.PathStartPropertyName, schema.PathStart);
            _writer.WriteEndObject();
        }
        private JsonSchema ResolveReferences(JsonSchema schema)
        {
            while (schema.DeferredReference != null)
            {
                string schemaUri;
                string idPath;
                bool isJsonPointer;

                PrepareLocationReference(schema.ResolutionScope, schema.DeferredReference, out schemaUri, out idPath, out isJsonPointer);

                JsonSchema resolvedSchema;

                if (isJsonPointer)
                {
                    string reference = schemaUri + UnescapeReference(idPath);
                    resolvedSchema = _resolver.GetSchema(reference);

                    if (resolvedSchema == null)
                    {
                        resolvedSchema = FindLocationReference(schemaUri, idPath);
                    }
                }
                else
                {
                    resolvedSchema = _resolver.GetSchema(idPath);
                }

                if (resolvedSchema == null)
                    throw new JsonException("Could not resolve schema reference '{0}'.".FormatWith(CultureInfo.InvariantCulture, schema.DeferredReference));

                schema = resolvedSchema;
            }

            if (schema.ReferencesResolved)
                return schema;

            schema.ReferencesResolved = true;

            if (schema.AnyOf != null)
            {
                for (int i = 0; i < schema.AnyOf.Count; i++)
                {
                    schema.AnyOf[i] = ResolveReferences(schema.AnyOf[i]);
                }
            }

            if (schema.AllOf != null)
            {
                for (int i = 0; i < schema.AllOf.Count; i++)
                {
                    schema.AllOf[i] = ResolveReferences(schema.AllOf[i]);
                }
            }

            if (schema.OneOf != null)
            {
                for (int i = 0; i < schema.OneOf.Count; i++)
                {
                    schema.OneOf[i] = ResolveReferences(schema.OneOf[i]);
                }
            }

            if (schema.NotOf != null)
                schema.NotOf = ResolveReferences(schema.NotOf);

            if (schema.Items != null)
            {
                for (int i = 0; i < schema.Items.Count; i++)
                {
                    schema.Items[i] = ResolveReferences(schema.Items[i]);
                }
            }

            if (schema.AdditionalItems != null)
                schema.AdditionalItems = ResolveReferences(schema.AdditionalItems);

            if (schema.PatternProperties != null)
            {
                foreach (KeyValuePair<string, JsonSchema> patternProperty in schema.PatternProperties.ToList())
                {
                    schema.PatternProperties[patternProperty.Key] = ResolveReferences(patternProperty.Value);
                }
            }

            if (schema.Properties != null)
            {
                foreach (KeyValuePair<string, JsonSchema> property in schema.Properties.ToList())
                {
                    schema.Properties[property.Key] = ResolveReferences(property.Value);
                }
            }

            if (schema.AdditionalProperties != null)
                schema.AdditionalProperties = ResolveReferences(schema.AdditionalProperties);

            return schema;
        }