예제 #1
0
        public async Task <IActionResult> UpdateDatamodel(string org, string app, string modelName)
        {
            SchemaKeywordCatalog.Add <InfoKeyword>();

            try
            {
                modelName = modelName.AsFileName();
            }
            catch
            {
                return(BadRequest("Invalid model name value."));
            }

            string filePath = $"App/models/{modelName}";

            using (Stream resource = Request.Body)
            {
                // Read the request body and deserialize to Json Schema
                using StreamReader streamReader = new StreamReader(resource);
                string content = await streamReader.ReadToEndAsync();

                TextReader textReader = new StringReader(content);
                JsonValue  jsonValue  = await JsonValue.ParseAsync(textReader);

                JsonSchema jsonSchemas = new Manatee.Json.Serialization.JsonSerializer().Deserialize <JsonSchema>(jsonValue);

                // Create the directory if it does not exist
                string appPath   = _repository.GetAppPath(org, app);
                string directory = appPath + Path.GetDirectoryName(filePath);
                if (!Directory.Exists(directory))
                {
                    Directory.CreateDirectory(directory);
                }

                // Serialize and store the Json Schema
                var          serializer = new Manatee.Json.Serialization.JsonSerializer();
                JsonValue    toar       = serializer.Serialize(jsonSchemas);
                byte[]       byteArray  = Encoding.UTF8.GetBytes(toar.ToString());
                MemoryStream jsonstream = new MemoryStream(byteArray);
                await _repository.WriteData(org, app, $"{filePath}.schema.json", jsonstream);

                // update meta data
                JsonSchemaToInstanceModelGenerator converter = new JsonSchemaToInstanceModelGenerator(org, app, jsonSchemas);
                ModelMetadata modelMetadata = converter.GetModelMetadata();
                string        root          = modelMetadata.Elements != null && modelMetadata.Elements.Count > 0 ? modelMetadata.Elements.Values.First(e => e.ParentElement == null).TypeName : null;
                _repository.UpdateApplicationWithAppLogicModel(org, app, modelName, "Altinn.App.Models." + root);

                // Convert to XML Schema and store in repository
                JsonSchemaToXsd jsonSchemaToXsd = new JsonSchemaToXsd();
                XmlSchema       xmlschema       = jsonSchemaToXsd.CreateXsd(jsonSchemas);
                MemoryStream    xsdStream       = new MemoryStream();
                XmlTextWriter   xwriter         = new XmlTextWriter(xsdStream, new UpperCaseUtf8Encoding());
                xwriter.Formatting = Formatting.Indented;
                xwriter.WriteStartDocument(false);
                xmlschema.Write(xsdStream);
                await _repository.WriteData(org, app, $"{filePath}.xsd", xsdStream);
            }

            return(Ok());
        }
예제 #2
0
        public async Task <IActionResult> UpdateDatamodel(string org, string app, string filepath)
        {
            SchemaKeywordCatalog.Add <InfoKeyword>();

            using (Stream resource = Request.Body)
            {
                // Read the request body and deserialize to Json Schema
                using StreamReader streamReader = new StreamReader(resource);
                string content = await streamReader.ReadToEndAsync();

                TextReader textReader = new StringReader(content);
                JsonValue  jsonValue  = await JsonValue.ParseAsync(textReader);

                JsonSchema jsonSchemas = new Manatee.Json.Serialization.JsonSerializer().Deserialize <JsonSchema>(jsonValue);

                // Serialize and store the Json Schema
                var          serializer = new Manatee.Json.Serialization.JsonSerializer();
                JsonValue    toar       = serializer.Serialize(jsonSchemas);
                byte[]       byteArray  = Encoding.UTF8.GetBytes(toar.ToString());
                MemoryStream jsonstream = new MemoryStream(byteArray);
                await _repository.WriteData(org, app, $"{filepath}.schema.json", jsonstream);

                // Convert to XML Schema and store in repository
                JsonSchemaToXsd jsonSchemaToXsd = new JsonSchemaToXsd();
                XmlSchema       xmlschema       = jsonSchemaToXsd.CreateXsd(jsonSchemas);
                MemoryStream    xsdStream       = new MemoryStream();
                XmlTextWriter   xwriter         = new XmlTextWriter(xsdStream, new UpperCaseUtf8Encoding());
                xwriter.Formatting = Formatting.Indented;
                xwriter.WriteStartDocument(false);
                xmlschema.Write(xsdStream);
                await _repository.WriteData(org, app, $"{filepath}.xsd", xsdStream);
            }

            return(Ok());
        }
예제 #3
0
        private static XmlSchema ConvertFromJsdToXsd(JsonSchema jsonSchema1, string fileName)
        {
            XmlSchema       xmlSchema2;
            JsonSchemaToXsd jsonConverter1 = new JsonSchemaToXsd();

            xmlSchema2 = jsonConverter1.CreateXsd(jsonSchema1);
            SaveXmlSchema(xmlSchema2, fileName);
            return(xmlSchema2);
        }
        public async void ConvertXsdToJsonSchemaAndBackViaString_CorrectNumberOfPropertiesAndDefinitions()
        {
            // string xsdName = "Designer.Tests._TestData.Model.Xsd.schema_3451_8_forms_4106_35721.xsd";
            string xsdName = "Designer.Tests._TestData.Model.Xsd.schema_4581_100_forms_5245_41111.xsd";

            SchemaKeywordCatalog.Add <InfoKeyword>();

            // Arrange
            XmlReader       xsdReader = XmlReader.Create(LoadTestData(xsdName));
            XsdToJsonSchema xsdToJsonSchemaConverter = new XsdToJsonSchema(xsdReader);

            // Act
            JsonSchema convertedSchema = xsdToJsonSchemaConverter.AsJsonSchema();

            JsonSerializer serializer = new JsonSerializer();
            JsonValue      serializedConvertedSchema = serializer.Serialize(convertedSchema);

            byte[]       byteArray  = Encoding.UTF8.GetBytes(serializedConvertedSchema.ToString());
            MemoryStream jsonstream = new MemoryStream(byteArray);

            await WriteData(xsdName + ".json", jsonstream);

            File.WriteAllText(xsdName + ".json", serializedConvertedSchema.ToString());

            string     savedJsonSchemaFileTextContent = File.ReadAllText(xsdName + ".json");
            TextReader textReader = new StringReader(savedJsonSchemaFileTextContent);
            JsonValue  jsonValue  = await JsonValue.ParseAsync(textReader);

            JsonSchema jsonSchemaFromFile = new Manatee.Json.Serialization.JsonSerializer().Deserialize <JsonSchema>(jsonValue);

            JsonSchemaToXsd jsonSchemaToXsd = new JsonSchemaToXsd();

            XmlSchema     xmlschema = jsonSchemaToXsd.CreateXsd(convertedSchema);
            MemoryStream  xmlStream = new MemoryStream();
            XmlTextWriter xwriter   = new XmlTextWriter(xmlStream, new UpperCaseUtf8Encoding());

            xwriter.Formatting = Formatting.Indented;
            xwriter.WriteStartDocument(false);
            xmlschema.Write(xmlStream);

            await WriteData(xsdName + ".new", xmlStream);

            XmlSchema     xmlschemaFromFile = jsonSchemaToXsd.CreateXsd(jsonSchemaFromFile);
            MemoryStream  xmlStreamFile     = new MemoryStream();
            XmlTextWriter xwriterFile       = new XmlTextWriter(xmlStreamFile, new UpperCaseUtf8Encoding());

            xwriterFile.Formatting = Formatting.Indented;
            xwriterFile.WriteStartDocument(false);
            xmlschemaFromFile.Write(xmlStreamFile);

            await WriteData(xsdName + ".newfile", xmlStreamFile);

            Assert.NotNull(convertedSchema);
        }
예제 #5
0
        public void ConvertFromAutogeneratedJsonSchemaToXsd()
        {
            string     schemaText = File.ReadAllText("Common/melding.schema.json");
            JsonValue  schemaJson = JsonValue.Parse(schemaText);
            JsonSchema schema     = new JsonSerializer().Deserialize <JsonSchema>(schemaJson);

            JsonSchemaToXsd converter = new JsonSchemaToXsd();
            XmlSchema       xmlSchema = converter.CreateXsd(schema);

            SaveXmlSchema(xmlSchema, "melding.generated.xsd");
        }
        public void ConvertXSDsToJsonSchema()
        {
            int failCount = 0;

            string[] files = Directory.GetFiles("Common/xsd", "*.xsd", SearchOption.AllDirectories);

            foreach (string file in files)
            {
                _logger.LogInformation("Converting file " + file + " to Json Schema");

                try
                {
                    // XSD to Json Schema
                    XsdToJsonSchema xsdToJsonSchemaConverter = new XsdToJsonSchema(new XmlTextReader(file), TestLogger.Create <XsdToJsonSchema>());
                    JsonSchema      schemaJsonSchema         = xsdToJsonSchemaConverter.AsJsonSchema();

                    // Json Schema to XSD
                    JsonSchemaToXsd jsonSchemaToXsdConverter = new JsonSchemaToXsd();
                    XmlSchema       xmlSchema = jsonSchemaToXsdConverter.CreateXsd(schemaJsonSchema);

                    // Load original file as XDocument
                    XDocument original = XDocument.Load(file);

                    // Load converted file as XDocument
                    XDocument     converted;
                    StringBuilder sb = new StringBuilder();
                    using (XmlWriter writer = XmlWriter.Create(sb))
                    {
                        xmlSchema.Write(writer);
                        converted = XDocument.Load(new StringReader(sb.ToString()));
                    }

                    // Compare XDocuments
                    bool xsdsAreEqual = XNode.DeepEquals(original, converted);
                    if (!xsdsAreEqual && writeDifferXsdFiles)
                    {
                        File.Copy(file, "c:\\temp\\original.xsd", true);
                        SaveJsonSchema(schemaJsonSchema, "c:\\temp\\converted.schema.json");
                        SaveXmlSchema(xmlSchema, "c:\\temp\\converted.xsd");
                    }

                    /*Assert.True(xsdsAreEqual);*/
                }
                catch (Exception e)
                {
                    _logger.LogError("Failed converting file " + file + ": " + e.Message);
                    failCount++;
                }
            }

            Assert.Equal(0, failCount);
        }
예제 #7
0
        public async Task InlineSchema_ShouldSerializeToCSharp()
        {
            var org = "yabbin";
            var app = "datamodelling";
            var jsonSchemaString = @"{""properties"":{""melding"":{""properties"":{""test"":{""type"":""object"",""properties"":{""navn"":{""type"":""string""}}}},""type"":""object""}},""definitions"":{}, ""required"": [""melding""]}";

            JsonSchema jsonSchema = await ParseJsonSchema(jsonSchemaString);

            ModelMetadata modelMetadata = GenerateModelMetadata(org, app, jsonSchema);
            string        classes       = GenerateCSharpClasses(modelMetadata);

            Assembly assembly = Compiler.CompileToAssembly(classes);

            Type type = assembly.GetType("Altinn.App.Models.melding");

            // Make sure the JSON can be serialized into the generated C# class
            // var json = @"{""melding"":{""test"":{""navn"":""Ronny""}}}";
            var    json    = @"{""test"":{""navn"":""Ronny""}}";
            object jsonObj = JsonSerializer.Deserialize(json, type);

            // Make sure the serialized JSON equals what we expect
            var jsonSerialized = new Manatee.Json.Serialization.JsonSerializer().Serialize(jsonObj);

            Assert.Equal(json, jsonSerialized.ToString());

            // Make sure the serialized JSON validates
            var jsonValidationResult = jsonSchema.Validate(new JsonValue(jsonSerialized.ToString()));

            Assert.True(jsonValidationResult.IsValid);

            // Validate JSON against JSON Schema (Manatee seems to think this is fine, but it's not ref. https://www.jsonschemavalidator.net/).
            jsonValidationResult = jsonSchema.Validate(new JsonValue(json), new JsonSchemaOptions()
            {
            });
            Assert.True(jsonValidationResult.IsValid);

            // Make sure the xml can be deserialized
            var    xml    = "<melding><test><navn>Ronny</navn></test></melding>";
            object xmlObj = SerializationHelper.Deserialize(xml, type);

            // Validate XML against generated XSD
            // OBS! On inline schemas the generated XSD only adds the root node, and does not traverse the properties.
            // This should be handled in the new XSD generator.
            JsonSchemaToXsd jsonSchemaToXsd    = new JsonSchemaToXsd();
            XmlSchema       xmlSchema          = jsonSchemaToXsd.CreateXsd(jsonSchema);
            var             xmlSchemaValidator = new XmlSchemaValidator(xmlSchema);

            Assert.True(xmlSchemaValidator.Validate(xml));

            // Do a deep compare, property by property, value by value
            jsonObj.Should().BeEquivalentTo(xmlObj);
        }
예제 #8
0
        private static Stream ConvertJsonSchemaToXsd(Manatee.Json.Schema.JsonSchema jsonSchema)
        {
            JsonSchemaToXsd jsonSchemaToXsd = new JsonSchemaToXsd();
            XmlSchema       xmlschema       = jsonSchemaToXsd.CreateXsd(jsonSchema);

            MemoryStream  xsdMemoryStream = new MemoryStream();
            XmlTextWriter xmlTextWriter   = new XmlTextWriter(xsdMemoryStream, new UpperCaseUtf8Encoding());

            xmlTextWriter.Formatting = Formatting.Indented;
            xmlTextWriter.WriteStartDocument(false);
            xmlschema.Write(xsdMemoryStream);

            xsdMemoryStream.Seek(0, SeekOrigin.Begin);

            return(xsdMemoryStream);
        }
예제 #9
0
        public void SeresSchema_ShouldSerializeToCSharp(string resourceName, string modelName, string json, string xml)
        {
            var org = "yabbin";
            var app = "hvem-er-hvem";

            JsonSchema    jsonSchema    = TestDataHelper.LoadDataFromEmbeddedResourceAsJsonSchema(resourceName);
            ModelMetadata modelMetadata = GenerateModelMetadata(org, app, jsonSchema);
            string        classes       = GenerateCSharpClasses(modelMetadata);

            Assembly assembly = Compiler.CompileToAssembly(classes);

            Type type = assembly.GetType(modelName);

            // Make sure the JSON can be serialized into the generated C# class
            object jsonObj = JsonSerializer.Deserialize(json, type);

            // Make sure the serialized JSON equals what we expect
            var jsonSerialized = new Manatee.Json.Serialization.JsonSerializer().Serialize(jsonObj);

            Assert.Equal(json, jsonSerialized.ToString());

            // Make sure the serialized JSON validates
            // Manatee fails on this, but not https://www.jsonschemavalidator.net/
            // var jsonValidationResult = jsonSchema.Validate(new JsonValue(jsonSerialized.ToString()));
            // Assert.True(jsonValidationResult.IsValid);

            // Validate JSON against JSON Schema (Manatee seems to think this is fine, but it's not ref. https://www.jsonschemavalidator.net/).
            // jsonValidationResult = jsonSchema.Validate(new JsonValue(json), new JsonSchemaOptions() { });
            // Assert.True(jsonValidationResult.IsValid);

            // Make sure the xml can be deserialized
            object xmlObj = SerializationHelper.Deserialize(xml, type);

            // Validate XML against generated XSD
            // OBS! On inline schemas the generated XSD only adds the root node, and does not traverse the properties.
            // This should be handled in the new XSD generator.
            JsonSchemaToXsd jsonSchemaToXsd    = new JsonSchemaToXsd();
            XmlSchema       xmlSchema          = jsonSchemaToXsd.CreateXsd(jsonSchema);
            var             xmlSchemaValidator = new XmlSchemaValidator(xmlSchema);

            Assert.True(xmlSchemaValidator.Validate(xml));

            // Do a deep compare, property by property, value by value
            jsonObj.Should().BeEquivalentTo(xmlObj);
        }
        public async void ConvertXsdToJsonSchemaAndBack_CorrectNumberOfPropertiesAndDefinitions()
        {
            // string xsdName = "Designer.Tests._TestData.Model.Xsd.schema_3451_8_forms_4106_35721.xsd";
            string xsdName = "Designer.Tests._TestData.Model.Xsd.schema_4581_100_forms_5245_41111.xsd";

            // Arrange
            XmlReader       xsdReader = XmlReader.Create(LoadTestData(xsdName));
            XsdToJsonSchema target    = new XsdToJsonSchema(xsdReader);

            // Act
            JsonSchema actual = target.AsJsonSchema();

            var       serializer = new JsonSerializer();
            JsonValue toar       = serializer.Serialize(actual);

            byte[]       byteArray  = Encoding.UTF8.GetBytes(toar.ToString());
            MemoryStream jsonstream = new MemoryStream(byteArray);

            await WriteData(xsdName + ".json", jsonstream);

            File.WriteAllText(xsdName + ".json", toar.ToString());

            JsonSchemaToXsd jsonSchemaToXsd = new JsonSchemaToXsd();

            XmlSchema     xmlschema = jsonSchemaToXsd.CreateXsd(actual);
            MemoryStream  xmlStream = new MemoryStream();
            XmlTextWriter xwriter   = new XmlTextWriter(xmlStream, new UpperCaseUtf8Encoding());

            xwriter.Formatting = Formatting.Indented;
            xwriter.WriteStartDocument(false);
            xmlschema.Write(xmlStream);

            await WriteData(xsdName + ".new", xmlStream);

            Assert.NotNull(actual);
        }
예제 #11
0
        public void ConvertXsdToJsonSchemaAndBack_CorrectNumberOfPropertiesAndDefinitions()
        {
            // Arrange
            XmlReader       xsdReader = XmlReader.Create(LoadTestData("Designer.Tests._TestData.xsd.melding-1603-12392.xsd"));
            XsdToJsonSchema target    = new XsdToJsonSchema(xsdReader);

            // Act
            JsonSchema actual = target.AsJsonSchema();

            JsonSchemaToXsd jsonSchemaToXsd = new JsonSchemaToXsd();

            XmlSchema xmlschema = jsonSchemaToXsd.CreateXsd(actual);

            FileStream    file    = new FileStream("Designer.Tests._TestData.xsd.melding-1603-12392b.xsd", FileMode.Create, FileAccess.ReadWrite);
            XmlTextWriter xwriter = new XmlTextWriter(file, new UTF8Encoding());

            xwriter.Formatting = Formatting.Indented;
            xmlschema.Write(xwriter);

            // Assert
            Assert.NotNull(actual);
            Assert.Equal(12, actual.Properties().Count);
            Assert.Equal(19, actual.Definitions().Count);
        }