public virtual void TestNotAllowNullSchemaEncodeAndDecode()
        {
            var keyValueSchema = ISchema <object> .KeyValue(JSONSchema <Foo> .Of(ISchemaDefinition <Foo> .Builder().WithPojo(typeof(Foo)).WithAlwaysAllowNull(false).Build())
                                                            , JSONSchema <Bar> .Of(ISchemaDefinition <Bar> .Builder().WithPojo(typeof(Bar)).WithAlwaysAllowNull(false).Build()));

            var bar = new Bar
            {
                Field1 = true
            };

            var foo = new Foo
            {
                Field1 = "field1",
                Field2 = "field2",
                Field3 = "3",
                Field4 = bar,
                Color  = Color.RED
            };

            var encodeBytes = keyValueSchema.Encode(new KeyValue <Foo, Bar>(foo, bar));

            Assert.True(encodeBytes.Length > 0);

            var keyValue = keyValueSchema.Decode(encodeBytes);
            var fooBack  = keyValue.Key;
            var barBack  = keyValue.Value;

            Assert.True(foo.Equals(fooBack));
            Assert.True(bar.Equals(barBack));
        }
Exemple #2
0
        static void Main(string[] args)
        {
            Options options = new Options();
            ParserResult <Options> result = Parser.Default.ParseArguments <Options>(args).WithParsed <Options>(o =>
            {
                if (string.IsNullOrEmpty(o.DataPackageFile))
                {
                    o.DataPackageFile = "ExtendedDataPackage.json";
                }
                options = o;
            });

            if (result.Tag == ParserResultType.NotParsed)
            {
                // Help text requested, or parsing failed. Exit.
                return;
            }

            DataPackage dataPackage = FilterJSON(options);

            if (options.ExportType == "gv")
            {
                ERD erd = new ERD(dataPackage.Tables);
                erd.Generate(options);
            }
            else if (options.ExportType == "json")
            {
                JSONSchema schema = new JSONSchema(dataPackage.Tables);
                schema.Generate(options);
            }
            else if (options.ExportType == "table")
            {
                JSONTable schema = new JSONTable(dataPackage.Tables);
                schema.Generate(options);
            }
            else if (options.ExportType == "csv")
            {
                CSVSchema schema = new CSVSchema(dataPackage.Tables);
                schema.Generate(options);
            }
            else if (options.ExportType == "sql")
            {
                SQL sql = new SQL(dataPackage.Tables);
                sql.Generate(options);
            }
            else if (options.ExportType == "html")
            {
                HTML html = new HTML(dataPackage);
                html.Generate(options);
            }
            else if (options.ExportType == "erd")
            {
                LucidChart lucidChart = new LucidChart(dataPackage);
                lucidChart.Generate(options);
            }
            else
            {
                Console.WriteLine("Export type not recognised");
            }
        }
Exemple #3
0
        public virtual void TestNotAllowNullEncodeAndDecode()
        {
            var jsonSchema = JSONSchema <Foo> .Of(ISchemaDefinition <Foo> .Builder().WithPojo(typeof(Foo)).WithAlwaysAllowNull(false).Build());

            var foo1 = new Foo
            {
                Field1 = "foo1",
                Field2 = "bar1",
                Field4 = new Bar()
            };

            var foo2 = new Foo
            {
                Field1 = "foo2",
                Field2 = "bar2"
            };

            var bytes1  = jsonSchema.Encode(foo1);
            var object1 = jsonSchema.Decode(bytes1);

            Assert.True(bytes1.Length > 0);
            Assert.True(object1.Equals(foo1));

            try
            {
                jsonSchema.Encode(foo2);
            }
            catch (Exception e)
            {
                Assert.True(e is SchemaSerializationException);
            }
        }
Exemple #4
0
        public void DecodeLargeArray(int length, int count)
        {
            var builder = new StringBuilder();
            var random  = new Random();

            builder.Append("[");

            if (length > 0)
            {
                for (var i = 0;;)
                {
                    builder.Append(random.Next().ToString(CultureInfo.InvariantCulture));

                    if (++i >= length)
                    {
                        break;
                    }

                    builder.Append(",");
                }
            }

            builder.Append("]");

            var schema = new JSONSchema <long[]>();

            schema.DecoderDescriptor.HasElements(() => 0,
                                                 (ref long[] target, IEnumerable <long> elements) => target = elements.ToArray()).HasValue();

            var decoder = schema.CreateDecoder(Array.Empty <long>);

            CompareNewtonsoft.BenchDecode(decoder, builder.ToString(), count);
        }
Exemple #5
0
        public void TestDraft04Schema()
        {
            JSONSchema draft04Schema = new JSONSchema(draft04SchemaJson);

            Console.WriteLine(draft04Schema.GetHashCode());
            Console.WriteLine(draft04Schema.ToString());

            TestSimpleType(draft04Schema, "object");



            Assert.That(draft04Schema.Properties.ContainsKey("id"));
            Assert.That(draft04Schema.Properties.ContainsKey("$schema"));

            JSONSchema idSchema = draft04Schema.Properties["id"];

            TestSimpleType(idSchema, "string");

            JSONSchema additionalItems = draft04Schema.Properties["additionalItems"];

            Assert.NotNull(additionalItems.AnyOf);

            SchemaArray anyOf = additionalItems.AnyOf as SchemaArray;

            TestSimpleType(anyOf[0], "boolean");
            Assert.AreEqual(draft04Schema, draft04Schema.Properties["not"]);
        }
Exemple #6
0
        public void TestSimpleSchema()
        {
            JSONSchema simpleSchema = new JSONSchema(simpleSchemaJson);

            TestSimpleType(simpleSchema, "object");

            Assert.AreEqual("simpleSchema", simpleSchema.Title);

            Assert.AreEqual(typeof(JSONSchema), simpleSchema.AdditionalProperties.GetUnderlyingType());
            JSONSchema additionalPropertiesSchema = simpleSchema.AdditionalProperties.GetValue() as JSONSchema;

            TestSimpleType(additionalPropertiesSchema, "string");

            Assert.AreEqual("id", simpleSchema.Required[0]);
            Assert.AreEqual(2, simpleSchema.Properties.Count);
            Assert.That(simpleSchema.Properties.ContainsKey("id"));
            Assert.That(simpleSchema.Properties.ContainsKey("field1"));

            JSONSchema idSchema = simpleSchema.Properties["id"];

            TestSimpleType(idSchema, "integer");

            JSONSchema field1Schema = simpleSchema.Properties["field1"];

            TestSimpleType(field1Schema, "array");

            JSONSchema itemsSchema = field1Schema.Items.GetValue() as JSONSchema;

            TestSimpleType(itemsSchema, "string");
        }
        public virtual void TestJsonSchemaCreate()
        {
            var fooSchema = JSONSchema <Foo> .Of(ISchemaDefinition <Foo> .Builder().WithPojo(typeof(Foo)).WithAlwaysAllowNull(false).Build());

            var barSchema = JSONSchema <Bar> .Of(ISchemaDefinition <Bar> .Builder().WithPojo(typeof(Bar)).WithAlwaysAllowNull(false).Build());

            var keyValueSchema1 = ISchema <object> .KeyValue(fooSchema, barSchema);

            var keyValueSchema2 = ISchema <object> .KeyValue(JSONSchema <Foo> .Of(ISchemaDefinition <Foo> .Builder().WithPojo(typeof(Foo)).WithAlwaysAllowNull(false).Build()), JSONSchema <Bar> .Of(ISchemaDefinition <Bar> .Builder().WithPojo(typeof(Bar)).WithAlwaysAllowNull(false).Build()));

            var keyValueSchema3 = ISchema <object> .KeyValue(JSONSchema <Foo> .Of(ISchemaDefinition <Foo> .Builder().WithPojo(typeof(Foo)).WithAlwaysAllowNull(false).Build()), JSONSchema <Bar> .Of(ISchemaDefinition <Bar> .Builder().WithPojo(typeof(Bar)).WithAlwaysAllowNull(false).Build()));

            Assert.Equal(keyValueSchema1.SchemaInfo.Type, SchemaType.KeyValue);
            Assert.Equal(keyValueSchema2.SchemaInfo.Type, SchemaType.KeyValue);
            Assert.Equal(keyValueSchema3.SchemaInfo.Type, SchemaType.KeyValue);

            Assert.Equal(((KeyValueSchema <Foo, Bar>)keyValueSchema1).KeySchema.SchemaInfo.Type, SchemaType.JSON);
            Assert.Equal(((KeyValueSchema <Foo, Bar>)keyValueSchema1).ValueSchema.SchemaInfo.Type, SchemaType.JSON);
            Assert.Equal(((KeyValueSchema <Foo, Bar>)keyValueSchema2).KeySchema.SchemaInfo.Type, SchemaType.JSON);
            Assert.Equal(((KeyValueSchema <Foo, Bar>)keyValueSchema2).ValueSchema.SchemaInfo.Type, SchemaType.JSON);
            Assert.Equal(((KeyValueSchema <Foo, Bar>)keyValueSchema3).KeySchema.SchemaInfo.Type, SchemaType.JSON);
            Assert.Equal(((KeyValueSchema <Foo, Bar>)keyValueSchema3).ValueSchema.SchemaInfo.Type, SchemaType.JSON);

            var schemaInfo1 = Encoding.UTF8.GetString(keyValueSchema1.SchemaInfo.Schema);
            var schemaInfo2 = Encoding.UTF8.GetString(keyValueSchema2.SchemaInfo.Schema);
            var schemaInfo3 = Encoding.UTF8.GetString(keyValueSchema3.SchemaInfo.Schema);

            Assert.Equal(schemaInfo1, schemaInfo2);
            Assert.Equal(schemaInfo1, schemaInfo3);
        }
Exemple #8
0
        private void TestSimpleType(JSONSchema stringTypeSchema, string typeName)
        {
            Assert.AreEqual(typeof(SimpleType), stringTypeSchema.Type.GetUnderlyingType());
            Assert.That(stringTypeSchema.Type.GetValue() is SimpleType);
            SimpleType simpleType = stringTypeSchema.Type.GetValue() as SimpleType;

            Assert.AreEqual(typeName, simpleType.Value);
        }
Exemple #9
0
        public void DecodeObjectAsArray(bool scalarAsArray, string json, int[] expected)
        {
            var schema = new JSONSchema <int[]>(new JSONConfiguration {
                ReadScalarAsOneElementArray = scalarAsArray
            });

            schema.DecoderDescriptor
            .HasField("parent", () => default, (ref int[] entity, int[] value) => entity = value)
Exemple #10
0
        public virtual void TestNotAllowNullSchema()
        {
            var jsonSchema = JSONSchema <Foo> .Of(ISchemaDefinition <Foo> .Builder().WithPojo(typeof(Foo)).WithAlwaysAllowNull(false).Build());

            Assert.Equal(jsonSchema.SchemaInfo.Type, SchemaType.JSON);
            var schemaJson = jsonSchema.SchemaInfo.SchemaDefinition;
            var schema     = Avro.Schema.Parse(schemaJson);

            Assert.NotNull(schema);
        }
Exemple #11
0
        private ISchema GetSchema(JSONSettings settings)
        {
            JSONSchema	schema;

            schema = new JSONSchema (settings);
            schema.OnStreamError += (position, message) => Console.Error.WriteLine ("Stream error at position {0}: {1}", position, message);
            schema.OnTypeError += (type, value) => Console.Error.WriteLine ("Type error: could not convert \"{1}\" to {0}", type, value);

            return schema;
        }
Exemple #12
0
        static void Main(string[] args)
        {
            Options options = new Options();
            ParserResult <Options> result = Parser.Default.ParseArguments <Options>(args).WithParsed <Options>(o =>
            {
                options = o;
            });

            if (result.Tag == ParserResultType.NotParsed)
            {
                // Help text requested, or parsing failed. Exit.
                return;
            }

            List <Table> tables = FilterJSON(options);

            if (options.ExportType == "gv")
            {
                ERD erd = new ERD(tables);
                erd.Generate(options);
            }
            else if (options.ExportType == "json")
            {
                JSONSchema schema = new JSONSchema(tables);
                schema.Generate(options);
            }
            else if (options.ExportType == "table")
            {
                JSONTable schema = new JSONTable(tables);
                schema.Generate(options);
            }
            else if (options.ExportType == "csv")
            {
                CSVSchema schema = new CSVSchema(tables);
                schema.Generate(options);
            }
            else if (options.ExportType == "sql")
            {
                SQL sql = new SQL(tables);
                sql.Generate(options);
            }
            else if (options.ExportType == "html")
            {
                HTML html = new HTML(tables);
                html.Generate(options);
            }
            else
            {
                Console.WriteLine("Export type not recognised");
            }
        }
Exemple #13
0
        private void TestSchema(string path)
        {
            var schemaJson = JsonDocument.Parse(File.ReadAllText(Path.GetFullPath(path + "input.json")));
            var schema     = new JSONSchema(schemaJson);
            var generator  = new ClassGeneratorFromJsonSchema(schema);

            generator.GenerateAll();
            var results = generator.PrintAll();

            var expected = File.ReadAllText(Path.GetFullPath(path + "expected.txt"));

            foreach (string value in results.Values)
            {
                Console.WriteLine(value);
            }
            results.Values.Aggregate("", (current, next) => current + next).ShouldBe(expected);
        }
Exemple #14
0
        public void Save()
        {
            JSONSchema json = new JSONSchema();

            json.id          = ID;
            json.serverId    = ServerID;
            json.displayName = DisplayName;

            try
            {
                json.keypairs = CertHelper.ExportKeyPairs(Cert);
            } catch (InvalidCertificateException)
            {
                UnityEngine.Debug.LogWarning("JSON PRIV NULL");
                json.keypairs = null;
            }

            StorageHelper.SaveToFileAlternate(JsonConvert.SerializeObject(json), ID + ".mdmc");
        }
Exemple #15
0
        /// <summary>
        /// UserFile constructor - loads from a .mdmc file.
        /// </summary>
        /// <param name="clientID">the client ID or filename to load (exluding ext)</param>
        public UserFile(string clientID)
        {
            string filename = clientID + ".mdmc";

            if (StorageHelper.FileExists(filename))
            {
                // Load the file
                byte[] raw = StorageHelper.ReadFileByteSync(filename);

                // Convert it from JSON into an object
                JSONSchema data = JsonConvert.DeserializeObject <JSONSchema>(Encoding.UTF8.GetString(raw));

                // Decode the Keypairs
                byte[] keypairsB = Convert.FromBase64String(data.keypairs);

                // Create the certificate
                X509Certificate2 cert = new X509Certificate2(keypairsB, "", X509KeyStorageFlags.PersistKeySet);

                // Run the usual init for certificates.
                Setup(cert);
            }
        }
Exemple #16
0
        public void Bench(int repeat)
        {
            IParser<A> parser1;
            IParser<A> parser2;
            JSONSchema<A> schema;
            A value;

            schema = new JSONSchema<A>();
            schema.ParserDescriptor.HasField("b", (ref A a, int b) => a.b = b).IsValue();

            parser1 = schema.CreateParser();

            schema = new JSONSchema<A>();
            schema.ParserDescriptor.HasField("b").IsValue((ref A a, int b) => a.b = b);

            parser2 = schema.CreateParser();

            var j1 = Encoding.UTF8.GetBytes("{\"b\": 5}");
            var j2 = Encoding.UTF8.GetBytes("{\"b\": 7}");

            value = new A();
            Assert.IsTrue(parser1.Parse(new MemoryStream(j1), ref value));
            Assert.AreEqual(5, value.b);

            value = new A();
            Assert.IsTrue(parser2.Parse(new MemoryStream(j2), ref value));
            Assert.AreEqual(7, value.b);

            var s1 = System.Diagnostics.Stopwatch.StartNew();
            for (int i = 0; i < repeat; ++i)
                parser1.Parse(new MemoryStream(j1), ref value);
            Console.WriteLine("p1: " + s1.Elapsed);
            var s2 = System.Diagnostics.Stopwatch.StartNew();
            for (int i = 0; i < repeat; ++i)
                parser2.Parse(new MemoryStream(j2), ref value);
            Console.WriteLine("p2: " + s2.Elapsed);
        }
Exemple #17
0
        public virtual void TestAllowNullEncodeAndDecode()
        {
            var jsonSchema = JSONSchema <Foo> .Of(ISchemaDefinition <Foo> .Builder().WithPojo(typeof(Foo)).Build());

            var bar = new Bar
            {
                Field1 = true
            };

            var foo1 = new Foo
            {
                Field1 = "foo1",
                Field2 = "bar1",
                Field4 = bar,
                Color  = Color.BLUE
            };

            var foo2 = new Foo
            {
                Field1 = "foo2",
                Field2 = "bar2"
            };

            var bytes1 = jsonSchema.Encode(foo1);

            Assert.True(bytes1.Length > 0);

            var bytes2 = jsonSchema.Encode(foo2);

            Assert.True(bytes2.Length > 0);

            var object1 = jsonSchema.Decode(bytes1);
            var object2 = jsonSchema.Decode(bytes2);

            Assert.True(object1.Equals(foo1));
            Assert.True(object2.Equals(foo2));
        }
Exemple #18
0
        static void Main(string[] args)
        {
            var    inputFile = args[0];
            string fullPath;

            try
            {
                fullPath = Path.GetFullPath(inputFile);
            }
            catch
            {
                Console.WriteLine(string.Format("{0} is not a valid File Path", inputFile));
                return;
            }

            string inputJson;

            try
            {
                inputJson = File.ReadAllText(fullPath);
            }
            catch
            {
                Console.WriteLine(string.Format("{0} cannot be read or is not a valid file", inputFile));
                return;
            }

            JsonDocument inputSchema;

            try
            {
                inputSchema = JsonDocument.Parse(inputJson);
            }
            catch
            {
                Console.WriteLine(string.Format("{0} is not a valid json", inputFile));
                return;
            }

            var schema = new JSONSchema(inputSchema);

            var generator = new ClassGeneratorFromJsonSchema(schema, schema.Title ?? "GeneratedClass");

            generator.GenerateAll();
            var results = generator.PrintAll();

            string outputFolder = args[1];

            Directory.CreateDirectory(outputFolder);

            string[] existingFiles = Directory.GetFiles(outputFolder);
            foreach (string file in existingFiles)
            {
                if (file.EndsWith(".cs"))
                {
                    File.Delete(file);
                }
            }

            foreach (var result in results)
            {
                string filePath = Path.Combine(outputFolder, string.Format("{0}.cs", result.Key));
                File.WriteAllText(filePath, result.Value);
            }
        }
 public static ISchema <T> NewJsonSchema <T>(ISchemaDefinition <T> schemaDefinition)
 {
     return(JSONSchema <T> .Of(schemaDefinition));
 }
Exemple #20
0
        public void TestStringTypeSchema()
        {
            JSONSchema stringTypeSchema = new JSONSchema(stringTypeJson);

            TestSimpleType(stringTypeSchema, "string");
        }
Exemple #21
0
        private ISchema GetSchema()
        {
            JSONSchema	schema;

            schema = new JSONSchema (0);
            schema.OnStreamError += (position, message) => Console.Error.WriteLine ("Stream error at position {0}: {1}", position, message);
            schema.OnTypeError += (type, value) => Console.Error.WriteLine ("Type error: could not convert \"{1}\" to {0}", type, value);

            schema.SetDecoderConverter<Guid> (Guid.TryParse);
            schema.SetEncoderConverter<Guid> ((g) => g.ToString ());

            return schema;
        }