示例#1
0
        public bool TryGetExtension <T>(string name, out T value)
        {
            if (Extensions == null)
            {
                value = default(T);
                return(false);
            }

            INode node;

            if (!Extensions.TryGetValue(name, out node))
            {
                value = default(T);
                return(false);
            }

            var v  = JsonSchemaAttribute.CreateFromClass <T>();
            var ex = v.Validate(node);

            if (ex != null)
            {
                // TODO:
                throw ex;
            }

            var d  = new JsonDeserializer(typeof(T));
            var dv = d.DeserializeFromNode(node);

            value = (T)dv;

            return(true);
        }
示例#2
0
        public static Types.Gltf Read(Stream s, bool withRepairment = true, bool withValidation = true)
        {
            using (var r = new JsonReader(s))
            {
                var node = r.Read();

                if (withRepairment)
                {
                    RepairKnownInvalidFormat(node);
                }

                var jd   = new JsonDeserializer(typeof(Types.Gltf));
                var gltf = (Types.Gltf)jd.DeserializeFromNode(node);

                if (withValidation)
                {
                    var schema = JsonSchemaAttribute.CreateFromClass <Types.Gltf>();
                    var ex     = schema.Validate(gltf);
                    if (ex != null)
                    {
                        throw ex;
                    }
                }

                return(gltf);
            }
        }
示例#3
0
        public void FromTypeValidationTest <E>(Type ty, E e, string expectedMsg, string _expectedContent)
        {
            var schema = JsonSchemaAttribute.CreateFromType(ty);

            var ex = schema.Validate(e);

            var message =
                String.Format("{0} : {1}", new JsonSerializer(ty).Serialize(e), schema.ToString());

            Assert.AreEqual(expectedMsg, ex != null ? ex.Message : null, message);
        }
示例#4
0
        public void ValidationTest <T>(T o, string expectedMsg, string _expectedContent)
        {
            var schema = JsonSchemaAttribute.CreateFromClass <T>();

            var ex = schema.Validate(o);

            var message =
                String.Format("{0} : {1}", new JsonSerializer(typeof(T)).Serialize(o), schema.ToString());

            Assert.AreEqual(expectedMsg, ex != null ? ex.Message : null, message);
        }
示例#5
0
        private static bool DetermineDynamic(
            JsonSchemaAttribute jsonSchema,
            JsonEventType optionalSuperType,
            StatementRawInfo raw)
        {
            if (optionalSuperType != null && optionalSuperType.Detail.IsDynamic)
            {
                return(true);
            }

            return(jsonSchema != null && jsonSchema.Dynamic);
        }
示例#6
0
        public static void Write(Stream s, Types.Gltf gltf)
        {
            var schema = JsonSchemaAttribute.CreateFromClass <Types.Gltf>();
            var ex     = schema.Validate(gltf);

            if (ex != null)
            {
                throw ex;
            }

            WriteWithoutValidation(s, gltf);
        }
示例#7
0
        public void BasicOperationTest()
        {
            var r = new JsonSchemaRegistory();

            Assert.Null(r.Resolve("=TEST="));
            Assert.That(r.GetRegisteredIDs(), Is.EquivalentTo(new string[] { }));

            var s = new JsonSchemaAttribute();

            r.Register("a", s);

            Assert.That(r.Resolve("a"), Is.EqualTo(s));
            Assert.That(r.GetRegisteredIDs(), Is.EquivalentTo(new string[] { "a" }));
        }
示例#8
0
        private static Type DetermineUnderlyingProvided(
            JsonSchemaAttribute jsonSchema,
            StatementCompileTimeServices services)
        {
            if (jsonSchema != null && !string.IsNullOrWhiteSpace(jsonSchema.ClassName))
            {
                try {
                    return(services.ImportServiceCompileTime.ResolveClass(jsonSchema.ClassName, true, ExtensionClassEmpty.INSTANCE));
                }
                catch (ImportException e) {
                    throw new ExprValidationException("Failed to resolve JSON event class '" + jsonSchema.ClassName + "': " + e.Message, e);
                }
            }

            return(null);
        }
示例#9
0
        static void Main(string[] args)
        {
            VVrm.ExtensionRegistrator.Register();

            // Create all JsonSchemas related to VRM from the root class.
            var reg     = new JsonSchemaRegistory();
            var _schama = JsonSchemaAttribute.CreateFromClass <VVrm.V0_x.Types.Vrm>(reg);

            if (args.Length != 1)
            {
                Console.Error.WriteLine("Error: Not enough arguments.");
                ShowUsage();
                System.Environment.Exit(1);
            }

            var outDir = args[0];

            if (!Directory.Exists(outDir))
            {
                Console.Error.WriteLine("Error: Directory not exists: Path = " + outDir);
                ShowUsage();
                System.Environment.Exit(1);
            }

            var indent = 4;

            var s = new JsonSerializer(typeof(JsonSchemaAttribute));

            foreach (var id in reg.GetRegisteredIDs())
            {
                var schema = reg.Resolve(id);
                if (string.IsNullOrEmpty(schema.Title))
                {
                    Console.Error.WriteLine("Schemas of VRM must have title: Id = " + id);
                    continue;
                }

                var fileName = string.Format("{0}.schema.json", schema.Title);
                var path     = Path.Combine(outDir, fileName);

                using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write))
                {
                    s.Serialize(fs, schema, indent);
                }
            }
        }
示例#10
0
        public void FromVrmTest(string[] modelPath, Action <VGltf.ResourcesStore> assertVrm)
        {
            VVrm.ExtensionRegistrator.Register();

            var path = modelPath.Aggregate("SampleModels", (b, p) => Path.Combine(b, p));

            using (var fs = new FileStream(path, FileMode.Open))
            {
                var c = VGltf.GltfContainer.FromGlb(fs);

                var schema = JsonSchemaAttribute.CreateFromClass <VGltf.Types.Gltf>();
                var ex     = schema.Validate(c.Gltf);
                Assert.Null(ex);

                var store = new VGltf.ResourcesStore(c.Gltf, c.Buffer, new VGltf.ResourceLoaderFromStorage());
                assertVrm(store);
            }
        }
示例#11
0
        public void CreateFromPersonTest()
        {
            var schema = JsonSchemaAttribute.CreateFromClass <Person>();

            Assert.IsNotNull(schema);

            Assert.AreEqual("Person", schema.Title);
            Assert.AreEqual(null, schema.Description);

            //Assert.AreEqual(NodeKind.Object, schema.Kind);

            Assert.That(schema.Properties.Count, Is.EqualTo(3));

            Assert.That(schema.Properties["firstName"],
                        Is.EqualTo(new JsonSchemaAttribute
            {
                Description = "The person's first name.",
                Type        = "string",
            })
                        );
            Assert.That(schema.Properties["lastName"],
                        Is.EqualTo(new JsonSchemaAttribute
            {
                Description = "The person's last name.",
                Type        = "string",
            })
                        );
            Assert.That(schema.Properties["age"],
                        Is.EqualTo(new JsonSchemaAttribute
            {
                Description = "Age in years which must be equal to or greater than zero.",
                Type        = "integer",
                Minimum     = 0,
            })
                        );
        }
示例#12
0
        public static JsonSchema FromType(Type t,
                                          BaseJsonSchemaAttribute a  = null, // field attribute
                                          ItemJsonSchemaAttribute ia = null
                                          )
        {
            // class attribute
            var aa = t.GetCustomAttributes(typeof(JsonSchemaAttribute), true)
                     .FirstOrDefault() as JsonSchemaAttribute;

            if (a != null)
            {
                a.Merge(aa);
            }
            else
            {
                if (aa == null)
                {
                    a = new JsonSchemaAttribute();
                }
                else
                {
                    a = aa;
                }
            }

            if (ia == null)
            {
                ia = t.GetCustomAttributes(typeof(ItemJsonSchemaAttribute), true)
                     .FirstOrDefault() as ItemJsonSchemaAttribute;
            }

            IJsonSchemaValidator validator = null;
            var skipComparison             = a.SkipSchemaComparison;

            if (t == typeof(object))
            {
                skipComparison = true;
            }

            if (a.EnumValues != null)
            {
                try
                {
                    validator = JsonEnumValidator.Create(a.EnumValues, a.EnumSerializationType);
                }
                catch (Exception)
                {
                    throw new Exception(String.Join(", ", a.EnumValues.Select(x => x.ToString()).ToArray()));
                }
            }
            else if (t.IsEnum)
            {
                validator = JsonEnumValidator.Create(t, a.EnumSerializationType, a.EnumExcludes);
            }
            else
            {
                validator = JsonSchemaValidatorFactory.Create(t, a, ia);
            }

            var schema = new JsonSchema
            {
                Title                       = a.Title,
                Description                 = a.Description,
                Validator                   = validator,
                SkipComparison              = skipComparison,
                ExplicitIgnorableValue      = a.ExplicitIgnorableValue,
                ExplicitIgnorableItemLength = a.ExplicitIgnorableItemLength,
            };

            return(schema);
        }
        private static IEnumerable <JsonSchemaItem> GetProperties(Type t, PropertyExportFlags exportFlags)
        {
            // fields
            foreach (var fi in t.GetFields())
            {
                var a =
                    fi.GetCustomAttributes(typeof(JsonSchemaAttribute), true).FirstOrDefault() as JsonSchemaAttribute;
                if (a == null)
                {
                    a = fi.FieldType.GetCustomAttributes(typeof(JsonSchemaAttribute), true).FirstOrDefault() as
                        JsonSchemaAttribute;
                    if (a == null)
                    {
                        if (!fi.IsStatic && fi.IsPublic)
                        {
                            a = new JsonSchemaAttribute();
                        }
                    }
                }

                // for array item
                var ia =
                    fi.GetCustomAttributes(typeof(ItemJsonSchemaAttribute), true).FirstOrDefault() as
                    ItemJsonSchemaAttribute;

                if (a == null)
                {
                    //int x = 0;
                }
                else
                {
                    yield return(new JsonSchemaItem
                    {
                        Key = fi.Name,
                        Schema = JsonSchema.FromType(fi.FieldType, a, ia),
                        Required = a.Required,
                        Dependencies = a.Dependencies,
                    });
                }
            }

            // properties
            foreach (var pi in t.GetProperties())
            {
                var a =
                    pi.GetCustomAttributes(typeof(JsonSchemaAttribute), true).FirstOrDefault() as JsonSchemaAttribute;

                // for array item
                var ia =
                    pi.GetCustomAttributes(typeof(ItemJsonSchemaAttribute), true).FirstOrDefault() as
                    ItemJsonSchemaAttribute;

                if (a != null)
                {
                    yield return new JsonSchemaItem
                           {
                               Key          = pi.Name,
                               Schema       = JsonSchema.FromType(pi.PropertyType, a, ia),
                               Required     = a.Required,
                               Dependencies = a.Dependencies,
                           }
                }
                ;
            }
        }
示例#14
0
        public void SchemaFormatTest(Type ty, string expected)
        {
            var schema = JsonSchemaAttribute.CreateFromType(ty);

            Assert.AreEqual(expected, schema.ToString());
        }