public void CreateSampleXml()
        {
            var xsdFileName = dialogService.AskForFiles(false, FileType.Xsd).FirstOrDefault();

            if (string.IsNullOrEmpty(xsdFileName))
            {
                logger.Error("Empty file path");
                return;
            }

            var targetFileName = dialogService.AskFileNameSaveAs("sample.xml", FileType.Xml);

            if (string.IsNullOrEmpty(targetFileName))
            {
                logger.Error("Empty target file path");
                return;
            }

            var sampleGenerator = new XmlSampleGenerator(xsdFileName, XmlQualifiedName.Empty);

            using (var fileStream = new FileStream(targetFileName, FileMode.CreateNew))
                using (var xmlTextWriter = new XmlTextWriter(fileStream, Encoding.UTF8))
                {
                    xmlTextWriter.Formatting = Formatting.Indented;
                    sampleGenerator.WriteXml(xmlTextWriter);
                }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Smíðar XML-dæmi sem svarar til SOAP-skeytis.
        /// </summary>
        /// <param name="message">Nafn SOAP-skeytis.</param>
        /// <param name="schema">Nafn skemaskrár sem skilgreinir viðkomandi SOAP-skeyti.</param>
        /// <returns>XML-dæmi sem svarar til viðkomandi SOAP-skeytis.</returns>
        public static string GenerateXMLExample(string message, string schema)
        {
            XDocument xdocument = XDocument.Load(schema);

            StringBuilder sb = new StringBuilder();

            using (XmlWriter xmlWriter = XmlWriter.Create(sb))
            {
                string ns = String.Empty;

                if (Path.GetExtension(schema) == WSDL_SUFFIX)
                {
                    ns = xdocument.Element(WSDL_NAMESPACE + SCHEMA_DEFINITIONS).Element(WSDL_NAMESPACE + SCHEMA_TYPES).Element(XMLSCHEMA_NAMESPACE + SCHEMA).Attribute(XName.Get(SCHEMA_TARGET_NAMESPACE)).Value;

                    schema = Path.Combine(Path.GetDirectoryName(schema), TEMP_SCHEMA_FILE);

                    try
                    {
                        File.Delete(schema);
                    }
                    catch
                    { }

                    if (!File.Exists(schema))
                    {
                        IEnumerable <XAttribute> attributes = xdocument.Element(WSDL_NAMESPACE + SCHEMA_DEFINITIONS).Attributes();

                        foreach (XAttribute attribute in attributes)
                        {
                            if (xdocument.Element(WSDL_NAMESPACE + SCHEMA_DEFINITIONS).Element(WSDL_NAMESPACE + SCHEMA_TYPES).Element(XMLSCHEMA_NAMESPACE + SCHEMA).Attribute(attribute.Name) == null)
                            {
                                xdocument.Element(WSDL_NAMESPACE + SCHEMA_DEFINITIONS).Element(WSDL_NAMESPACE + SCHEMA_TYPES).Element(XMLSCHEMA_NAMESPACE + SCHEMA).Add(attribute);
                            }
                        }

                        xdocument.Element(WSDL_NAMESPACE + SCHEMA_DEFINITIONS).Element(WSDL_NAMESPACE + SCHEMA_TYPES).Element(XMLSCHEMA_NAMESPACE + SCHEMA).Save(schema);
                    }
                }
                else if (Path.GetExtension(schema) == XSD_SUFFIX)
                {
                    ns = xdocument.Element(XMLSCHEMA_NAMESPACE + SCHEMA).Attribute(XName.Get(SCHEMA_TARGET_NAMESPACE)).Value;
                }
                else
                {
                    throw new Exception();
                }

                XmlQualifiedName qn = new XmlQualifiedName(message, ns);

                XmlSampleGenerator generator = new XmlSampleGenerator(schema, qn);
                generator.WriteXml(xmlWriter);
            }

            return(sb.ToString());
        }
        private void button2_Click(object sender, EventArgs e)
        {
            string        t1         = DateTime.Now.ToString().Replace(@"/", "").Replace(" ", "").Replace(":", "");
            XmlTextWriter textWriter = new XmlTextWriter(t1 + ".xml", null);

            textWriter.Formatting = Formatting.Indented;
            XmlQualifiedName   qname     = new XmlQualifiedName("SendFAX", "http://www.childmaintenance.gsi.gov.uk/futurescheme/outboundCorrespondence/faxgateway/1.0");
            XmlSampleGenerator generator = new XmlSampleGenerator("..\\..\\XSDs\\FAXGateway.xsd", qname);

            generator.WriteXml(textWriter);
        }
Exemplo n.º 4
0
        public void button1_Click(object sender, EventArgs e)
        {
            var path = System.IO.Path.GetDirectoryName(
                System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
            XmlTextWriter textWriter = new XmlTextWriter("FAXGateway.xml", null);

            textWriter.Formatting = Formatting.Indented;
            XmlQualifiedName   qname     = new XmlQualifiedName("SendOutboundFAX", "http://www.childmaintenance.gsi.gov.uk");
            XmlSampleGenerator generator = new XmlSampleGenerator("Schemas\\FAXGateway.xsd", qname);

            generator.WriteXml(textWriter);
        }
Exemplo n.º 5
0
        private void button3_Click(object sender, EventArgs e)
        {
            string        t          = DateTime.Now.ToString().Replace(@"/", "").Replace(" ", "").Replace(":", "");
            var           path       = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase);
            XmlTextWriter textWriter = new XmlTextWriter("FAXmessage" + t + ".xml", null);

            textWriter.Formatting = Formatting.Indented;
            XmlQualifiedName   qname     = new XmlQualifiedName("SendOutboundFAX", "");
            XmlSampleGenerator generator = new XmlSampleGenerator("..\\..\\Schemas\\FAXGateway.xsd", qname); /* The "..\..\" are to avoid moving the Schema directory to the Debug directory - for some reason the system was looking for the schema file in .\bin\Debug\Schemas */

            generator.WriteXml(textWriter);
            MessageBox.Show("Done!");
        }
Exemplo n.º 6
0
        public string ReadSchemaFromXmlTextReader(string filename)
        {
            var xmlString = new StringWriter();

            if (filename != null)
            {
                using (var stream = new MemoryStream(File.ReadAllBytes(filename)))
                {
                    var schema = XmlSchema.Read(XmlReader.Create(stream), null);
                    var gen    = new XmlSampleGenerator(schema, new XmlQualifiedName("rootElement"));
                    //gen.WriteXml(XmlWriter.Create(@"c:\temp\autogen.xml"));
                    gen.WriteXml(XmlWriter.Create(xmlString));
                }
            }
            return(xmlString.ToString());
        }
Exemplo n.º 7
0
        public string GenerateXMLInstanceFromSchema()
        {
            StringBuilder xmlOutString = new StringBuilder();

            using (StringWriter xmlString = new StringWriter(xmlOutString))
            {
                using (XmlTextWriter textWriter = new XmlTextWriter(xmlString))
                {
                    textWriter.Formatting = Formatting.Indented;
                    XmlSampleGenerator genr = new XmlSampleGenerator(schemas, qname);
                    //genr.MaxThreshold = 0;
                    //genr.ListLength = 1;
                    genr.WriteXml(textWriter);
                }
            }

            return(xmlOutString.ToString());
        }
Exemplo n.º 8
0
        public static string Generate(string xml, string elem)
        {
            XmlDocument xmlDoc = new XmlDocument();
            string ret = "";

            using (StringWriter sWriter = new StringWriter())
            {
                using (XmlWriter xWriter = XmlTextWriter.Create(sWriter, new XmlWriterSettings()
                {
                    Indent = true
                }))
                {
                    using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
                    {
                        xmlDoc.Load(stream);
                        XmlNamespaceManager ns = new XmlNamespaceManager(xmlDoc.NameTable);
                        ns.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema");
                        using (XmlNodeList childNodes = xmlDoc.SelectNodes("xsd:schema/xsd:element[@name!='" + elem + "']", ns))
                        {
                            foreach (XmlNode childNode in childNodes)
                            {
                                childNode.ParentNode.RemoveChild(childNode);
                            }
                        }
                        XmlSchema schema = XmlSchema.Read(new XmlNodeReader(xmlDoc), null);
                        schema.Namespaces.Add("wd", "urn:com.workday/bsvc");
                        XmlSampleGenerator gen = new XmlSampleGenerator(schema, null);
                        gen.ListLength = 1;
                        gen.MaxThreshold = 1;

                        gen.WriteXml(xWriter);
                    }

                    ret = sWriter.ToString();
                    ret = ret.Replace("p2=", "wd=");
                    ret = ret.Replace("p2:", "wd:");
                    ret = ret.Replace("encoding=\"utf-16\"", "encoding=\"UTF-8\"");
                }
            }
            return ret;
        }
Exemplo n.º 9
0
        public static void Main(string[] args)
        {
            XmlSchemaSet     schemas   = new XmlSchemaSet();
            XmlQualifiedName qname     = XmlQualifiedName.Empty;
            string           localName = string.Empty;
            string           ns        = string.Empty;
            int max        = 0;
            int listLength = 0;

            for (int i = 0; i < args.Length; i++)
            {
                string arg      = args[i];
                string value    = string.Empty;
                bool   argument = false;

                if (arg.StartsWith("/") || arg.StartsWith("-"))
                {
                    argument = true;
                    int colonPos = arg.IndexOf(":");
                    if (colonPos != -1)
                    {
                        value = arg.Substring(colonPos + 1);
                        arg   = arg.Substring(0, colonPos);
                    }
                }
                arg = arg.ToLower(CultureInfo.InvariantCulture);
                if (!argument && arg.EndsWith(".xsd"))
                {
                    schemas.Add(null, args[i]);
                }
                else if (ArgumentMatch(arg, "?") || ArgumentMatch(arg, "help"))
                {
                    WriteHelp();
                    return;
                }
                else if (ArgumentMatch(arg, "localname"))
                {
                    localName = value;
                }
                else if (ArgumentMatch(arg, "namespace"))
                {
                    ns = value;
                }
                else if (ArgumentMatch(arg, "maxthreshold"))
                {
                    max = Int16.Parse(value);
                }
                else if (ArgumentMatch(arg, "listlength"))
                {
                    listLength = Int16.Parse(value);
                }
                else
                {
                    throw new ArgumentException(args[i]);
                }
            }

            if (args.Length == 0)
            {
                WriteHelp();
                return;
            }
            XmlTextWriter textWriter = new XmlTextWriter("Sample.xml", null);

            textWriter.Formatting = Formatting.Indented;
            XmlSampleGenerator genr = new XmlSampleGenerator(schemas, qname);

            if (max > 0)
            {
                genr.MaxThreshold = max;
            }
            if (listLength > 0)
            {
                genr.ListLength = listLength;
            }
            genr.WriteXml(textWriter);
        }
Exemplo n.º 10
0
        private void DeserializeSampleXml(string pattern, Assembly assembly)
        {
            var files = Glob.Glob.ExpandNames(pattern);

            var set = new XmlSchemaSet();

            var schemas = files.Select(f => XmlSchema.Read(XmlReader.Create(f), (s, e) =>
            {
                Assert.True(false, e.Message);
            }));

            foreach (var s in schemas)
            {
                set.Add(s);
            }

            set.Compile();

            foreach (var rootElement in set.GlobalElements.Values.Cast <XmlSchemaElement>().Where(e => !e.IsAbstract))
            {
                var type       = FindType(assembly, rootElement.QualifiedName);
                var serializer = new XmlSerializer(type);
                var generator  = new XmlSampleGenerator(set, rootElement.QualifiedName);
                var sb         = new StringBuilder();
                using (var xw = XmlWriter.Create(sb, new XmlWriterSettings {
                    Indent = true
                }))
                {
                    // generate sample xml
                    generator.WriteXml(xw);
                    var xml = sb.ToString();

                    File.WriteAllText("xml.xml", xml);

                    // deserialize from sample
                    var sr = new StringReader(xml);
                    var o  = serializer.Deserialize(sr);

                    // serialize back to xml
                    var xml2 = Serialize(serializer, o);

                    File.WriteAllText("xml2.xml", xml2);

                    // validate serialized xml
                    XmlReaderSettings settings = new XmlReaderSettings
                    {
                        ValidationType = ValidationType.Schema,
                        Schemas        = set
                    };

                    settings.ValidationEventHandler += (s, e) =>
                    {
                        // generator doesn't generate valid values where pattern restrictions exist, e.g. email
                        if (!e.Message.Contains("The Pattern constraint failed"))
                        {
                            Assert.True(false, e.Message);
                        }
                    };

                    XmlReader reader = XmlReader.Create(new StringReader(xml2), settings);
                    while (reader.Read())
                    {
                        ;
                    }

                    // deserialize again
                    sr = new StringReader(xml2);
                    var o2 = serializer.Deserialize(sr);

                    AssertEx.Equal(o, o2);
                }
            }
        }
Exemplo n.º 11
0
        private void btnGenerate_Click(object sender, RoutedEventArgs e)
        {
            XmlSchemaSet     schemas = new XmlSchemaSet();
            XmlQualifiedName qname;
            object           selItem = cboRoot.SelectedItem;

            if (selItem == null)
            {
                qname = XmlQualifiedName.Empty;
            }
            else
            {
                qname = new XmlQualifiedName(selItem.ToString());
            }

            int max        = 0;
            int listLength = 0;

            try
            {
                schemas.Add(null, _currentFileName);
            }
            catch (Exception ex)
            {
                MessageBox.Show(Application.Current.MainWindow, "Error in XSD file: " + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            if (!string.IsNullOrEmpty(edtMaxThreshold.Text))
            {
                max = Int16.Parse(edtMaxThreshold.Text);
            }
            if (!string.IsNullOrEmpty(edtListLength.Text))
            {
                listLength = Int16.Parse(edtListLength.Text);
            }

            try
            {
                using (StringWriter writer = new StringWriter())
                    using (XmlTextWriter textWriter = new XmlTextWriter(writer))
                    {
                        textWriter.Formatting = Formatting.Indented;
                        XmlSampleGenerator genr = new XmlSampleGenerator(schemas, qname);

                        if (max > 0)
                        {
                            genr.MaxThreshold = max;
                        }
                        if (listLength > 0)
                        {
                            genr.ListLength = listLength;
                        }
                        genr.WriteXml(textWriter);

                        edtResult.Text = writer.ToString();
                    }

                _foldingStrategy.UpdateFoldings(_foldingManager, edtResult.Document);
            }
            catch (Exception ex)
            {
                MessageBox.Show(Application.Current.MainWindow, "Error: " + ex.Message, "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Exemplo n.º 12
0
        public Mensagem LerXsd(string xsdPath, string nomeMensagem)
        {
            Mensagem mensagem = new Mensagem();

            mensagem.nome = nomeMensagem;
            using (var stream = new MemoryStream(File.ReadAllBytes(xsdPath)))
            {
                var schema = XmlSchema.Read(XmlReader.Create(stream), null);
                var gen    = new XmlSampleGenerator(schema, new XmlQualifiedName("rootElement"));

                try
                {
                    var xmlString = new StringWriter();
                    gen.WriteXml(XmlWriter.Create(xmlString));
                    //var texto = xmlString.ToString();
                    if (!xmlString.ToString().Equals(""))
                    {
                        XmlDocument document = new XmlDocument();
                        document.LoadXml(xmlString.ToString());
                        mensagem.xml = xmlString.ToString();
                        XmlElement    root = document.DocumentElement;
                        StringBuilder sb   = new StringBuilder("<form> <br>");
                        foreach (XmlNode noPrincipal in root.ChildNodes)
                        {
                            sb.Append("<fieldset> <legend>" + noPrincipal.Name + "</legend> </br>");
                            bool noTemFilhos = noPrincipal.HasChildNodes;

                            //Console.WriteLine(noPrincipal.Name);
                            foreach (XmlNode subNo in noPrincipal.ChildNodes)
                            {
                                //input
                                //ou um field novo
                                // Console.WriteLine(subNo.Name);
                                if (subNo.ChildNodes.Count > 1)
                                {
                                    bool subNoFilho = subNo.HasChildNodes;
                                    sb.Append("<fieldset> <legend>" + subNo.Name + "</legend> </br>");
                                    foreach (XmlNode subNo2 in subNo.ChildNodes)
                                    {
                                        sb.Append("<label>" + subNo2.Name + "<label/>");
                                        sb.Append("<input type='text' value=" + subNo2.Name + "'/></br>");
                                        //Console.WriteLine(subNo2.Name);
                                        bool subNoFilho2 = subNo2.HasChildNodes;
                                    }
                                    sb.Append("</fieldset>");
                                }
                                else
                                {
                                    if (subNo.Name.Contains("text"))
                                    {
                                        sb.Append("<label>" + subNo.InnerText + "<label/>");
                                        sb.Append("<input type='text' value=" + subNo.InnerText + "'/></br>");
                                    }
                                    else
                                    {
                                        sb.Append("<label>" + subNo.Name + "<label/>");
                                        sb.Append("<input type='text' value=" + subNo.Name + "'/></br>");
                                    }
                                }
                            }
                            sb.Append("</fieldset>");
                            //fechar o field set
                        }
                        sb.Append("</form>");
                        mensagem.html = sb.ToString();
                        return(mensagem);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Erro ao ler:" + xsdPath);
                }
            }

            return(null);
        }
Exemplo n.º 13
0
        private void DeserializeSampleXml(string pattern, Assembly assembly)
        {
            var files = Glob.ExpandNames(pattern);

            var set = new XmlSchemaSet();

            var schemas = files.Select(f => XmlSchema.Read(XmlReader.Create(f), (s, e) =>
            {
                Assert.True(false, e.Message);
            }));

            foreach (var s in schemas)
            {
                set.Add(s);
            }

            set.Compile();

            var anyValidXml = false;

            foreach (var rootElement in set.GlobalElements.Values.Cast <XmlSchemaElement>().Where(e => !e.IsAbstract && !(e.ElementSchemaType is XmlSchemaSimpleType)))
            {
                var type       = FindType(assembly, rootElement.QualifiedName);
                var serializer = new XmlSerializer(type);
                var generator  = new XmlSampleGenerator(set, rootElement.QualifiedName);
                var sb         = new StringBuilder();
                using (var xw = XmlWriter.Create(sb, new XmlWriterSettings {
                    Indent = true
                }))
                {
                    // generate sample xml
                    generator.WriteXml(xw);
                    var xml = sb.ToString();

                    File.WriteAllText("xml.xml", xml);

                    // validate serialized xml
                    var settings = new XmlReaderSettings
                    {
                        ValidationType = ValidationType.Schema,
                        Schemas        = set
                    };

                    var invalid = false;

                    void validate(object s, ValidationEventArgs e)
                    {
                        if (HandleValidationError(xml, e))
                        {
                            invalid = true;
                        }
                    }

                    settings.ValidationEventHandler += validate;

                    var reader = XmlReader.Create(new StringReader(xml), settings);
                    while (reader.Read())
                    {
                        ;
                    }

                    settings.ValidationEventHandler -= validate;

                    // generated xml is not schema valid -> skip
                    if (invalid)
                    {
                        continue;
                    }
                    anyValidXml = true;

                    // deserialize from sample
                    var sr = new StringReader(xml);
                    var o  = serializer.Deserialize(sr);

                    // serialize back to xml
                    var xml2 = Serialize(serializer, o);

                    File.WriteAllText("xml2.xml", xml2);

                    void validate2(object s, ValidationEventArgs e)
                    {
                        if (HandleValidationError(xml2, e))
                        {
                            throw e.Exception;
                        }
                    };

                    settings.ValidationEventHandler += validate2;

                    reader = XmlReader.Create(new StringReader(xml2), settings);
                    while (reader.Read())
                    {
                        ;
                    }

                    settings.ValidationEventHandler -= validate2;

                    // deserialize again
                    sr = new StringReader(xml2);
                    var o2 = serializer.Deserialize(sr);

                    AssertEx.Equal(o, o2);
                }
            }

            Assert.True(anyValidXml, "No valid generated XML for this test");
        }
Exemplo n.º 14
0
        static void Main(string[] args)
        {
            if (CreateOutputFolders() == false)
            {
                Console.ReadKey();
                Environment.Exit(99);
            }
            const string xsltFilePath = "xs3p.xsl";

            // Load XSLT
            XsltSettings         settings    = new XsltSettings(true, true);
            XslCompiledTransform transformer = new XslCompiledTransform();

            transformer.Load(xsltFilePath, settings, new XmlUrlResolver());

            string schemaProjectDirectory = System.Environment.CurrentDirectory + "\\XSD";

            // Look in the project output directory for all xsd files
            string[] files = Directory.GetFiles(schemaProjectDirectory, "*.xsd");

            // Create the output directories for the generated HTML files, and code example files
            //string outputDirectory = Path.Combine(Environment.CurrentDirectory, "Generated HTML Docs");
            //if (!Directory.Exists(outputDirectory))
            //    Directory.CreateDirectory(outputDirectory);

            //string exampleDirectory = Path.Combine(Environment.CurrentDirectory, "Generated Examples");
            //if (!Directory.Exists(exampleDirectory))
            //    Directory.CreateDirectory(exampleDirectory);

            // For each XSD file, create the HTML documentation, and examples (.cs, .vb, .xml, json)
            Console.WriteLine("Generating Files.....");
            foreach (string xsdFilePath in files)
            {
                //Don't create HTML documentation or XML samples for base schema
                if (xsdFilePath == schemaProjectDirectory + "\\Common.xsd" ||
                    xsdFilePath == schemaProjectDirectory + "\\ISOCountryCodeType-V2006.xsd" ||
                    xsdFilePath == schemaProjectDirectory + "\\ISOCurrencyCodeType.xsd" ||
                    xsdFilePath == schemaProjectDirectory + "\\MessageContext.xsd" ||
                    xsdFilePath == schemaProjectDirectory + "\\Meta.xsd")
                {
                    continue;
                }


                #region Generate the HTML documentation
                string outHtmlFileName = Path.Combine(sGeneratedPath + "\\HTML\\", Path.GetFileNameWithoutExtension(xsdFilePath)) + ".html";
                using (StreamWriter outHtmlfile = new StreamWriter(outHtmlFileName))
                {
                    string documentTitle = Path.GetFileNameWithoutExtension(xsdFilePath);
                    documentTitle = documentTitle.Replace("CUFX_", "");
                    documentTitle = documentTitle.Replace("_", " ");

                    XsltArgumentList argsList = new XsltArgumentList();
                    argsList.AddParam("title", "", documentTitle);
                    argsList.AddParam("currentDateTime", "", DateTime.Now.ToString("d"));

                    using (XmlTextReader xsdReader = new XmlTextReader(xsdFilePath))
                    {
                        XPathNavigator nav = new XPathDocument(xsdReader).CreateNavigator();

                        try
                        {
                            transformer.Transform(nav, argsList, outHtmlfile);
                        }
                        catch (XsltException xsltEx)
                        {
                            Console.WriteLine("Could not transform the XSD file [{0}]. Message: [{1}] line: [{2}], position: [{3}]", xsdFilePath, xsltEx.Message, xsltEx.LineNumber, xsltEx.LinePosition);
                            Console.ReadKey();
                        }
                        xsdReader.Close();
                    }
                    outHtmlfile.Close();
                    //Console.WriteLine("HTML Files Created");
                }
                #endregion

                #region Generate the XML/JSON examples
                string outXmlFileName = Path.Combine(sGeneratedPath + "\\XML\\", Path.GetFileNameWithoutExtension(xsdFilePath)) + ".xml";
                using (XmlTextWriter outXmlFile = new XmlTextWriter(outXmlFileName, null))
                {
                    outXmlFile.Formatting = System.Xml.Formatting.Indented;
                    XmlQualifiedName qname = new XmlQualifiedName("AccountList",
                                                                  "http://cufxstandards.com/v2/Account.xsd");
                    XmlSampleGenerator generator = new XmlSampleGenerator(xsdFilePath, qname);
                    generator.WriteXml(outXmlFile);
                    //Console.WriteLine("XML Files Created");
                }

                string outJSONFileName = Path.Combine(sGeneratedPath + "\\JSON\\", Path.GetFileNameWithoutExtension(xsdFilePath)) + ".json";
                JsonGenerator.GenerateJsonFromXml(outXmlFileName, outJSONFileName);
                #endregion

                // Generate one .cs for all the types and place it in the Schemas project
                //string cufxCsFile = Path.Combine(schemaProjectDirectory, "CUFX.cs");
                //string cufxCsFile = Path.Combine(sGeneratedPath + "\\WCF\\", Path.GetFileNameWithoutExtension(xsdFilePath)) + ".cs";
                //string cufxVbFile = Path.Combine(sGeneratedPath + "\\WCF\\", Path.GetFileNameWithoutExtension(xsdFilePath)) + ".vb";
                //CodeGenerator.GenerateCodeFromXsd(xsdFilePath, cufxCsFile, cufxVbFile);
                //CodeGenerator.GenerateCodeFromXsds(files, cufxCsFile);
                //JsonGenerator.GenerateJsonFromCs(cufxCsFile, Path.Combine(sGeneratedPath + "\\JSON\\", Path.GetFileNameWithoutExtension(cufxCsFile)) + ".json");

                //#region Generate the WCF examples
                //cufxCsFile = Path.Combine(sGeneratedPath + "\\WCF\\", Path.GetFileNameWithoutExtension(xsdFilePath)) + ".cs";
                //string cufxVbFile = Path.Combine(sGeneratedPath + "\\WCF\\", Path.GetFileNameWithoutExtension(xsdFilePath)) + ".vb";
                //CodeGenerator.GenerateCodeFromXsds(files, cufxCsFile);
                //CodeGenerator.GenerateCodeFromXsd(xsdFilePath, cufxCsFile, cufxVbFile);
                //Now Generate the WCF Files
                //Converter converter = new Converter(xsdFilePath);
                //bool wasSuccessful = converter.Convert(cufxCsFile);
                //#endregion
            }
            Console.WriteLine("HTML & XML Files Created.....");

            #region Generate the WCF examples
            // Generate one .cs for all the types and place it in the Schemas project
            string cufxCsFile = Path.Combine(sGeneratedPath + "\\WCF\\", "CUFX.cs");
            //CodeGeneratorV1.GenerateCodeFromXsds(files, sGeneratedPath + "\\WCF\\CUFX.vb", sGeneratedPath + "\\WCF\\CUFX.cs");

            //Working Single WCF Generator
            CodeGenerator.GenerateCodeFromXsds(files, cufxCsFile);

            //Now Generate the WCF File
            //Converter converter = new Converter(sGeneratedPath + "\\WCF\\CUFXTemp.cs");
            //bool wasSuccessful = converter.Convert(sGeneratedPath + "\\WCF\\CUFX.cs");
            //System.IO.File.Delete(sGeneratedPath + "\\WCF\\CUFXTemp.cs");

            //if (wasSuccessful)
            //{
            Console.WriteLine("WCF File Created");
            //}
            #endregion



            Console.WriteLine("JSON File Created");
            Console.WriteLine("Press any key to close");
            Console.ReadLine();
        }
Exemplo n.º 15
0
        public string BuildRequest(string operation)
        {
            // load operation's input message
            // MESSAGE = portType/operation[].(name=OPERATION)/input.message
            var operations    = wsdl_object.XPathElements($"/wsdl:portType[1]/wsdl:operation[@name='{operation}']/wsdl:input[1]", xml_ns_mgr);
            var input_message = operations.FirstOrDefault().Attribute("message").LocalValue(namespaces.Keys).value;

            // load message's main element
            // ELEMENT = message[].(name=MESSAGE)/(part.(name="body")).element
            var messages = wsdl_object.XPathElements($"/wsdl:message[@name='{input_message}']/wsdl:part[@element]", xml_ns_mgr);

            var(xsd_element, ns_prefix) = messages.FirstOrDefault().Attribute("element").LocalValue(namespaces.Keys);

            using var stream_xmldom = new MemoryStream();
            using var stream_schema = new MemoryStream();
            using var stream_sample = new MemoryStream();
            using var stream_xmlout = new MemoryStream();
            using var stream_reader = new StreamReader(stream_xmlout, true);
            using var xml_writer    = XmlWriter.Create(stream_sample);

            // extract XSD from WSDL
            var xelement_schema = wsdl_object.XPathElements("/wsdl:types/xsd:schema[1]", xml_ns_mgr).FirstOrDefault();

            // remove all <element ref="schema"> (causes problems in sample generation)
            var nodes = xelement_schema.XPathElements("//xsd:element[@ref]", xml_ns_mgr).ToList();

            foreach (var element in
                     from XElement element in nodes
                     where (element.Parent != null) && (element.Attribute("ref").LocalValue(namespaces.Keys).value == "schema")
                     select element)
            {
                element.Remove();
            }

            // add targetNamespace
            xelement_schema.Save(stream_xmldom, SaveOptions.DisableFormatting);
            var xml_dom_schema = new XmlDocument();

            stream_xmldom.Position = 0;
            xml_dom_schema.Load(stream_xmldom);
            xml_dom_schema.DocumentElement.SetAttribute($"xmlns:{ns_prefix}", targetNamespace);
            xml_dom_schema.Save(stream_schema);

            // generate sample XML from XSD
            stream_schema.Position = 0;
            var xml_schema = XmlSchema.Read(stream_schema, (s, v) => { throw new XmlSchemaException(v.Message); });
            var generator  = new XmlSampleGenerator(xml_schema, new XmlQualifiedName(xsd_element, targetNamespace));

            generator.WriteXml(xml_writer);
            xml_writer.Flush();

            // load XML
            var xml_dom_inner = new XmlDocument();

            stream_sample.Position = 0;
            xml_dom_inner.Load(stream_sample);

            // create SOAP envelope
            var xml_dom_outer = new XmlDocument()
            {
                PreserveWhitespace = false
            };
            var elm_envelope  = xml_dom_outer.CreateElement("soap", "Envelope", NS_ENV);
            var elm_body      = xml_dom_outer.CreateElement("soap", "Body", NS_ENV);
            var elm_operation = xml_dom_outer.CreateElement(operation, targetNamespace);

            foreach (var node in
                     from XmlNode? node in xml_dom_inner.DocumentElement.ChildNodes
                     where node !.NodeType == XmlNodeType.Element
                     select node)
            {
                elm_operation.AppendChild(xml_dom_outer.ImportNode(node, true));
            }
            elm_body.AppendChild(elm_operation);
            elm_envelope.AppendChild(elm_body);
            xml_dom_outer.AppendChild(elm_envelope);
            xml_dom_outer.DocumentElement.SetAttribute("xmlns:xsi", NS_XSI);
            xml_dom_outer.DocumentElement.SetAttribute("xmlns:xsd", NS_XSD);
            xml_dom_outer.Save(stream_xmlout);

            // output SOAP
            stream_xmlout.Position = 0;
            var xml_string = stream_reader.ReadToEnd();

            return(xml_string);
        }