public void ComplexArrayProperty()
        {
            //// Arrange
            var data = @"{
                persons: [
                    {
                        foo: ""bar"", 
                        bar: ""foo""
                    },
                    {
                        foo: ""bar"", 
                        puk: ""fii""
                    }
                ]
            }";

            //// Act
            var schema   = JsonSchema.FromSampleJson(data);
            var json     = schema.ToJson();
            var property = schema.Properties["persons"].ActualTypeSchema;

            //// Assert
            Assert.Equal(JsonObjectType.Array, property.Type);
            Assert.Equal(3, property.Item.ActualSchema.Properties.Count);
            Assert.True(schema.Definitions.ContainsKey("Person"));
        }
Exemple #2
0
        public List <T> Get()
        {
            string content = sendGET();

            JArray   jItems  = (JArray)JObject.Parse(content)["results"];
            List <T> loaders = new List <T>();

            foreach (JToken i in jItems)
            {
                T loader = new T();

                JsonSchema schema = JsonSchema.FromSampleJson(i.ToString());
                foreach (var p in schema.Properties)
                {
                    try
                    {
                        typeof(Car).GetProperty(p.Key).SetValue(loader, i[p.Key].ToObject(typeof(Loader).GetProperty(p.Key).PropertyType));
                    }
                    catch (NullReferenceException) { }
                    catch (FormatException) { }
                }
                loaders.Add(loader);
            }
            return(loaders);
        }
Exemple #3
0
        public async Task <IActionResult> EditDynamic([FromQuery] string url)
        {
            if (string.IsNullOrEmpty(url))
            {
                return(new NotFoundResult());
            }

            var httpClient = httpClientFactory.CreateClient();
            var json       = await httpClient.GetStringAsync(url).ConfigureAwait(false);

            var jsonSchema = JsonSchema.FromSampleJson(json);

            var schema = new SchemaLocation()
            {
                Key    = "_dynamic",
                Schema = jsonSchema.ToJson()
            };

            var model = new EditViewModel
            {
                CmsType          = "_dynamic",
                Id               = Guid.NewGuid(),
                SchemaLocation   = schema,
                CmsConfiguration = schemaService.GetCmsConfiguration(),
                Data             = JsonSerializer.Deserialize <CmsItem>(json)
            };

            return(View(nameof(Edit), model));
        }
        public static T Parse <T>(string data)
        {
            if (string.IsNullOrEmpty(data))
            {
                throw new ModinfoParseException("No input data.");
            }

            var schema           = JsonSchema.FromSampleJson(ModinfoJsonSchema.Schema);
            var validationErrors = schema.Validate(data);

            if (validationErrors.Any())
            {
                throw new ModinfoParseException($"Unable to parse. Error:{validationErrors.First()}");
            }

            try
            {
                var parseResult = JsonConvert.DeserializeObject <T>(data);
                if (parseResult is null)
                {
                    throw new ModinfoParseException(
                              $"Unable to parse input '{data}' to {typeof(T).Name}. Unknown Error!");
                }
                return(parseResult);
            }
            catch (JsonSerializationException cause)
            {
                throw new ModinfoParseException(cause.Message, cause);
            }
        }
        public void Get_Extract_SchemaResponse_Compare()
        {
            //Arrange
            var expectedJsonSchema = JsonSchema.FromSampleJson(JsonSerializer.Serialize(AutoFaker.Generate <ExtractResponse_Expected>())).ToJson();
            var actualJsonSchema   = JsonSchema.FromSampleJson(JsonSerializer.Serialize(AutoFaker.Generate <ExtractResponse>())).ToJson();

            //Act

            //Assert
            Assert.Equal(expectedJsonSchema, actualJsonSchema);
        }
Exemple #6
0
        static void Main(string[] args)
        {
            string json           = File.ReadAllText("dcat-ap_2.0.0 (1).json");
            var    schemaFromFile = JsonSchema.FromSampleJson(json);
            var    classGenerator = new CSharpGenerator(schemaFromFile, new CSharpGeneratorSettings
            {
                ClassStyle = CSharpClassStyle.Poco,
            });
            var codeFile = classGenerator.GenerateFile();

            File.WriteAllText("DcatAp.cs", codeFile);
        }
Exemple #7
0
        static void Main(string[] cmd)
        {
            Console.WriteLine("JSONSchema to C# class");
            Devmasters.Args args = new Devmasters.Args(cmd, new string[] { "/schema" });

            string schema       = "";
            string fn           = "";
            string schemaSource = args["/schema"];

            if (schemaSource.StartsWith("http"))
            {
                schema = new System.Net.WebClient().DownloadString(schemaSource);
                fn     = System.IO.Path.GetFileName(new Uri(schemaSource).LocalPath);
            }
            else
            {
                schema = System.IO.File.ReadAllText(schemaSource);
                fn     = System.IO.Path.GetFileName(schemaSource);
            }
            if (string.IsNullOrEmpty(schema) || string.IsNullOrEmpty(fn))
            {
                Console.WriteLine("No schema available");
                return;
            }
            fn = fn + ".cs";
            var sch             = JsonSchema.FromSampleJson(schema);
            var classGenerator1 = new CSharpGenerator(sch, new CSharpGeneratorSettings
            {
                ClassStyle = CSharpClassStyle.Poco,
            });
            var codeFile1 = classGenerator1.GenerateFile();

            //var classGenerator2 = new CSharpGenerator(sch, new CSharpGeneratorSettings
            //{
            //    ClassStyle = CSharpClassStyle.Inpc,
            //});
            //var codeFile2 = classGenerator2.GenerateFile();
            //var classGenerator3 = new CSharpGenerator(sch, new CSharpGeneratorSettings
            //{
            //    ClassStyle = CSharpClassStyle.Prism,
            //});
            //var codeFile3 = classGenerator3.GenerateFile();

            //var classGenerator4 = new CSharpGenerator(sch, new CSharpGeneratorSettings
            //{
            //    ClassStyle = CSharpClassStyle.Record,
            //});
            //var codeFile4 = classGenerator4.GenerateFile();

            System.IO.File.WriteAllText(fn, codeFile1);
        }
Exemple #8
0
        private async Task <string> Generate(string json, CSharpGeneratorSettings settings, string name = "name")
        {
            var schema = JsonSchema.FromSampleJson(json);

            schema.AllowAdditionalProperties = false;
            schema.Title = name;

            string temp      = schema.ToJson();
            string temp2     = schema.ToString();
            var    generator = new CSharpGenerator(schema, settings);

            var code = generator.GenerateFile();

            return(code);
        }
Exemple #9
0
        private static async Task <(string csharpfile, string jsonschema)> GenerateFileContentFromSchema(string input, string @namespace)
        {
            var        json = File.ReadAllText(input);
            JsonSchema schema;

            if (json.Contains("$schema"))
            {
                schema = await JsonSchema.FromFileAsync(input);
            }
            else
            {
                schema = JsonSchema.FromSampleJson(json);
            }
            var generator = new CSharpGenerator(schema, new CSharpGeneratorSettings
            {
                Namespace = @namespace,
                GenerateDataAnnotations = false
            });
            var file = generator.GenerateFile();

            return(file, schema.ToJson());
        }
        public void MergedSchemas()
        {
            //// Arrange
            var data = @"{
    ""Address"": {
        ""Street"": [
            {
                ""Street"": ""Straße 1"",
                ""House"": {
                    ""Floor"": ""1"",
                    ""Number"": ""35""
                }
},
            {
                ""Street"": ""Straße 2"",
                ""House"": {
                    ""Floor"": ""2"",
                    ""Number"": ""54""
                }
            }
        ],
        ""@first_name"": ""Albert"",
        ""@last_name"": ""Einstein""
    }
}";

            //// Act
            var schema = JsonSchema.FromSampleJson(data);
            var json   = schema.ToJson();

            //// Assert
            Assert.Equal(3, schema.Definitions.Count);
            Assert.True(schema.Definitions.ContainsKey("Street"));
            Assert.True(schema.Definitions.ContainsKey("House"));
            Assert.True(schema.Definitions.ContainsKey("Address"));
        }
Exemple #11
0
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("Application accepts a parameter. The parameter should be a url of the configuration file"); return;
            }
            if (!File.Exists(args[0]))
            {
                Console.WriteLine("You need to provide existing configuration file url as a parameter."); return;
            }

            configFilePath = args[0];
            PrepareFilesAndFolders();

            string config = File.ReadAllText(configFilePath);

            string[] lines = config.Split(new char[] { '\r' });

            string authorization = lines[0].Replace("\n", "").Trim();

            HttpClient client = prepareClient(authorization);

            string urlPartToRemove = lines[1].Replace("\n", "").Trim();

            for (var i = 2; i < lines.Length; i++)
            {
                HttpResponseMessage response = null;
                var endpointUrl = lines[i].Replace("\n", "").Trim();

                try
                {
                    response = client.GetAsync(endpointUrl).Result;
                    if (response.StatusCode == HttpStatusCode.OK)
                    {
                        var schema            = JsonSchema.FromSampleJson(response.Content.ReadAsStringAsync().Result);
                        var currentSchema     = schema.ToJson().ToString();
                        var oldSchemaFilePath = GetSchemaFilePath(endpointUrl);

                        if (File.Exists(oldSchemaFilePath))
                        {
                            string oldSchema = File.ReadAllText(oldSchemaFilePath);
                            if (oldSchema != currentSchema)
                            {
                                if (!Directory.Exists(GetSchemaFolderPath() + "schema-old\\"))
                                {
                                    Directory.CreateDirectory(GetSchemaFolderPath() + "schema-old\\");
                                }
                                if (!Directory.Exists(GetSchemaFolderPath() + "schema-current\\"))
                                {
                                    Directory.CreateDirectory(GetSchemaFolderPath() + "schema-current\\");
                                }

                                string oldSchemaDiffFilePath     = GetSchemaFolderPath() + "schema-old\\" + GetSchemaFileName(endpointUrl.Replace(urlPartToRemove, "")) + ".txt";
                                string currentSchemaDiffFilePath = GetSchemaFolderPath() + "schema-current\\" + GetSchemaFileName(endpointUrl.Replace(urlPartToRemove, "")) + ".txt";

                                File.WriteAllText(oldSchemaDiffFilePath, endpointUrl + "\r\n\r\n" + oldSchema);
                                File.WriteAllText(currentSchemaDiffFilePath, endpointUrl + "\r\n\r\n" + currentSchema);

                                showError(endpointUrl, "Different schema\r\n\r\nOld:\r\n\r\n" + oldSchema + "\r\n\r\nNew:\r\n\r\n" + currentSchema);
                            }
                        }

                        if (args.Length > 1 && args[1] == "save")
                        {
                            if (!System.IO.Directory.Exists(GetSchemaFolderPath()))
                            {
                                System.IO.Directory.CreateDirectory(GetSchemaFolderPath());
                            }
                            File.WriteAllText(oldSchemaFilePath, currentSchema);
                        }
                    }
                    else
                    {
                        showError(endpointUrl, response.StatusCode.ToString() + "\r\n" + response);
                    }
                }
                catch (Exception ex)
                {
                    showError(endpointUrl, ex.ToString());
                }
            }


            File.WriteAllText(logFile, log);
            Console.WriteLine("Processing done. Log saved to " + logFile);
        }
Exemple #12
0
        static void Main(string[] args)
        {
            /*
             * Test project to illustrate how to manually generate a JSON schema
             * This is our test json which should validate against our schema
             *
             * [
             * {
             * "id":1,
             * "value":"one",
             * "enabled":false
             * },
             * {
             * "id":2,
             * "value":"two",
             * "enabled":true
             * }
             * ]
             *
             * This is what our schema should look like
             * {
             * "$schema": "http://json-schema.org/draft-06/schema#",
             * "type": "array",
             * "items": {
             * "$ref": "#/definitions/DataRowElement"
             * },
             * "definitions": {
             * "DataRowElement": {
             * "type": "object",
             * "additionalProperties": false,
             * "properties": {
             *  "id": {
             *      "type": "integer"
             *  },
             *  "value": {
             *      "type": "string"
             *  },
             *  "enabled": {
             *      "type": "boolean"
             *  }
             * },
             * "required": [
             *  "enabled",
             *  "id",
             *  "value"
             * ],
             * "title": "DataRowElement"
             * }
             * }
             * }
             */


            var testJson = @"[
    {
        ""id"":1,
        ""value"":""one"",
        ""enabled"":false
    },
    {
        ""id"":2,
        ""value"":""two"",
        ""enabled"":true
    }
]";

            var testSchema = JsonSchema.FromSampleJson(testJson);

            var testSchemaJson = testSchema.ToJson();

            Console.WriteLine(testSchemaJson);

            var objectSchema = new JsonSchema();

            objectSchema.Type             = JsonObjectType.Object;
            objectSchema.Title            = "DataRowElement";
            objectSchema.Properties["id"] = new JsonSchemaProperty {
                Type = JsonObjectType.Integer
            };
            objectSchema.Properties["value"] = new JsonSchemaProperty {
                Type = JsonObjectType.String
            };
            objectSchema.Properties["enabled"] = new JsonSchemaProperty {
                Type = JsonObjectType.Boolean
            };

            var schemaJson = objectSchema.ToJson();

            Console.WriteLine(schemaJson);
            Console.WriteLine("All good so far, this is our reference schema for our array elements");

            var arraySchema = new JsonSchema();

            arraySchema.Type = JsonObjectType.Array;
            arraySchema.Definitions["DataRowElement"] = objectSchema;

            // Aha, now we set the "item" of our outer array schema to a reference to our inner schema
            arraySchema.Item = new JsonSchema {
                Reference = objectSchema
            };

            schemaJson = arraySchema.ToJson();
            Console.WriteLine(schemaJson);

            Console.WriteLine("Success");

            Console.WriteLine("Any key to exit");
            Console.ReadKey();
        }
 public string GetJsonSchema(string json) => JsonSchema.FromSampleJson(json).ToJson();