public void ArrayBasicValidation_Pass()
        {
            JSchema schema = new JSchema();
            schema.Type = JSchemaType.Array;
            schema.Items.Add(new JSchema
            {
                Type = JSchemaType.Integer
            });

            SchemaValidationEventArgs a = null;

            StringWriter sw = new StringWriter();
            JsonTextWriter writer = new JsonTextWriter(sw);
            JSchemaValidatingWriter validatingWriter = new JSchemaValidatingWriter(writer);
            validatingWriter.Schema = schema;
            validatingWriter.ValidationEventHandler += (sender, args) => { a = args; };

            validatingWriter.WriteStartArray();
            validatingWriter.WriteValue(10);
            validatingWriter.WriteValue(10);
            validatingWriter.WriteEndArray();

            Assert.IsNull(a);

            Assert.AreEqual("[10,10]", sw.ToString());
        }
        public override void RaiseError(string message, ErrorType errorType, JSchema schema, object value, IList<ValidationError> childErrors)
        {
            if (Errors == null)
                Errors = new List<ValidationError>();

            Errors.Add(Validator.CreateError(message, errorType, schema, value, childErrors));
        }
        /// <summary>
        /// Gets a <see cref="JSchema"/> for a <see cref="Type"/>.
        /// </summary>
        /// <param name="context">The <see cref="Type"/> and associated information used to generate a <see cref="JSchema"/>.</param>
        /// <returns>The generated <see cref="JSchema"/>.</returns>
        public override JSchema GetSchema(JSchemaTypeGenerationContext context)
        {
            bool isNullable = ReflectionUtils.IsNullableType(context.ObjectType);
            Type t = isNullable ? Nullable.GetUnderlyingType(context.ObjectType) : context.ObjectType;

            if (!t.IsEnum())
            {
                return null;
            }

            JSchema schema = new JSchema
            {
                Type = JSchemaType.String
            };

            if (isNullable && context.Required != Required.Always)
            {
                schema.Type |= JSchemaType.Null;
            }

            string[] names = Enum.GetNames(t);

            foreach (string name in names)
            {
                string finalName = EnumUtils.ToEnumName(t, name, CamelCaseText);

                schema.Enum.Add(JValue.CreateString(finalName));
            }

            return schema;
        }
예제 #4
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);
        }
        public void WriteTo_ReferenceWithRootId()
        {
            JSchema nested = new JSchema
            {
                Type = JSchemaType.Object
            };

            JSchema s = new JSchema();
            s.Id = new Uri("http://www.jnk.com/");
            s.Items.Add(nested);
            s.Properties["test"] = nested;

            string json = s.ToString();

            StringAssert.AreEqual(@"{
  ""id"": ""http://www.jnk.com/"",
  ""properties"": {
    ""test"": {
      ""type"": ""object""
    }
  },
  ""items"": {
    ""$ref"": ""#/properties/test""
  }
}", json);
        }
예제 #6
0
        protected ValidationError CreateError(string message, ErrorType errorType, JSchema schema, object value, IList<ValidationError> childErrors, IJsonLineInfo lineInfo, string path)
        {
            if (_schemaDiscovery == null)
            {
                _schemaDiscovery = new JSchemaDiscovery();
                _schemaDiscovery.Discover(Schema, null);
            }

            ValidationError error = new ValidationError();
            error.Message = message;
            error.ErrorType = errorType;
            error.Path = path;
            if (lineInfo != null)
            {
                error.LineNumber = lineInfo.LineNumber;
                error.LinePosition = lineInfo.LinePosition;
            }
            error.Schema = schema;
            error.SchemaId = _schemaDiscovery.KnownSchemas.Single(s => s.Schema == schema).Id;
            error.SchemaBaseUri = schema.BaseUri;
            error.Value = value;
            error.ChildErrors = childErrors;

            return error;
        }
        private void DiscoverInternal(JSchema schema, string latestPath)
        {
            if (schema.Reference != null)
                return;

            if (_knownSchemas.Any(s => s.Schema == schema))
                return;

            Uri newScopeId;
            Uri schemaKnownId = GetSchemaIdAndNewScopeId(schema, ref latestPath, out newScopeId);

            // check whether a schema with the resolved id is already known
            // this will be hit when a schema contains duplicate ids or references a schema with a duplicate id
            bool existingSchema = _knownSchemas.Any(s => UriComparer.Instance.Equals(s.Id, schemaKnownId));

#if DEBUG
            if (_knownSchemas.Any(s => s.Schema == schema))
                throw new InvalidOperationException("Schema with id '{0}' already a known schema.".FormatWith(CultureInfo.InvariantCulture, schemaKnownId));
#endif

            // add schema to known schemas whether duplicate or not to avoid multiple errors
            // the first schema with a duplicate id will be used
            _knownSchemas.Add(new KnownSchema(schemaKnownId, schema, _state));

            if (existingSchema)
            {
                if (ValidationErrors != null)
                {
                    ValidationError error = ValidationError.CreateValidationError("Duplicate schema id '{0}' encountered.".FormatWith(CultureInfo.InvariantCulture, schemaKnownId.OriginalString), ErrorType.Id, schema, null, schemaKnownId, null, schema, schema.Path);
                    ValidationErrors.Add(error);
                }

                return;
            }

            _pathStack.Push(new SchemaPath(newScopeId, latestPath));

            // discover should happen in the same order as writer except extension data (e.g. definitions)
            if (schema._extensionData != null)
            {
                foreach (KeyValuePair<string, JToken> valuePair in schema._extensionData)
                {
                    DiscoverTokenSchemas(EscapePath(valuePair.Key), valuePair.Value);
                }
            }

            DiscoverSchema(Constants.PropertyNames.AdditionalProperties, schema.AdditionalProperties);
            DiscoverSchema(Constants.PropertyNames.AdditionalItems, schema.AdditionalItems);
            DiscoverDictionarySchemas(Constants.PropertyNames.Properties, schema._properties);
            DiscoverDictionarySchemas(Constants.PropertyNames.PatternProperties, schema._patternProperties);
            DiscoverDictionarySchemas(Constants.PropertyNames.Dependencies, schema._dependencies);
            DiscoverArraySchemas(Constants.PropertyNames.Items, schema._items);
            DiscoverArraySchemas(Constants.PropertyNames.AllOf, schema._allOf);
            DiscoverArraySchemas(Constants.PropertyNames.AnyOf, schema._anyOf);
            DiscoverArraySchemas(Constants.PropertyNames.OneOf, schema._oneOf);
            DiscoverSchema(Constants.PropertyNames.Not, schema.Not);

            _pathStack.Pop();
        }
        public static SchemaScope CreateTokenScope(JsonToken token, JSchema schema, ContextBase context, Scope parent, int depth)
        {
            SchemaScope scope;

            switch (token)
            {
                case JsonToken.StartObject:
                    var objectScope = new ObjectScope(context, parent, depth, schema);
                    context.Scopes.Add(objectScope);

                    objectScope.InitializeScopes(token);

                    scope = objectScope;
                    break;
                case JsonToken.StartArray:
                case JsonToken.StartConstructor:
                    scope = new ArrayScope(context, parent, depth, schema);
                    context.Scopes.Add(scope);
                    break;
                default:
                    scope = new PrimativeScope(context, parent, depth, schema);
                    context.Scopes.Add(scope);
                    break;
            }

            if (schema._allOf != null && schema._allOf.Count > 0)
            {
                AllOfScope allOfScope = new AllOfScope(scope, context, depth);
                context.Scopes.Add(allOfScope);

                allOfScope.InitializeScopes(token, schema._allOf);
            }
            if (schema._anyOf != null && schema._anyOf.Count > 0)
            {
                AnyOfScope anyOfScope = new AnyOfScope(scope, context, depth);
                context.Scopes.Add(anyOfScope);

                anyOfScope.InitializeScopes(token, schema._anyOf);
            }
            if (schema._oneOf != null && schema._oneOf.Count > 0)
            {
                OneOfScope oneOfScope = new OneOfScope(scope, context, depth);
                context.Scopes.Add(oneOfScope);

                oneOfScope.InitializeScopes(token, schema._oneOf);
            }
            if (schema.Not != null)
            {
                NotScope notScope = new NotScope(scope, context, depth);
                context.Scopes.Add(notScope);

                notScope.InitializeScopes(token, Enumerable.Repeat(schema.Not, 1));
            }

            return scope;
        }
        public void Discover(JSchema schema, Uri uri, string path = "#")
        {
            Uri resolvedUri = uri ?? schema.Id ?? new Uri(string.Empty, UriKind.RelativeOrAbsolute);

            _pathStack.Push(new SchemaPath(resolvedUri, string.Empty));

            DiscoverInternal(schema, path);

            _pathStack.Pop();
        }
        public void SetResolvedSchema(JSchema schema)
        {
            foreach (Action<JSchema> setSchema in SetSchemas)
            {
                setSchema(schema);
            }

            // successful
            _success = (schema.Reference == null);
        }
예제 #11
0
        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 JSchemaValidationException.Create(error);
        }
        public void WriteTo_MaximumLength_Large()
        {
            JSchema s = new JSchema
            {
                MaximumLength = long.MaxValue
            };

            string json = s.ToString();

            StringAssert.AreEqual(@"{
  ""maxLength"": 9223372036854775807
}", json);
        }
        public void WriteTo_UniqueItems()
        {
            JSchema s = new JSchema
            {
                UniqueItems = true
            };

            string json = s.ToString();

            StringAssert.AreEqual(@"{
  ""uniqueItems"": true
}", json);
        }
        public void Example()
        {
            #region Usage
            JSchema schema = new JSchema
            {
                Type = JSchemaType.Object,
                Properties =
                {
                    { "name", new JSchema { Type = JSchemaType.String } },
                    {
                        "hobbies", new JSchema
                        {
                            Type = JSchemaType.Array,
                            Items = { new JSchema { Type = JSchemaType.String } }
                        }
                    },
                }
            };

            string schemaJson = schema.ToString();

            Console.WriteLine(schemaJson);
            // {
            //   "type": "object",
            //   "properties": {
            //     "name": {
            //       "type": "string"
            //     },
            //     "hobbies": {
            //       "type": "array",
            //       "items": {
            //         "type": "string"
            //       }
            //     }
            //   }
            // }

            JObject person = JObject.Parse(@"{
              'name': 'James',
              'hobbies': ['.NET', 'Blogging', 'Reading', 'Xbox', 'LOLCATS']
            }");

            bool valid = person.IsValid(schema);

            Console.WriteLine(valid);
            // true
            #endregion

            Assert.IsTrue(valid);
        }
예제 #15
0
        public ObjectScope(ContextBase context, Scope parent, int initialDepth, JSchema schema)
            : base(context, parent, initialDepth, schema)
        {
            if (schema._required != null)
                _requiredProperties = schema._required.ToList();

            if (schema._dependencies != null && schema._dependencies.Count > 0)
            {
                _readProperties = new List<string>();

                if (schema._dependencies.Values.OfType<JSchema>().Any())
                    _dependencyScopes = new Dictionary<string, SchemaScope>();
            }
        }
예제 #16
0
        protected ValidationError CreateError(string message, ErrorType errorType, JSchema schema, object value, IList<ValidationError> childErrors, IJsonLineInfo lineInfo, string path)
        {
            if (_schemaDiscovery == null)
            {
                _schemaDiscovery = new JSchemaDiscovery();
                _schemaDiscovery.Discover(Schema, null);
            }

            Uri schemaId = _schemaDiscovery.KnownSchemas.Single(s => s.Schema == schema).Id;

            ValidationError error = ValidationError.CreateValidationError(message, errorType, schema, schemaId, value, childErrors, lineInfo, path);

            return error;
        }
예제 #17
0
        public void Initialize(ContextBase context, Scope parent, int initialDepth, JSchema schema)
        {
            Initialize(context, parent, initialDepth, ScopeType.Object);
            InitializeSchema(schema);

            _propertyCount = 0;
            _currentPropertyName = null;

            if (!schema._required.IsNullOrEmpty())
            {
                if (_requiredProperties != null)
                {
                    _requiredProperties.Clear();
                }
                else
                {
                    _requiredProperties = new List<string>(schema._required.Count);
                }

                foreach (string required in schema._required)
                {
                    _requiredProperties.Add(required);
                }
            }

            if (!schema._dependencies.IsNullOrEmpty())
            {
                if (_readProperties != null)
                {
                    _readProperties.Clear();
                }
                else
                {
                    _readProperties = new List<string>();
                }

                if (schema._dependencies.HasSchemas)
                {
                    if (_dependencyScopes != null)
                    {
                        _dependencyScopes.Clear();
                    }
                    else
                    {
                        _dependencyScopes = new Dictionary<string, SchemaScope>(StringComparer.Ordinal);
                    }
                }
            }
        }
        public void SerializeSchema()
        {
            JSchema schema = new JSchema
            {
                Properties =
                {
                    { "first", new JSchema { Type = JSchemaType.String | JSchemaType.Null } }
                }
            };

            string s1 = schema.ToString();
            string s2 = JsonConvert.SerializeObject(schema, Formatting.Indented);

            Assert.AreEqual(s1, s2);
        }
예제 #19
0
        internal virtual void RaiseError(string message, ErrorType errorType, JSchema schema, object value, IList<ValidationError> childErrors)
        {
            // mark all parent SchemaScopes as invalid
            Scope current = this;
            SchemaScope parentSchemaScope;
            while ((parentSchemaScope = current.Parent as SchemaScope) != null)
            {
                if (!parentSchemaScope.IsValid)
                    break;

                parentSchemaScope.IsValid = false;
                current = parentSchemaScope;
            }

            Context.RaiseError(message, errorType, schema, value, childErrors);
        }
        public void WriteTo_ReferenceToPatternChild()
        {
            JSchema nested = new JSchema
            {
                Type = JSchemaType.Object
            };

            JSchema s = new JSchema();
            s.Id = new Uri("http://www.jnk.com/");
            s.Properties["pattern_parent"] = new JSchema
            {
                PatternProperties =
                {
                    { "///~~~test~/~/~", nested }
                }
            };
            s.Properties["ref_parent"] = new JSchema
            {
                Items =
                {
                    nested
                }
            };

            string json = s.ToString();

            StringAssert.AreEqual(@"{
  ""id"": ""http://www.jnk.com/"",
  ""properties"": {
    ""pattern_parent"": {
      ""patternProperties"": {
        ""///~~~test~/~/~"": {
          ""type"": ""object""
        }
      }
    },
    ""ref_parent"": {
      ""items"": {
        ""$ref"": ""#/properties/pattern_parent/patternProperties/~1~1~1~0~0~0test~0~1~0~1~0""
      }
    }
  }
}", json);
        }
예제 #21
0
        public void Initialize(ContextBase context, Scope parent, int initialDepth, JSchema schema)
        {
            Initialize(context, parent, initialDepth, ScopeType.Array);
            InitializeSchema(schema);

            _index = -1;

            if (schema.UniqueItems)
            {
                if (_uniqueArrayItems != null)
                {
                    _uniqueArrayItems.Clear();
                }
                else
                {
                    _uniqueArrayItems = new List<JToken>();
                }
            }
        }
        public void Example()
        {
            #region Usage
            JSchema schema = new JSchema
            {
                Type = JSchemaType.Object
            };

            // serialize JSchema to a string and then write string to a file
            File.WriteAllText(@"c:\schema.json", schema.ToString());

            // serialize JSchema directly to a file
            using (StreamWriter file = File.CreateText(@"c:\schema.json"))
            using (JsonTextWriter writer = new JsonTextWriter(file))
            {
                schema.WriteTo(writer);
            }
            #endregion
        }
예제 #23
0
        public ObjectScope(ContextBase context, Scope parent, int initialDepth, JSchema schema)
            : base(context, parent, initialDepth, schema)
        {
            if (schema._required != null)
                _requiredProperties = schema._required.ToList();

            if (schema._dependencies != null && schema._dependencies.Count > 0)
            {
                _readProperties = new List<string>();

                foreach (KeyValuePair<string, object> dependency in schema._dependencies)
                {
                    if (dependency.Value is JSchema)
                    {
                        _dependencyScopes = new Dictionary<string, SchemaScope>(StringComparer.Ordinal);
                        break;
                    }
                }
            }
        }
        public void SimpleTest()
        {
            JSchema prop = new JSchema();
            JSchema root = new JSchema
            {
                Properties =
                {
                    { "prop1", prop },
                    { "prop2", prop }
                }
            };

            JSchemaDiscovery discovery = new JSchemaDiscovery();
            discovery.Discover(root, null);

            Assert.AreEqual(2, discovery.KnownSchemas.Count);
            Assert.AreEqual(root, discovery.KnownSchemas[0].Schema);
            Assert.AreEqual(new Uri("#", UriKind.RelativeOrAbsolute), discovery.KnownSchemas[0].Id);
            Assert.AreEqual(prop, discovery.KnownSchemas[1].Schema);
            Assert.AreEqual(new Uri("#/properties/prop1", UriKind.RelativeOrAbsolute), discovery.KnownSchemas[1].Id);
        }
        public void ArrayBasicValidation_Fail()
        {
            JSchema schema = new JSchema();
            schema.Type = JSchemaType.Array;
            schema.Items.Add(new JSchema
            {
                Type = JSchemaType.Integer
            });

            SchemaValidationEventArgs a = null;

            StringWriter sw = new StringWriter();
            JsonTextWriter writer = new JsonTextWriter(sw);
            JSchemaValidatingWriter validatingWriter = new JSchemaValidatingWriter(writer);
            validatingWriter.Schema = schema;
            validatingWriter.ValidationEventHandler += (sender, args) =>
            {
                a = args;
            };

            validatingWriter.WriteStartArray();

            validatingWriter.WriteValue("string");
            Assert.IsNotNull(a);
            StringAssert.AreEqual("Invalid type. Expected Integer but got String. Path '[0]'.", a.Message);
            Assert.AreEqual("string", a.ValidationError.Value);
            a = null;

            validatingWriter.WriteValue(true);
            Assert.IsNotNull(a);
            StringAssert.AreEqual("Invalid type. Expected Integer but got Boolean. Path '[1]'.", a.Message);
            Assert.AreEqual(true, a.ValidationError.Value);
            a = null;

            validatingWriter.WriteEndArray();
            Assert.IsNull(a);

            Assert.AreEqual(@"[""string"",true]", sw.ToString());
        }
예제 #26
0
        // Async main requires c# 7.1 which is set in the csproj with the LangVersion attribute
        // <Main>
        public static async Task Main(string[] args)
        {
            IConfigurationRoot configuration = new ConfigurationBuilder()
                                               .AddJsonFile("appSettings.json")
                                               .Build();

            string endpoint = configuration["EndPointUrl"];

            if (string.IsNullOrEmpty(endpoint))
            {
                throw new ArgumentNullException("Please specify a valid endpoint in the appSettings.json");
            }

            string authKey = configuration["AuthorizationKey"];

            if (string.IsNullOrEmpty(authKey) || string.Equals(authKey, "Super secret key"))
            {
                throw new ArgumentException("Please specify a valid AuthorizationKey in the appSettings.json");
            }

            // Connecting to Emulator. Change if you want a live account
            CosmosClientBuilder cosmosClientBuilder = new CosmosClientBuilder(endpoint, authKey);

            // Declare a JSON schema to use with the schema validation handler
            var myContainerSchema = JSchema.Parse(@"{
  'type': 'object',
  'properties': {
    'name': {'type': 'string'}
  },
  'required': ['name']
}");

            cosmosClientBuilder.AddCustomHandlers(
                new LoggingHandler(),
                new ConcurrencyHandler(),
                new ThrottlingHandler(),
                new SchemaValidationHandler((database: "mydb", container: "mycoll2", schema: myContainerSchema))
                );

            CosmosClient client = cosmosClientBuilder.Build();

            DatabaseResponse databaseResponse = await client.CreateDatabaseIfNotExistsAsync("mydb");

            Database database = databaseResponse.Database;

            ContainerResponse containerResponse = await database.CreateContainerIfNotExistsAsync("mycoll", "/id");

            Container container = containerResponse.Container;

            Item item = new Item()
            {
                Id          = Guid.NewGuid().ToString(),
                Name        = "Test Item",
                Description = "Some random test item",
                Completed   = false
            };

            // Create
            await container.CreateItemAsync <Item>(item, new PartitionKey(item.Id));

            item.Completed = true;

            // Replace
            await container.ReplaceItemAsync <Item>(item, item.Id, new PartitionKey(item.Id));

            // Querying
            List <Item> results = new List <Item>();

            using (FeedIterator <Item> query = container.GetItemQueryIterator <Item>(new QueryDefinition("SELECT * FROM c"), requestOptions: new QueryRequestOptions()
            {
                MaxConcurrency = 1
            }))
            {
                while (query.HasMoreResults)
                {
                    FeedResponse <Item> response = await query.ReadNextAsync();

                    results.AddRange(response.ToList());
                }
            }

            // Read Item

            ItemResponse <Item> cosmosItemResponse = await container.ReadItemAsync <Item>(item.Id, new PartitionKey(item.Id));

            ItemRequestOptions itemRequestOptions = new ItemRequestOptions()
            {
                IfMatchEtag = cosmosItemResponse.ETag
            };

            // Concurrency

            List <Task <ItemResponse <Item> > > tasks = new List <Task <ItemResponse <Item> > >
            {
                UpdateItemForConcurrency(container, itemRequestOptions, item),
                UpdateItemForConcurrency(container, itemRequestOptions, item)
            };

            try
            {
                await Task.WhenAll(tasks);
            }
            catch (CosmosException ex)
            {
                // Verify that our custom handler caught the scenario
                Debug.Assert(999.Equals(ex.SubStatusCode));
            }

            // Delete
            await container.DeleteItemAsync <Item>(item.Id, new PartitionKey(item.Id));

            // Schema validation

            containerResponse = await database.CreateContainerIfNotExistsAsync("mycoll2", "/id");

            container = containerResponse.Container;

            // Insert an item with invalid schema
            var writeSucceeded = true;

            try
            {
                await container.CreateItemAsync(new { id = "12345" });
            }
            catch (InvalidItemSchemaException)
            {
                writeSucceeded = false;
            }
            Debug.Assert(!writeSucceeded);

            // Insert an item with valid schema
            try
            {
                await container.CreateItemAsync(new { id = "12345", name = "Youri" });

                writeSucceeded = true;
            }
            catch (InvalidItemSchemaException)
            {
                writeSucceeded = false;
            }
            Debug.Assert(writeSucceeded);

            // Update an item with invalid schema
            try
            {
                await container.ReplaceItemAsync(new { id = "12345" }, "12345");

                writeSucceeded = true;
            }
            catch (InvalidItemSchemaException)
            {
                writeSucceeded = false;
            }
            Debug.Assert(!writeSucceeded);

            // Update an item with valid schema
            try
            {
                await container.ReplaceItemAsync(new { id = "12345", name = "Vladimir" }, "12345");

                writeSucceeded = true;
            }
            catch (InvalidItemSchemaException)
            {
                writeSucceeded = false;
            }
            Debug.Assert(writeSucceeded);
        }
 private bool ValidateNull(JSchema schema, object value)
 {
     return(TestType(schema, JSchemaType.Null, value));
 }
        public void RootId_NestedId()
        {
            JSchema prop1 = new JSchema
            {
                Id    = new Uri("test.json/", UriKind.RelativeOrAbsolute),
                Items =
                {
                    new JSchema(),
                    new JSchema
                    {
                        Id    = new Uri("#fragmentItem2", UriKind.RelativeOrAbsolute),
                        Items =
                        {
                            new JSchema(),
                            new JSchema {
                                Id = new Uri("#fragmentItem2Item2",UriKind.RelativeOrAbsolute)
                            },
                            new JSchema {
                                Id = new Uri("file.json",UriKind.RelativeOrAbsolute)
                            },
                            new JSchema {
                                Id = new Uri("/file1.json",UriKind.RelativeOrAbsolute)
                            }
                        },
                        ItemsPositionValidation = true
                    }
                },
                ItemsPositionValidation = true
            };
            JSchema prop2 = new JSchema
            {
                Id  = new Uri("#fragment", UriKind.RelativeOrAbsolute),
                Not = new JSchema()
            };
            JSchema root = new JSchema
            {
                Id         = new Uri("http://localhost/", UriKind.RelativeOrAbsolute),
                Properties =
                {
                    { "prop1", prop1 },
                    { "prop2", prop2 }
                },
                ExtensionData =
                {
                    {
                        "definitions",
                        new JObject
                        {
                            { "def1", new JSchema() },
                            { "def2", new JSchema {
                                      Id = new Uri("def2.json", UriKind.RelativeOrAbsolute)
                                  } },
                            {
                                "defn",
                                new JArray
                                {
                                    new JValue(5),
                                    new JSchema()
                                }
                            }
                        }
                    }
                }
            };

            Console.WriteLine(root.ToString());

            JSchemaDiscovery discovery = new JSchemaDiscovery();

            discovery.Discover(root, null);

            int i = 0;

            foreach (KnownSchema knownSchema in discovery.KnownSchemas)
            {
                Console.WriteLine(knownSchema.Id);
            }

            Assert.AreEqual(new Uri("http://localhost/#", UriKind.RelativeOrAbsolute), discovery.KnownSchemas[i].Id);
            Assert.AreEqual(root, discovery.KnownSchemas[i++].Schema);

            Assert.AreEqual(new Uri("http://localhost/#/definitions/def1", UriKind.RelativeOrAbsolute), discovery.KnownSchemas[i].Id);
            Assert.AreEqual((JSchema)root.ExtensionData["definitions"]["def1"], discovery.KnownSchemas[i++].Schema);

            Assert.AreEqual(new Uri("http://localhost/def2.json", UriKind.RelativeOrAbsolute), discovery.KnownSchemas[i].Id);
            Assert.AreEqual((JSchema)root.ExtensionData["definitions"]["def2"], discovery.KnownSchemas[i++].Schema);

            Assert.AreEqual(new Uri("http://localhost/#/definitions/defn/1", UriKind.RelativeOrAbsolute), discovery.KnownSchemas[i].Id);
            Assert.AreEqual((JSchema)root.ExtensionData["definitions"]["defn"][1], discovery.KnownSchemas[i++].Schema);

            Assert.AreEqual(new Uri("http://localhost/test.json/", UriKind.RelativeOrAbsolute), discovery.KnownSchemas[i].Id);
            Assert.AreEqual(root.Properties["prop1"], discovery.KnownSchemas[i++].Schema);

            Assert.AreEqual(new Uri("http://localhost/test.json/#/items/0", UriKind.RelativeOrAbsolute), discovery.KnownSchemas[i].Id);
            Assert.AreEqual(root.Properties["prop1"].Items[0], discovery.KnownSchemas[i++].Schema);

            Assert.AreEqual(new Uri("http://localhost/test.json/#fragmentItem2", UriKind.RelativeOrAbsolute), discovery.KnownSchemas[i].Id);
            Assert.AreEqual(root.Properties["prop1"].Items[1], discovery.KnownSchemas[i++].Schema);

            Assert.AreEqual(new Uri("http://localhost/test.json/#fragmentItem2/items/0", UriKind.RelativeOrAbsolute), discovery.KnownSchemas[i].Id);
            Assert.AreEqual(root.Properties["prop1"].Items[1].Items[0], discovery.KnownSchemas[i++].Schema);

            Assert.AreEqual(new Uri("http://localhost/test.json/#fragmentItem2Item2", UriKind.RelativeOrAbsolute), discovery.KnownSchemas[i].Id);
            Assert.AreEqual(root.Properties["prop1"].Items[1].Items[1], discovery.KnownSchemas[i++].Schema);

            Assert.AreEqual(new Uri("http://localhost/test.json/file.json", UriKind.RelativeOrAbsolute), discovery.KnownSchemas[i].Id);
            Assert.AreEqual(root.Properties["prop1"].Items[1].Items[2], discovery.KnownSchemas[i++].Schema);

            Assert.AreEqual(new Uri("http://localhost/file1.json", UriKind.RelativeOrAbsolute), discovery.KnownSchemas[i].Id);
            Assert.AreEqual(root.Properties["prop1"].Items[1].Items[3], discovery.KnownSchemas[i++].Schema);

            Assert.AreEqual(new Uri("http://localhost/#fragment", UriKind.RelativeOrAbsolute), discovery.KnownSchemas[i].Id);
            Assert.AreEqual(root.Properties["prop2"], discovery.KnownSchemas[i++].Schema);

            Assert.AreEqual(new Uri("http://localhost/#fragment/not", UriKind.RelativeOrAbsolute), discovery.KnownSchemas[i].Id);
            Assert.AreEqual(root.Properties["prop2"].Not, discovery.KnownSchemas[i++].Schema);
        }
        public void MultipleNestedPaths()
        {
            string schemaJson = @"{
    ""$schema"": ""http://json-schema.org/draft-04/schema#"",
    ""type"": ""object"",
    ""title"": ""Quotes Configurator Schema"",
    ""description"": ""Defines the constraints for an acceptable JSON object required to produce a package"",
    ""properties"": {
       ""working_directory"" : { ""$ref"": ""#/definitions/working_directory"" },
       ""environment"" : { ""$ref"": ""#/definitions/environment"" },
        ""timezone"" : {
          ""description"": ""Timezone in in which processes are scheduled, does control the timezone in which they run"",
          ""type"": ""string""
       },
       ""cleanup_directories"" : {
          ""description"": ""Directories (and corresponding file types) which will be cleaned twice daily"",
          ""type"": ""object""
       },
       ""holiday_key"" : {
          ""description"": ""Holiday key which your package will follow"",
          ""type"": ""string""
       },
       ""cpu_alerting_threshold"" : {
          ""description"": ""Alerting threshold for high CPU usage"",
          ""type"": ""integer"",
          ""minimum"": 75,
          ""maximum"" : 250,
          ""multipleOf"" : 1
       },
       ""processes"" : { ""$ref"": ""#/definitions/processes"" },
       ""schedule"" : { ""$ref"": ""#/definitions/schedule"" }
    },
    ""additionalProperties"": false,
    ""required"": [
        ""working_directory"",
        ""timezone"",
        ""environment"",
        ""cleanup_directories"",
        ""processes"",
        ""schedule""
    ],
    ""definitions"": {
        ""nonEmptyWord"" : {
           ""type"" : ""string"",
           ""pattern"" : ""(^\\S+$)""
        },
        ""nonEmptyString"" : {
           ""type"" : ""string"",
           ""pattern"": ""(^\\S+(\\S|\\s)+$)""
        },
        ""dayShorthand"" : {
           ""type"" : ""string"",
           ""enum"" : [ ""Sun"", ""Mon"", ""Tue"", ""Wed"", ""Thu"", ""Fri"", ""Sat"" ]
        },
        ""twentyFourHourTime"" : {
           ""type"" : ""integer"",
           ""minimum"": 0,
           ""maximum"" : 235959,
           ""multipleOf"" : 1
        },
        ""environment"" : {
           ""description"": ""Global environment settings for each of the processes"",
           ""type"": ""object""
        },
        ""working_directory"" : {
           ""description"": ""Working directory for each process. Usually either root directory of your package or its etc/ directory"",
           ""type"": ""string"",
           ""pattern"": ""(^@\\w+@$)""
        },
        ""process"": {
           ""id"": ""process"",
           ""type"" : ""object"",
           ""properties"": {
              ""working_directory"" : { ""$ref"": ""../#/definitions/working_directory"" },
              ""environment"" : { ""$ref"": ""../#/definitions/environment"" },
              ""name"" : { ""$ref"": ""../#/definitions/nonEmptyWord"" },
              ""description"" : { ""$ref"": ""../#/definitions/nonEmptyString"" },
              ""ulimit"" : {
                 ""type"" : ""integer"",
                 ""multipleOf"": 256,
                 ""minimum"" : 256
              },
              ""alert_on_downtime"" : { ""type"" : ""boolean"" },
              ""starts_on_holiday"" : { ""type"" : ""boolean"" },
              ""check_for_completion"" : { ""type"" : ""boolean"" },
              ""arguments"" : {
                 ""type"" : ""array"",
                 ""items"" : { ""$ref"": ""../#/definitions/nonEmptyString"" },
                 ""minItems"": 1
              },
              ""stats_store_groups"" : {
                 ""type"" : ""array"",
                 ""items"" : { ""$ref"": ""../#/definitions/nonEmptyWord"" },
                 ""uniqueItems"" : true
              }
           },
           ""patternProperties"": {

              ""(^binary$|^module$|^external$|^bash$|^python$|^perl$)"" : { ""$ref"": ""../#/definitions/nonEmptyWord"" },
           },
           ""additionalProperties"": false,
           ""minProperties"": 5,
           ""maxProperties"": 12,
           ""allOf"" : [
             { ""required"": [ ""name"", ""ulimit"", ""alert_on_downtime"", ""starts_on_holiday"" ] },
             { ""oneOf"": [
               { ""required"" :  [ ""binary"" ] },
               { ""required"" :  [ ""module"" ] },
               { ""required"" :  [ ""external"" ] },
               { ""required"" :  [ ""bash"" ] },
               { ""required"" :  [ ""python"" ] },
               { ""required"" :  [ ""perl"" ] }
                ]
             }
           ]
        },
        ""processes"": {
          ""description"": ""All processes that are allowed to be run"",
          ""type"" : ""array"",
          ""items"" : { ""$ref"": ""#/definitions/process"" }
        },
        ""task"": {
          ""id"" : ""task"",
          ""type"" : ""object"",
          ""properties"" : {
             ""task_name"" : { ""$ref"": ""../#/definitions/nonEmptyWord"" },
             ""processes"" : {
                ""type"" : ""array""
             },
             ""runs_on""   : {
                ""type"" : ""array"",
                ""items"" : { ""$ref"": ""../#/definitions/dayShorthand"" },
                ""uniqueItems"" : true
             }
          },
          ""patternProperties"": {
             ""(^start_at$|^end_at$)"" : { ""$ref"": ""../#/definitions/twentyFourHourTime"" },
          },
          ""allOf"" : [
             { ""required"": [ ""task_name"", ""processes"", ""runs_on"" ] },
             { ""oneOf"" : [
                   {
                      ""anyOf"": [
                         { ""required"" :  [ ""start_at"" ] }
                      ]
                   },
                   {
                      ""anyOf"": [
                         { ""required"" :  [ ""end_at"" ] }
                      ]
                   }
                ]
             },
           ],
          ""additionalProperties"": false
        },
        ""schedule"": {
           ""description"": ""Separate tasks which consist of one or more processes and will run under your package"",
           ""type"" : ""array"",
           ""items"" : { ""$ref"": ""#/definitions/task"" }
        }
    }
}";

            JSchema schema = JSchema.Parse(schemaJson);

            JSchemaDiscovery discovery = new JSchemaDiscovery();

            discovery.Discover(schema, null);

            //for (int i = 0; i < discovery.KnownSchemas.Count; i++)
            //{
            //    KnownSchema knownSchema = discovery.KnownSchemas[i];

            //    Console.WriteLine(string.Format(@"Assert.AreEqual(""{0}"", discovery.KnownSchemas[{1}].Id.OriginalString);", knownSchema.Id, i));
            //}

            Assert.AreEqual("#", discovery.KnownSchemas[0].Id.OriginalString);
            Assert.AreEqual("#/definitions/nonEmptyWord", discovery.KnownSchemas[1].Id.OriginalString);
            Assert.AreEqual("#/definitions/nonEmptyString", discovery.KnownSchemas[2].Id.OriginalString);
            Assert.AreEqual("#/definitions/dayShorthand", discovery.KnownSchemas[3].Id.OriginalString);
            Assert.AreEqual("#/definitions/twentyFourHourTime", discovery.KnownSchemas[4].Id.OriginalString);
            Assert.AreEqual("#/definitions/environment", discovery.KnownSchemas[5].Id.OriginalString);
            Assert.AreEqual("#/definitions/working_directory", discovery.KnownSchemas[6].Id.OriginalString);
            Assert.AreEqual("process", discovery.KnownSchemas[7].Id.OriginalString);
            Assert.AreEqual("process#/properties/ulimit", discovery.KnownSchemas[8].Id.OriginalString);
            Assert.AreEqual("process#/properties/alert_on_downtime", discovery.KnownSchemas[9].Id.OriginalString);
            Assert.AreEqual("process#/properties/starts_on_holiday", discovery.KnownSchemas[10].Id.OriginalString);
            Assert.AreEqual("process#/properties/check_for_completion", discovery.KnownSchemas[11].Id.OriginalString);
            Assert.AreEqual("process#/properties/arguments", discovery.KnownSchemas[12].Id.OriginalString);
            Assert.AreEqual("process#/properties/stats_store_groups", discovery.KnownSchemas[13].Id.OriginalString);
            Assert.AreEqual("process#/allOf/0", discovery.KnownSchemas[14].Id.OriginalString);
            Assert.AreEqual("process#/allOf/1", discovery.KnownSchemas[15].Id.OriginalString);
            Assert.AreEqual("process#/allOf/1/oneOf/0", discovery.KnownSchemas[16].Id.OriginalString);
            Assert.AreEqual("process#/allOf/1/oneOf/1", discovery.KnownSchemas[17].Id.OriginalString);
            Assert.AreEqual("process#/allOf/1/oneOf/2", discovery.KnownSchemas[18].Id.OriginalString);
            Assert.AreEqual("process#/allOf/1/oneOf/3", discovery.KnownSchemas[19].Id.OriginalString);
            Assert.AreEqual("process#/allOf/1/oneOf/4", discovery.KnownSchemas[20].Id.OriginalString);
            Assert.AreEqual("process#/allOf/1/oneOf/5", discovery.KnownSchemas[21].Id.OriginalString);
            Assert.AreEqual("#/definitions/processes", discovery.KnownSchemas[22].Id.OriginalString);
            Assert.AreEqual("task", discovery.KnownSchemas[23].Id.OriginalString);
            Assert.AreEqual("task#/properties/processes", discovery.KnownSchemas[24].Id.OriginalString);
            Assert.AreEqual("task#/properties/runs_on", discovery.KnownSchemas[25].Id.OriginalString);
            Assert.AreEqual("task#/allOf/0", discovery.KnownSchemas[26].Id.OriginalString);
            Assert.AreEqual("task#/allOf/1", discovery.KnownSchemas[27].Id.OriginalString);
            Assert.AreEqual("task#/allOf/1/oneOf/0", discovery.KnownSchemas[28].Id.OriginalString);
            Assert.AreEqual("task#/allOf/1/oneOf/0/anyOf/0", discovery.KnownSchemas[29].Id.OriginalString);
            Assert.AreEqual("task#/allOf/1/oneOf/1", discovery.KnownSchemas[30].Id.OriginalString);
            Assert.AreEqual("task#/allOf/1/oneOf/1/anyOf/0", discovery.KnownSchemas[31].Id.OriginalString);
            Assert.AreEqual("#/definitions/schedule", discovery.KnownSchemas[32].Id.OriginalString);
            Assert.AreEqual("#/properties/timezone", discovery.KnownSchemas[33].Id.OriginalString);
            Assert.AreEqual("#/properties/cleanup_directories", discovery.KnownSchemas[34].Id.OriginalString);
            Assert.AreEqual("#/properties/holiday_key", discovery.KnownSchemas[35].Id.OriginalString);
            Assert.AreEqual("#/properties/cpu_alerting_threshold", discovery.KnownSchemas[36].Id.OriginalString);
        }
 protected abstract JSchema Customize(JSchemaTypeGenerationContext context, JsonContract contract, Type type, JSchema schema);
예제 #31
0
        public void WriteComplex()
        {
            JSchema schema = new JSchema();

            schema.Id   = new Uri("root", UriKind.RelativeOrAbsolute);
            schema.Type = JSchemaType.Boolean;

            JSchema file = new JSchema();

            file.Id = new Uri("file", UriKind.RelativeOrAbsolute);
            file.Properties.Add("blah", schema);
            file.ExtensionData["definitions"] = new JObject
            {
                { "parent", schema }
            };

            schema.Properties.Add("storage", file);
            schema.ExtensionData["definitions"] = new JObject
            {
                { "file", file },
                { "file2", file }
            };
            schema.Items.Add(new JSchema
            {
                Type = JSchemaType.Integer | JSchemaType.Null
            });
            schema.Items.Add(file);
            schema.ItemsPositionValidation = true;
            schema.Not = file;
            schema.AllOf.Add(file);
            schema.AllOf.Add(new JSchema
            {
                Type = JSchemaType.Integer | JSchemaType.Null
            });
            schema.AllOf.Add(file);
            schema.AnyOf.Add(file);
            schema.AnyOf.Add(new JSchema
            {
                Type = JSchemaType.Integer | JSchemaType.Null
            });
            schema.AnyOf.Add(schema);
            schema.OneOf.Add(file);
            schema.OneOf.Add(new JSchema
            {
                Type = JSchemaType.Integer | JSchemaType.Null
            });
            schema.OneOf.Add(schema);
            schema.Not = file;

            JSchema file2 = (JSchema)schema.ExtensionData["definitions"]["file"];

            Assert.AreEqual(file, file2);

            string json = schema.ToString(SchemaVersion.Draft4);

            StringAssert.AreEqual(@"{
  ""$schema"": ""http://json-schema.org/draft-04/schema#"",
  ""id"": ""root"",
  ""definitions"": {
    ""file"": {
      ""id"": ""file"",
      ""definitions"": {
        ""parent"": {
          ""$ref"": ""root""
        }
      },
      ""properties"": {
        ""blah"": {
          ""$ref"": ""root""
        }
      }
    },
    ""file2"": {
      ""$ref"": ""file""
    }
  },
  ""type"": ""boolean"",
  ""properties"": {
    ""storage"": {
      ""$ref"": ""file""
    }
  },
  ""items"": [
    {
      ""type"": [
        ""integer"",
        ""null""
      ]
    },
    {
      ""$ref"": ""file""
    }
  ],
  ""allOf"": [
    {
      ""$ref"": ""file""
    },
    {
      ""type"": [
        ""integer"",
        ""null""
      ]
    },
    {
      ""$ref"": ""file""
    }
  ],
  ""anyOf"": [
    {
      ""$ref"": ""file""
    },
    {
      ""type"": [
        ""integer"",
        ""null""
      ]
    },
    {
      ""$ref"": ""root""
    }
  ],
  ""oneOf"": [
    {
      ""$ref"": ""file""
    },
    {
      ""type"": [
        ""integer"",
        ""null""
      ]
    },
    {
      ""$ref"": ""root""
    }
  ],
  ""not"": {
    ""$ref"": ""file""
  }
}", json);
        }
예제 #32
0
        public static DocumentSchema Load(TextReader reader, string title)
        {
            DocumentSchema schema;

            using (var jtr = new JsonTextReader(reader))
            {
                JSchema jSchema;
                JObject jObject;
                try
                {
                    jObject = JObject.Load(jtr);
                    jSchema = JSchema.Load(jObject.CreateReader());
                }
                catch (Exception e) when(e is JSchemaException || e is JsonException)
                {
                    throw new InvalidSchemaException($"{title} is not a valid schema: {e.Message}", e);
                }

                var validator = new SchemaValidator(jObject, jSchema);

                // validate schema here
                validator.ValidateMetaSchema();

                try
                {
                    schema = LoadSchema <DocumentSchema>(jSchema, new Dictionary <JSchema, BaseSchema>());
                    schema.SchemaVersion = jSchema.SchemaVersion;
                    schema.Id            = jSchema.Id;
                    schema.Version       = GetValueFromJSchemaExtensionData <string>(jSchema, "version");
                    schema.Metadata      = GetValueFromJSchemaExtensionData <string>(jSchema, "metadata");
                    schema.Validator     = validator;
                }
                catch (Exception e)
                {
                    throw new InvalidSchemaException($"{title} is not a valid schema: {e.Message}", e);
                }

                if (string.IsNullOrWhiteSpace(schema.Title))
                {
                    if (string.IsNullOrWhiteSpace(title))
                    {
                        throw new InvalidSchemaException($"Title of schema must be specified.");
                    }
                    schema.Title = title;
                }

                if (schema.Type != JSchemaType.Object)
                {
                    throw new InvalidSchemaException("Type for the root schema object must be object");
                }

                if (!JsonPointer.TryCreate(schema.Metadata, out var pointer))
                {
                    throw new InvalidJsonPointerException($"Metadata's json pointer {schema.Metadata} is invalid.");
                }

                var metadataSchema = pointer.FindSchema(schema);
                if (metadataSchema != null && metadataSchema.Type != JSchemaType.Object)
                {
                    throw new InvalidJsonPointerException($"The referenced object is in type: {metadataSchema.Type}, only object can be a metadata reference");
                }

                schema.MetadataReference = pointer;
                schema.AllowOverwrite    = CheckOverwriteAbility(schema);
                schema.Hash = JsonUtility.Serialize(jObject).GetMd5String();

                return(schema);
            }
        }
예제 #33
0
        static void Main(string[] args)
        {
            var jsondata = @"{
                ""_id"": ""5cdb46266da15edda43c1464"",
                ""index"": 0,
                ""guid"": ""7878a6de-fc94-4efb-87c2-38614fa8543b"",
                ""isActive"": true,
                ""balance"": ""$3,932.58"",
                ""picture"": ""http://placehold.it/32x32"",
                ""age"": 20,
                ""eyeColor"": ""blue"",
                ""name"": ""Sharpe Faulkner"",
                ""gender"": ""male"",
                ""company"": ""GEEKETRON"",
                ""email"": ""*****@*****.**"",
                ""phone"": ""+1 (975) 544-2284"",
                ""address"": ""843 Surf Avenue, Alden, District Of Columbia, 1966"",
                ""about"": ""In tempor commodo est culpa anim. Anim ea amet veniam reprehenderit aliquip elit sit enim pariatur. Aliquip duis ex labore sunt eiusmod dolore veniam eu ex eiusmod. Esse consectetur minim cupidatat officia laboris sint nisi veniam aliqua. Ad duis culpa commodo consectetur Lorem ad officia nulla. Amet do excepteur pariatur occaecat exercitation cupidatat cupidatat aliqua exercitation consectetur.\r\n"",
                ""registered"": ""2019-02-20T06:45:46 +05:00"",
                ""latitude"": 17.76389,
                ""longitude"": 108.249262,
                ""tags"": [
                ""fugiat"",
                ""eu"",
                ""est"",
                ""eiusmod"",
                ""pariatur"",
                ""aliquip"",
                ""ex""
                ],
                ""friends"": [
                {
                    ""id"": 0,
                    ""name"": ""Leonard Davidson""
                },
                {
                    ""id"": 1,
                    ""name"": ""Allison Walton""
                },
                {
                    ""id"": 2,
                    ""name"": ""Spencer Nichols""
                }
                ],
                ""greeting"": ""Hello, Sharpe Faulkner! You have 8 unread messages."",
                ""favoriteFruit"": ""strawberry""
            }";

            JObject parsed = JObject.Parse(jsondata);

            foreach (JProperty p in parsed.Properties())
            {
                Console.WriteLine(p.Name + " - " + p.Value.Type);
            }

            Console.WriteLine("SCHEMA");
            JSchema schema = JSchema.Parse(jsondata);

            foreach (var property in schema.Properties)
            {
                Console.WriteLine(property.Key + " : " + property.Value.Type);
            }
        }
        /// <inheritdoc/>
        public virtual async Task <IOperationResult <Integration.Models.V1WorkflowInstance> > HandleAsync(V1CreateWorkflowInstanceCommand command, CancellationToken cancellationToken = default)
        {
            var workflow = await this.Workflows.FindAsync(command.WorkflowId, cancellationToken);

            if (workflow == null)
            {
                throw DomainException.NullReference(typeof(V1Workflow), command.WorkflowId);
            }
            var parent = null as V1WorkflowInstance;

            if (!string.IsNullOrWhiteSpace(command.ParentId))
            {
                parent = await this.WorkflowInstances.FindAsync(command.ParentId, cancellationToken);

                if (parent == null)
                {
                    throw DomainException.NullReference(typeof(V1WorkflowInstance), command.ParentId);
                }
            }
            string?key             = null;
            var    dataInputSchema = workflow.Definition.DataInputSchema?.Schema;

            if (dataInputSchema == null &&
                workflow.Definition.DataInputSchemaUri != null)
            {
                using var httpClient = this.HttpClientFactory.CreateClient();
                var json = await httpClient.GetStringAsync(workflow.Definition.DataInputSchemaUri, cancellationToken);

                dataInputSchema = JSchema.Parse(json);
            }
            if (dataInputSchema != null)
            {
                var     input = command.InputData;
                JObject?jobj;
                if (input == null)
                {
                    jobj = new JObject();
                }
                else
                {
                    jobj = JObject.FromObject(input);
                }
                if (!jobj.IsValid(dataInputSchema, out IList <string> errors))
                {
                    throw new DomainArgumentException($"Invalid workflow input data:{Environment.NewLine}{string.Join(Environment.NewLine, errors)}", nameof(command.InputData));
                }
            }
            if (!string.IsNullOrWhiteSpace(workflow.Definition.Key) &&
                command.InputData != null)
            {
                try
                {
                    key = this.ExpressionEvaluatorProvider.GetEvaluator(workflow.Definition.ExpressionLanguage) !.Evaluate(workflow.Definition.Key, command.InputData)?.ToString();
                }
                catch { }
            }
            if (string.IsNullOrWhiteSpace(key))
            {
                key = Guid.NewGuid().ToBase64();
            }
            while (await this.WorkflowInstances.ContainsAsync(V1WorkflowInstance.BuildUniqueIdentifier(key, workflow), cancellationToken))
            {
                key = Guid.NewGuid().ToBase64();
            }
            var workflowInstance = await this.WorkflowInstances.AddAsync(new(key.ToLowerInvariant(), workflow, command.ActivationType, command.InputData, command.CorrelationContext, parent), cancellationToken);

            await this.WorkflowInstances.SaveChangesAsync(cancellationToken);

            workflow.Instanciate();
            await this.Workflows.UpdateAsync(workflow, cancellationToken);

            await this.Workflows.SaveChangesAsync(cancellationToken);

            if (command.AutoStart)
            {
                await this.Mediator.ExecuteAndUnwrapAsync(new V1StartWorkflowInstanceCommand(workflowInstance.Id), cancellationToken);
            }
            return(this.Ok(this.Mapper.Map <Integration.Models.V1WorkflowInstance>(workflowInstance)));
        }
        private bool ValidateInteger(JSchema schema, object value)
        {
            if (!TestType(schema, JSchemaType.Integer, value))
                return false;

            if (schema.Maximum != null)
            {
                object v;
#if !(NET20 || NET35 || PORTABLE)
                v = (value is BigInteger) ? (double)(BigInteger)value : value;
#else
                v = value;
#endif

                if (JValue.Compare(JTokenType.Integer, v, schema.Maximum) > 0)
                    RaiseError($"Integer {value} exceeds maximum value of {schema.Maximum}.", ErrorType.Maximum, schema, value, null);
                if (schema.ExclusiveMaximum && JValue.Compare(JTokenType.Integer, v, schema.Maximum) == 0)
                    RaiseError($"Integer {value} equals maximum value of {schema.Maximum} and exclusive maximum is true.", ErrorType.Maximum, schema, value, null);
            }

            if (schema.Minimum != null)
            {
                object v;
#if !(NET20 || NET35 || PORTABLE)
                v = (value is BigInteger) ? (double)(BigInteger)value : value;
#else
                v = value;
#endif
                
                if (JValue.Compare(JTokenType.Integer, v, schema.Minimum) < 0)
                    RaiseError($"Integer {value} is less than minimum value of {schema.Minimum}.", ErrorType.Minimum, schema, value, null);
                if (schema.ExclusiveMinimum && JValue.Compare(JTokenType.Integer, v, schema.Minimum) == 0)
                    RaiseError($"Integer {value} equals minimum value of {schema.Minimum} and exclusive minimum is true.", ErrorType.Minimum, schema, value, null);
            }

            if (schema.MultipleOf != null)
            {
                bool notDivisible;
#if !(NET20 || NET35 || PORTABLE)
                if (value is BigInteger)
                {
                    double multipleOf = schema.MultipleOf.Value;

                    // not that this will lose any decimal point on MultipleOf
                    // so manually raise an error if MultipleOf is not an integer and value is not zero
                    BigInteger i = (BigInteger)value;
                    bool divisibleNonInteger = !Math.Abs(multipleOf - Math.Truncate(multipleOf)).Equals(0);
                    if (divisibleNonInteger)
                        notDivisible = i != 0;
                    else
                        notDivisible = i % new BigInteger(multipleOf) != 0;
                }
                else
#endif
                notDivisible = !MathHelpers.IsZero(Convert.ToInt64(value, CultureInfo.InvariantCulture) % schema.MultipleOf.Value);

                if (notDivisible)
                    RaiseError($"Integer {JsonConvert.ToString(value)} is not a multiple of {schema.MultipleOf}.", ErrorType.MultipleOf, schema, value, null);
            }

            return true;
        }
 private bool ValidateNull(JSchema schema, object value)
 {
     return TestType(schema, JSchemaType.Null, value);
 }
예제 #37
0
        protected ValidationError CreateError(IFormattable message, ErrorType errorType, JSchema schema, object?value, IList <ValidationError>?childErrors, IJsonLineInfo?lineInfo, string path)
        {
            ValidationError error = ValidationError.CreateValidationError(message, errorType, schema, null, value, childErrors, lineInfo, path);

            return(error);
        }
예제 #38
0
 public override bool CanValidate(JSchema schema)
 {
     return(true);
 }
예제 #39
0
        /// <summary>
        /// Validate a Json file against a Json schema using Json.Net
        /// </summary>
        /// <param name="jsonSchemaFile"></param>
        /// <param name="jsonFile"></param>
        /// <returns></returns>
        public static ValidationResult ValidateJsonFileAgainstSchema(string jsonSchemaFile, string jsonFile)
        {
            // Read the Json file
            string jsonSchemaContent = "";

            try
            {
                using (StreamReader sr = new StreamReader(jsonSchemaFile))
                {
                    jsonSchemaContent = sr.ReadToEnd();
                }
            }
            catch
            {
                // TBD
            }

            // Read the Json file
            string jsonFileContent = "";

            try
            {
                using (StreamReader sr = new StreamReader(jsonFile))
                {
                    jsonFileContent = sr.ReadToEnd();
                }
            }
            catch
            {
                // TBD
            }

            // Parse the content
            JSchema jsonSchema = new JSchema();

            try
            {
                jsonSchema = JSchema.Parse(jsonSchemaContent);
            }
            catch (Exception ex)
            {
                Console.WriteLine("An error has occured. The error message is: " + ex);
            }

            JToken jsonFileToken = "";

            try
            {
                jsonFileToken = JToken.Parse(jsonFileContent);
            }
            catch (Exception ex)
            {
                Console.WriteLine("An error has occured. The error message is: " + ex);
            }

            // Validate the file against the schema
            IList <ValidationError> errors;
            bool valid = jsonFileToken.IsValid(jsonSchema, out errors);

            // return outcome + errors and line info
            return(new ValidationResult
            {
                Valid = valid,
                Errors = errors
            });
        }
예제 #40
0
        public void WriteTo_Draft201909()
        {
            var defs = new JSchema {
                Title = "$defs"
            };

            JSchema schema = new JSchema
            {
                UnevaluatedItems = new JSchema {
                    Title = "UnevaluatedItems"
                },
                UnevaluatedProperties = new JSchema {
                    Title = "UnevaluatedProperties"
                },
                DependentSchemas =
                {
                    ["key"] = new JSchema(),
                    ["ref"] = defs
                },
                DependentRequired =
                {
                    ["key"] = new [] { "value" }
                },
                MinimumContains = 1,
                MaximumContains = 2,
                Anchor          = "Anchor",
                ExtensionData   =
                {
                    ["$defs"] = new JObject
                    {
                    ["name"] = defs
                    }
                },
                Ref = defs
            };
            string json = schema.ToString();

            string expected = @"{
  ""$anchor"": ""Anchor"",
  ""$defs"": {
    ""name"": {
      ""title"": ""$defs""
    }
  },
  ""unevaluatedProperties"": {
    ""title"": ""UnevaluatedProperties""
  },
  ""unevaluatedItems"": {
    ""title"": ""UnevaluatedItems""
  },
  ""minContains"": 1,
  ""maxContains"": 2,
  ""dependentSchemas"": {
    ""key"": {},
    ""ref"": {
      ""$ref"": ""#/$defs/name""
    }
  },
  ""dependentRequired"": {
    ""key"": [
      ""value""
    ]
  },
  ""$ref"": ""#/$defs/name""
}";

            StringAssert.AreEqual(expected, json);
        }
예제 #41
0
        public void OnGet()
        {
            String SearchString = HttpContext.Request.Query["SearchString"];
            String TeamString   = HttpContext.Request.Query["TeamString"];

            using (var webClient = new WebClient())
            {
                string InfoString = webClient.DownloadString("https://api.sportsdata.io/v3/soccer/stats/json/PlayerSeasonStats/383?key=bc49021bad1943008414c5a75e665961");

                JSchema        InfoSchema     = JSchema.Parse(System.IO.File.ReadAllText("PlayerInfoSchema.json"));
                JArray         InfoArray      = JArray.Parse(InfoString);
                IList <string> validationInfo = new List <string>();
                if (InfoArray.IsValid(InfoSchema, out validationInfo))
                {
                    var playerInfo = PlayerInfo.FromJson(InfoString);

                    ViewData["PlayerInfo"] = playerInfo;
                    var players = from m in playerInfo
                                  select m;
                    if (!string.IsNullOrEmpty(TeamString))
                    {
                        var seachple = players.Where(s => s.Team.Contains(TeamString));



                        ViewData["PlayerInfo"] = seachple.ToArray();
                    }
                }
                else
                {
                    foreach (string evtInfo in validationInfo)
                    {
                        Console.WriteLine(evtInfo);
                    }
                    ViewData["PlayerInfo"] = new List <PlayerInfo>();
                }



                string positionString = webClient.DownloadString("https://raw.githubusercontent.com/ShukiSaito/GroupProject/master/GroupProject/PlayersTeamAndSalary.json");

                //JObject jsonObject = JObject.Parse(playerPositionJson);
                // var myDeserializedClass = JsonConvert.DeserializeObject<Root>(jsonObject);

                JSchema        PositionSchema     = JSchema.Parse(System.IO.File.ReadAllText("PlayerPositionSchema.json"));
                JArray         PositionArray      = JArray.Parse(positionString);
                IList <string> validationPosition = new List <string>();
                if (PositionArray.IsValid(PositionSchema, out validationPosition))
                {
                    var playerPosition = PlayerPosition.FromJson(positionString);

                    ViewData["PlayerPosition"] = playerPosition;
                    var players = from m in playerPosition
                                  select m;
                    if (!string.IsNullOrEmpty(SearchString))
                    {
                        var seachple = players.Where(s => s.CommonName.Contains(SearchString));



                        ViewData["PlayerPosition"] = seachple.ToArray();
                    }
                }
                else
                {
                    foreach (string evtPosition in validationPosition)
                    {
                        Console.WriteLine(evtPosition);
                    }
                    ViewData["PlayerPosition"] = new List <PlayerPosition>();
                }
            }
        }
예제 #42
0
        public static async Task <List <ErrorViewModel> > ValidateAsync(string payload)
        {
            List <ErrorViewModel> errors = new List <ErrorViewModel>();

            JObject parsedObject = null;

            try
            {
                parsedObject = JObject.Parse(payload);
            }
            catch (JsonReaderException ex)
            {
                errors.Add(new ErrorViewModel()
                {
                    Message = "Parse error: " + ex.Message,
                    Type    = ErrorViewModelType.Error
                });
            }
            catch (Exception ex)
            {
                errors.Add(new ErrorViewModel()
                {
                    Message = "Parse error: " + ex.ToString(),
                    Type    = ErrorViewModelType.Error
                });
            }

            if (parsedObject != null)
            {
                string schema = null;
                try
                {
                    schema = await GetSchemaAsync();
                }
                catch { }

                if (schema != null)
                {
                    JSchema jsonSchema = null;

                    try
                    {
                        jsonSchema = JSchema.Parse(schema);
                    }
                    catch
                    {
                        // We don't report this error to user, it's a coding error
                        if (Debugger.IsAttached)
                        {
                            Debugger.Break();
                        }
                    }

                    if (jsonSchema != null)
                    {
                        parsedObject.IsValid(jsonSchema, out IList <ValidationError> validationErrors);

                        foreach (var error in validationErrors)
                        {
                            var err = error;
                            if (err.ChildErrors.Count > 0)
                            {
                                err = error.ChildErrors.Last();
                            }
                            var distinct = error.ChildErrors.Distinct().ToArray();

                            var finalErrors = GetLowestMostErrors(error).Distinct(new ErrorEqualityComparer()).ToArray();

                            var typeError = finalErrors.FirstOrDefault(i => i.Path.EndsWith(".type") && i.ErrorType == ErrorType.Enum);
                            if (typeError != null)
                            {
                                JObject definitions = jsonSchema.ExtensionData["definitions"] as JObject;
                                JObject definition  = definitions[typeError.Value.ToString()] as JObject;
                                if (definition != null)
                                {
                                    bool loggedErrorForType   = false;
                                    var  errorsSpecificToType = finalErrors.Where(i => object.Equals(i.Schema.Description, definition["description"]?.ToString())).ToArray();
                                    if (errorsSpecificToType.Length > 0)
                                    {
                                        foreach (var typeErrorChild in errorsSpecificToType)
                                        {
                                            if (typeErrorChild.ErrorType == ErrorType.Required && typeErrorChild.Message.StartsWith("Required properties are missing from object:"))
                                            {
                                                errors.Add(new ErrorViewModel()
                                                {
                                                    Message  = typeErrorChild.Message.Replace("Required properties are missing from object:", $"Required properties are missing from {typeError.Value}:"),
                                                    Type     = ErrorViewModelType.ErrorButRenderAllowed,
                                                    Position = GetPositionInfo(typeErrorChild)
                                                });
                                                loggedErrorForType = true;
                                            }
                                        }
                                    }

                                    foreach (var parseTypeError in finalErrors.Where(i => i.ErrorType == ErrorType.Type))
                                    {
                                        errors.Add(new ErrorViewModel()
                                        {
                                            Message  = parseTypeError.Message.Replace("Invalid type", $"Invalid value type on {typeError.Value}.{GetPropertyName(parseTypeError)}"),
                                            Type     = ErrorViewModelType.ErrorButRenderAllowed,
                                            Position = GetPositionInfo(typeError)
                                        });
                                        loggedErrorForType = true;
                                    }

                                    if (!loggedErrorForType)
                                    {
                                        errors.Add(new ErrorViewModel()
                                        {
                                            Message  = "Unknown properties or values inside " + typeError.Value.ToString(),
                                            Type     = ErrorViewModelType.Warning,
                                            Position = GetPositionInfo(typeError)
                                        });
                                    }
                                    continue;
                                }

                                errors.Add(new ErrorViewModel()
                                {
                                    Message  = "Invalid type: " + typeError.Value.ToString(),
                                    Type     = ErrorViewModelType.Warning,
                                    Position = GetPositionInfo(typeError)
                                });
                            }
                        }
                    }
                }
            }

            return(errors);
        }
예제 #43
0
        public void Initialize(ContextBase context, SchemaScope?parent, int initialDepth, JSchema schema)
        {
            Initialize(context, parent, initialDepth, ScopeType.Array);
            InitializeSchema(schema);

            _index      = -1;
            _matchCount = 0;

            if (schema.Contains != null)
            {
                if (_containsContexts != null)
                {
                    _containsContexts.Clear();
                }
                else
                {
                    _containsContexts = new List <ConditionalContext>();
                }
            }

            if (schema.UniqueItems)
            {
                if (_uniqueArrayItems != null)
                {
                    _uniqueArrayItems.Clear();
                }
                else
                {
                    _uniqueArrayItems = new List <JToken>();
                }
            }

            if (ShouldValidateUnevaluated())
            {
                if (_unevaluatedScopes != null)
                {
                    _unevaluatedScopes.Clear();
                }
                else
                {
                    _unevaluatedScopes = new Dictionary <int, UnevaluatedContext>();
                }
            }
        }
예제 #44
0
        public void WriteTo_RecursiveRef()
        {
            string schemaJson = @"{
    ""$id"": ""recursiveRef8_main.json"",
    ""$defs"": {
        ""inner"": {
            ""$id"": ""recursiveRef8_inner.json"",
            ""$recursiveAnchor"": true,
            ""title"": ""inner"",
            ""additionalProperties"": {
                ""$recursiveRef"": ""#""
            }
        }
    },
    ""if"": {
        ""propertyNames"": {
            ""pattern"": ""^[a-m]""
        }
    },
    ""then"": {
        ""title"": ""any type of node"",
        ""$id"": ""recursiveRef8_anyLeafNode.json"",
        ""$recursiveAnchor"": true,
        ""$ref"": ""recursiveRef8_main.json#/$defs/inner""
    },
    ""else"": {
        ""title"": ""integer node"",
        ""$id"": ""recursiveRef8_integerNode.json"",
        ""$recursiveAnchor"": true,
        ""type"": [ ""object"", ""integer"" ],
        ""$ref"": ""recursiveRef8_main.json#/$defs/inner""
    }
}";

            JSchema schema = JSchema.Parse(schemaJson);
            string  json   = schema.ToString();

            string expected = @"{
  ""$id"": ""recursiveRef8_main.json"",
  ""$defs"": {
    ""inner"": {
      ""$id"": ""recursiveRef8_inner.json"",
      ""$recursiveAnchor"": true,
      ""title"": ""inner"",
      ""additionalProperties"": {
        ""$recursiveRef"": ""#""
      }
    }
  },
  ""if"": {
    ""propertyNames"": {
      ""pattern"": ""^[a-m]""
    }
  },
  ""then"": {
    ""$id"": ""recursiveRef8_anyLeafNode.json"",
    ""$recursiveAnchor"": true,
    ""title"": ""any type of node"",
    ""$ref"": ""recursiveRef8_inner.json""
  },
  ""else"": {
    ""$id"": ""recursiveRef8_integerNode.json"",
    ""$recursiveAnchor"": true,
    ""title"": ""integer node"",
    ""type"": [
      ""integer"",
      ""object""
    ],
    ""$ref"": ""recursiveRef8_inner.json""
  }
}";

            StringAssert.AreEqual(expected, json);
        }
예제 #45
0
 public HelperMethods()
 {
     schema = JSchema.Parse(File.ReadAllText($"json_schema.json"));
 }
 private bool ValidateBoolean(JSchema schema, object value)
 {
     return(TestType(schema, JSchemaType.Boolean, value));
 }
예제 #47
0
        public void RaiseError(IFormattable message, ErrorType errorType, JSchema schema, object?value, IList <ValidationError>?childErrors)
        {
            ValidationError error = CreateError(message, errorType, schema, value, childErrors);

            RaiseError(error);
        }
        public void Draft4Example()
        {
            JSchema schema1 = new JSchema
            {
                Id    = new Uri("#foo", UriKind.RelativeOrAbsolute),
                Title = "schema1"
            };
            JSchema schema2 = new JSchema
            {
                Id            = new Uri("otherschema.json", UriKind.RelativeOrAbsolute),
                Title         = "schema2",
                ExtensionData =
                {
                    {
                        "nested",
                        new JSchema
                        {
                            Title = "nested",
                            Id    = new Uri("#bar", UriKind.RelativeOrAbsolute)
                        }
                    },
                    {
                        "alsonested",
                        new JSchema
                        {
                            Title         = "alsonested",
                            Id            = new Uri("t/inner.json#a", UriKind.RelativeOrAbsolute),
                            ExtensionData =
                            {
                                {
                                    "nestedmore",
                                    new JSchema {
                                        Title = "nestedmore"
                                    }
                                }
                            }
                        }
                    }
                }
            };
            JSchema schema3 = new JSchema
            {
                Title = "schema3",
                Id    = new Uri("some://where.else/completely#", UriKind.RelativeOrAbsolute)
            };

            JSchema root = new JSchema
            {
                Id            = new Uri("http://x.y.z/rootschema.json#", UriKind.RelativeOrAbsolute),
                ExtensionData =
                {
                    { "schema1", schema1 },
                    { "schema2", schema2 },
                    { "schema3", schema3 }
                }
            };

            JSchemaDiscovery discovery = new JSchemaDiscovery();

            discovery.Discover(root, null);

            Assert.AreEqual(7, discovery.KnownSchemas.Count);
            Assert.AreEqual("http://x.y.z/rootschema.json#", discovery.KnownSchemas[0].Id.ToString());
            Assert.AreEqual("http://x.y.z/rootschema.json#foo", discovery.KnownSchemas[1].Id.ToString());
            Assert.AreEqual("http://x.y.z/otherschema.json", discovery.KnownSchemas[2].Id.ToString());
            Assert.AreEqual("http://x.y.z/otherschema.json#bar", discovery.KnownSchemas[3].Id.ToString());
            Assert.AreEqual("http://x.y.z/t/inner.json#a", discovery.KnownSchemas[4].Id.ToString());
            Assert.AreEqual("http://x.y.z/t/inner.json#/nestedmore", discovery.KnownSchemas[5].Id.ToString());
            Assert.AreEqual("some://where.else/completely#", discovery.KnownSchemas[6].Id.ToString());
        }
        protected override void ProcessRecord()
        {
            WriteDebug(string.Format("Continue: {0}", _Continue));
            if (!_Continue)
            {
                return;
            }

            Encoding enc = null;

            switch (this.Encoding)
            {
            case EncodingType.ASCII:
                WriteVerbose("Using ASCII encoding.");
                enc = System.Text.Encoding.ASCII;
                break;

            case EncodingType.BigEndianUnicode:
                WriteVerbose("Using Big Endian Unicode encoding.");
                enc = System.Text.Encoding.BigEndianUnicode;
                break;

            case EncodingType.Unicode:
                WriteVerbose("Using Unicode encoding.");
                enc = System.Text.Encoding.Unicode;
                break;

            case EncodingType.UTF32:
                WriteVerbose("Using UTF32 encoding.");
                enc = System.Text.Encoding.UTF32;
                break;

            case EncodingType.UTF7:
                WriteVerbose("Using UTF7 encoding.");
                enc = System.Text.Encoding.UTF7;
                break;

            case EncodingType.UTF8:
                WriteVerbose("Using UTF8 encoding.");
                enc = System.Text.Encoding.UTF8;
                break;

            case EncodingType.Default:
            default:
                enc = System.Text.Encoding.Default;
                WriteVerbose(string.Format("Using System's Default encoding. ({0})", enc.EncodingName));
                break;
            }

            JSchemaUrlResolverEvent resolver = new JSchemaUrlResolverEvent();

            resolver.SchemaResolving += Resolver_SchemaResolving;

            this._JsonFile = TransformPath(this._JsonFile);
            WriteVerbose("Reading JSON File.");
            string sJson = File.ReadAllText(this._JsonFile, enc);

            WriteVerbose("Parsing JSON File.");
            var json = JObject.Parse(sJson);

            string sSchema = string.Empty;

            if (this.SchemaInJsonFile)
            {
                WriteVerbose("Read schema file path from JSON file.");
                if (json["$schema"] == null || string.IsNullOrWhiteSpace(json["$schema"].Value <string>()))
                {
                    throw new PSInvalidOperationException("No $schema property defined in JSON file.");
                }

                this._SchemaFile = json["$schema"].Value <string>();
                WriteVerbose($"Found schema file path [{this._SchemaFile}] in JSON data file [{this._JsonFile}].");
            }

            this._SchemaFile = TransformPath(this._SchemaFile);
            WriteVerbose("Reading Schema File.");
            sSchema = File.ReadAllText(this._SchemaFile, enc);

            // load schema
            WriteVerbose("Parsing Schema File.");
            var schema = JSchema.Parse(sSchema, resolver);

            IList <ValidationError> errors = new List <ValidationError>();

            //if (this.ErrorAsObject) {
            //    errors = new List<ValidationError>();
            //} else {
            //    errors = new List<string>();
            //}

            // validate JSON
            WriteVerbose("Testing JSON file against schema.");
            var valid  =  SchemaExtensions.IsValid(json, schema,  out errors);

            // return error messages and line info
            WriteObject(new SchemaTestResult <ValidationError>()
            {
                Valid   =  valid,
                Errors  = valid ? null : errors
            });

            base.ProcessRecord();
        }
 public void Initialize(ContextBase context, SchemaScope parent, int initialDepth, JSchema schema)
 {
     Initialize(context, parent, initialDepth, ScopeType.Primitive);
     InitializeSchema(schema);
 }
예제 #51
0
 public abstract ValidationError CreateError(string message, ErrorType errorType, JSchema schema, object value, IList <ValidationError> childErrors);
예제 #52
0
        public bool ValidarJson(JObject Json, TipoJson Tipojson)
        {
            try
            {
                var     appDomain = AppDomain.CurrentDomain;
                JSchema Schema;

                switch (Tipojson)
                {
                case TipoJson.CadastroCliente:
                    Schema = JSchema.Parse(File.ReadAllText(Path.Combine(appDomain.BaseDirectory, "SchemasJson\\CadastroClienteSchema.json")));
                    break;

                case TipoJson.EdicaoCliente:
                    Schema = JSchema.Parse(File.ReadAllText(Path.Combine(appDomain.BaseDirectory, "SchemasJson\\EdicaoClienteSchema.json")));
                    break;

                case TipoJson.CadastroLogradouros:
                    Schema = JSchema.Parse(File.ReadAllText(Path.Combine(appDomain.BaseDirectory, "SchemasJson\\CadastroLogradouroSchema.json")));
                    break;

                default:
                    Schema = null;
                    break;
                }

                if (Schema != null)
                {
                    return(Json.IsValid(Schema));
                }
                else
                {
                    return(false);
                }
            }
            catch (DirectoryNotFoundException)
            {
                throw new Exception("Não foi possivel validar o json.");
            }
            catch (DriveNotFoundException)
            {
                throw new Exception("Não foi possivel validar o json.");
            }
            catch (EndOfStreamException)
            {
                throw new Exception("Não foi possivel validar o json.");
            }
            catch (FileLoadException)
            {
                throw new Exception("Não foi possivel validar o json.");
            }
            catch (FileNotFoundException)
            {
                throw new Exception("Não foi possivel validar o json.");
            }
            catch (PathTooLongException)
            {
                throw new Exception("Não foi possivel validar o json.");
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
 public override bool CanValidate(JSchema schema)
 {
     return(schema.ExtensionData.ContainsKey("uniqueDictionaryKey"));
 }
예제 #54
0
 public abstract ValidationError CreateError(IFormattable message, ErrorType errorType, JSchema schema, object?value, IList <ValidationError>?childErrors);
        private bool ValidateNumber(JSchema schema, double value)
        {
            if (!TestType(schema, JSchemaType.Number, value))
                return false;

            if (schema.Maximum != null)
            {
                if (value > schema.Maximum)
                    RaiseError($"Float {JsonConvert.ToString(value)} exceeds maximum value of {schema.Maximum}.", ErrorType.Maximum, schema, value, null);
                if (schema.ExclusiveMaximum && value == schema.Maximum)
                    RaiseError($"Float {JsonConvert.ToString(value)} equals maximum value of {schema.Maximum} and exclusive maximum is true.", ErrorType.Maximum, schema, value, null);
            }

            if (schema.Minimum != null)
            {
                if (value < schema.Minimum)
                    RaiseError($"Float {JsonConvert.ToString(value)} is less than minimum value of {schema.Minimum}.", ErrorType.Minimum, schema, value, null);
                if (schema.ExclusiveMinimum && value == schema.Minimum)
                    RaiseError($"Float {JsonConvert.ToString(value)} equals minimum value of {schema.Minimum} and exclusive minimum is true.", ErrorType.Minimum, schema, value, null);
            }

            if (schema.MultipleOf != null)
            {
                double remainder = MathHelpers.FloatingPointRemainder(value, schema.MultipleOf.Value);

                if (!MathHelpers.IsZero(remainder))
                    RaiseError($"Float {JsonConvert.ToString(value)} is not a multiple of {schema.MultipleOf}.", ErrorType.MultipleOf, schema, value, null);
            }

            return true;
        }
        public void ValidateComplexType()
        {
            string json = @"{
  ""someDictionary"": [
    {
      ""key"":
      {
        ""field1"": ""value1"",
        ""field2"": ""value2"",
        ""field3"": ""value3"",
      },
      ""value"": {}
    },
    {
      ""key"":
      {
        ""field1"": ""value1a"",
        ""field2"": ""value2a"",
        ""field3"": ""value3a"",
      },
      ""value"": {}
    },
    {
      ""key"":
      {
        ""field1"": ""value1"",
        ""field2"": ""value2"",
        ""field3"": ""value3"",
      },
      ""value"": ""invalid!""
    }   
  ]
}";

            JSchemaReaderSettings settings = new JSchemaReaderSettings
            {
                Validators = new List <JsonValidator> {
                    new UniqueKeyValidator()
                }
            };

            JSchema schema = JSchema.Parse(@"{
  ""type"": ""object"",
  ""properties"": {
    ""someDictionary"": {
      ""type"": ""array"",
      ""uniqueDictionaryKey"": true,
      ""items"": {
        ""type"": ""object"",
        ""properties"": {
          ""key"": { ""type"": ""object"" },
          ""value"": { ""type"": ""object"" }
        }
      }
    }
  }
}", settings);

            JObject o = JObject.Parse(json);

            IList <string> errors;

            Assert.IsFalse(o.IsValid(schema, out errors));

            Assert.AreEqual(2, errors.Count);
            Assert.AreEqual(@"Invalid type. Expected Object but got String. Path 'someDictionary[2].value', line 28, position 25.", errors[0]);
            Assert.AreEqual(@"Duplicate key: {""field1"":""value1"",""field2"":""value2"",""field3"":""value3""}. Path 'someDictionary', line 2, position 21.", errors[1]);
        }
 private bool ValidateBoolean(JSchema schema, object value)
 {
     return TestType(schema, JSchemaType.Boolean, value);
 }
 public override bool CanValidate(JSchema schema)
 {
     return(schema.Format == "json");
 }
 public override void RaiseError(IFormattable message, ErrorType errorType, JSchema schema, object value, IList<ValidationError> childErrors)
 {
     _hasErrors = true;
     Validator.RaiseError(message, errorType, schema, value, childErrors);
 }
        private void DiscoverInternal(JSchema schema, string latestPath)
        {
            if (schema.Reference != null)
            {
                return;
            }

            if (_knownSchemas.Any(s => s.Schema == schema))
            {
                return;
            }

            Uri    newScopeId;
            string scopePath     = latestPath;
            Uri    schemaKnownId = GetSchemaIdAndNewScopeId(schema, ref scopePath, out newScopeId);

            // check whether a schema with the resolved id is already known
            // this will be hit when a schema contains duplicate ids or references a schema with a duplicate id
            bool existingSchema = _knownSchemas.Any(s => UriComparer.Instance.Equals(s.Id, schemaKnownId));

#if DEBUG
            if (_knownSchemas.Any(s => s.Schema == schema))
            {
                throw new InvalidOperationException("Schema with id '{0}' already a known schema.".FormatWith(CultureInfo.InvariantCulture, schemaKnownId));
            }
#endif

            // add schema to known schemas whether duplicate or not to avoid multiple errors
            // the first schema with a duplicate id will be used
            _knownSchemas.Add(new KnownSchema(schemaKnownId, schema, _state));

            if (existingSchema)
            {
                if (ValidationErrors != null)
                {
                    ValidationError error = ValidationError.CreateValidationError("Duplicate schema id '{0}' encountered.".FormatWith(CultureInfo.InvariantCulture, schemaKnownId.OriginalString), ErrorType.Id, schema, null, schemaKnownId, null, schema, schema.Path);
                    ValidationErrors.Add(error);
                }

                return;
            }

            _pathStack.Push(new SchemaPath(newScopeId, scopePath));

            // discover should happen in the same order as writer except extension data (e.g. definitions)
            if (schema._extensionData != null)
            {
                foreach (KeyValuePair <string, JToken> valuePair in schema._extensionData)
                {
                    DiscoverTokenSchemas(EscapePath(valuePair.Key), valuePair.Value);
                }
            }

            DiscoverSchema(Constants.PropertyNames.AdditionalProperties, schema.AdditionalProperties);
            DiscoverSchema(Constants.PropertyNames.AdditionalItems, schema.AdditionalItems);
            DiscoverDictionarySchemas(Constants.PropertyNames.Properties, schema._properties);
            DiscoverDictionarySchemas(Constants.PropertyNames.PatternProperties, schema._patternProperties);
            DiscoverDictionarySchemas(Constants.PropertyNames.Dependencies, schema._dependencies);
            DiscoverArraySchemas(Constants.PropertyNames.Items, schema._items);
            DiscoverArraySchemas(Constants.PropertyNames.AllOf, schema._allOf);
            DiscoverArraySchemas(Constants.PropertyNames.AnyOf, schema._anyOf);
            DiscoverArraySchemas(Constants.PropertyNames.OneOf, schema._oneOf);
            DiscoverSchema(Constants.PropertyNames.Not, schema.Not);

            _pathStack.Pop();
        }