public virtual string ImportAnyElement ( XmlSchemaAny any, bool mixed, XmlSchemas schemas, XmlSchemaImporter importer, CodeCompileUnit compileUnit, CodeNamespace mainNamespace, CodeGenerationOptions options, CodeDomProvider codeProvider ) { return null; }
public virtual string ImportSchemaType ( XmlSchemaType type, XmlSchemaObject context, XmlSchemas schemas, XmlSchemaImporter importer, CodeCompileUnit compileUnit, CodeNamespace mainNamespace, CodeGenerationOptions options, CodeDomProvider codeProvider ) { return null; }
//<snippet1> public override string ImportSchemaType(string name, string ns, XmlSchemaObject context, XmlSchemas schemas, XmlSchemaImporter importer, CodeCompileUnit compileUnit, CodeNamespace codeNamespace, CodeGenerationOptions options, CodeDomProvider codeGenerator) { if (name.Equals("Order") && ns.Equals("http://orders/")) { compileUnit.ReferencedAssemblies.Add("Order.dll"); codeNamespace.Imports.Add (new CodeNamespaceImport("Microsoft.Samples")); return("Order"); } return(null); }
public static void GenerateCode(string xsdFilepath, string codeOutPath, string nameSpace) { FileStream stream = File.OpenRead(xsdFilepath); XmlSchema xsd = XmlSchema.Read(stream, ValidationCallbackOne); // Remove namespaceattribute from schema xsd.TargetNamespace = null; XmlSchemas xsds = new XmlSchemas { xsd }; XmlSchemaImporter imp = new XmlSchemaImporter(xsds); //imp.Extensions.Add(new CustomSchemaImporterExtension()); CodeNamespace ns = new CodeNamespace(nameSpace); XmlCodeExporter exp = new XmlCodeExporter(ns); foreach (XmlSchemaObject item in xsd.Items) { if (!(item is XmlSchemaElement)) { continue; } XmlSchemaElement xmlSchemaElement = (XmlSchemaElement)item; XmlQualifiedName xmlQualifiedName = new XmlQualifiedName(xmlSchemaElement.Name, xsd.TargetNamespace); XmlTypeMapping map = imp.ImportTypeMapping(xmlQualifiedName); exp.ExportTypeMapping(map); } // Remove all the attributes from each type in the CodeNamespace, except // System.Xml.Serialization.XmlTypeAttribute RemoveAttributes(ns); ToProperties(ns); CodeCompileUnit compileUnit = new CodeCompileUnit(); compileUnit.Namespaces.Add(ns); CSharpCodeProvider provider = new CSharpCodeProvider(); using (StreamWriter sw = new StreamWriter(codeOutPath, false)) { CodeGeneratorOptions codeGeneratorOptions = new CodeGeneratorOptions(); provider.GenerateCodeFromCompileUnit(compileUnit, sw, codeGeneratorOptions); } }
public Parser(WSDescriber wsDesc, ref bool untrustedSSLSecureChannel, ref List <Param> respHeader) { HttpWebRequest wr = GetHttpWebReq(wsDesc); HttpWebResponse wres = null; try { wres = (HttpWebResponse)wr.GetResponse(); } catch (WebException wex) { if (wex.Status == WebExceptionStatus.TrustFailure) { ServicePointManager.ServerCertificateValidationCallback = delegate { return(true); }; wr = GetHttpWebReq(wsDesc); wres = (HttpWebResponse)wr.GetResponse(); untrustedSSLSecureChannel = true; } } if (wres != null) { for (int i = 0; i < wres.Headers.Count; ++i) { respHeader.Add(new Param() { Name = wres.Headers.Keys[i].ToLowerInvariant(), Value = wres.Headers[i].ToLowerInvariant() }); } StreamReader streamReader = new StreamReader(wres.GetResponseStream()); rawWSDL = XDocument.Parse(streamReader.ReadToEnd()); TextReader myTextReader = new StringReader(rawWSDL.ToString()); serviceDescription = ServiceDescription.Read(myTextReader); TargetNameSpace = serviceDescription.TargetNamespace; bindColl = serviceDescription.Bindings; portTypColl = serviceDescription.PortTypes; msgColl = serviceDescription.Messages; types = serviceDescription.Types; schemas = types.Schemas; } }
/// <summary> /// Get schema /// </summary> public XmlSchema GetSchema(int schemaId) { this.ThrowIfNotReady(); XmlSchemas schemaCollection = new XmlSchemas(); XmlReflectionImporter importer = new XmlReflectionImporter("http://hl7.org/fhir"); XmlSchemaExporter exporter = new XmlSchemaExporter(schemaCollection); foreach (var cls in typeof(FhirServiceBehavior).Assembly.GetTypes().Where(o => o.GetCustomAttribute <XmlRootAttribute>() != null && !o.IsGenericTypeDefinition)) { exporter.ExportTypeMapping(importer.ImportTypeMapping(cls, "http://hl7.org/fhir")); } return(schemaCollection[schemaId]); }
static void SerializarSchema(Type tipo, string nomeArquivo) { var schemas = new XmlSchemas(); var exporter = new XmlSchemaExporter(schemas); var mapping = new XmlReflectionImporter().ImportTypeMapping(tipo); exporter.ExportTypeMapping(mapping); TextWriter writer = new StreamWriter(nomeArquivo); foreach (XmlSchema schema in schemas) { schema.Write(writer); } writer.Dispose(); }
public ServiceDescriptionImporter() { this.serviceDescriptions = new ServiceDescriptionCollection(); this.schemas = new XmlSchemas(); this.allSchemas = new XmlSchemas(); this.options = System.Xml.Serialization.CodeGenerationOptions.GenerateOldAsync; this.abstractSchemas = new XmlSchemas(); this.concreteSchemas = new XmlSchemas(); Type[] protocolImporterTypes = WebServicesSection.Current.ProtocolImporterTypes; this.importers = new ProtocolImporter[protocolImporterTypes.Length]; for (int i = 0; i < this.importers.Length; i++) { this.importers[i] = (ProtocolImporter)Activator.CreateInstance(protocolImporterTypes[i]); this.importers[i].Initialize(this); } }
public void Generate(XmlSchemas schemas, CodeNamespace codeNamespace, CodeCompileUnit codeCompileUnit) { this.schemas = schemas; this.codeCompileUnit = codeCompileUnit; this.codeNamespace = codeNamespace; codeCompileUnit.Namespaces.Add(codeNamespace); foreach (XmlSchema schema in schemas) { GenerateSchemaTypes(schema); } new CSharpCodeProvider().CreateGenerator().GenerateCodeFromCompileUnit(codeCompileUnit, Console.Out, null); }
static XmlQualifiedName StaticGetSchema(XmlSchemaSet schemaSet) { XmlReflectionImporter importer = new XmlReflectionImporter(); XmlTypeMapping xmlTypeMapping = importer.ImportTypeMapping(typeof(T)); XmlSchemas schemas = new XmlSchemas(); XmlSchemaExporter exporter = new XmlSchemaExporter(schemas); exporter.ExportTypeMapping(xmlTypeMapping); schemas.Compile(new ValidationEventHandler(ValidationCallbackWithErrorCode), true); for (int i = 0; i < schemas.Count; i++) { XmlSchema schema = schemas[i]; schemaSet.Add(schema); } return(new XmlQualifiedName(xmlTypeMapping.TypeName, xmlTypeMapping.Namespace)); }
public Valida(ServiceDescription service) { _services.Add(service); _schemas=service.Types.Schemas ; if (service.Name == string.Empty) service.Name=service.RetrievalUrl; if (service.Name == string.Empty) service.Name=service.TargetNamespace; ServiceNode=new TreeNode(service.Name); ServiceNode.Tag=service.Documentation ; ServiceNode.ImageIndex=15; ServiceNode.SelectedImageIndex=15; Parse(); ServiceNode.Expand (); }
static XmlSchema GetSchema(Type t) { XmlReflectionImporter xri = new XmlReflectionImporter(); XmlTypeMapping xtm = xri.ImportTypeMapping(t); XmlSchemas schemas = new XmlSchemas(); XmlSchemaExporter xse = new XmlSchemaExporter(schemas); xse.ExportTypeMapping(xtm); foreach (XmlSchema xs in schemas) { return(xs); } return(null); }
static void Main(string[] args) { var xmlSchemas = new XmlSchemas(); xmlSchemas.Add(XmlSchema.Read(File.OpenRead("contacts.xsd"), validationHandler)); xmlSchemas.Compile(validationHandler, true); XmlSchemaImporter schemaImporter = new XmlSchemaImporter(xmlSchemas); CodeNamespace codeNamespace = new CodeNamespace("CSharpGenerated"); XmlCodeExporter codeExporter = new XmlCodeExporter(codeNamespace, null, CodeGenerationOptions.None); foreach (XmlSchema xsd in xmlSchemas) { foreach (XmlSchemaElement schemaElement in xsd.Elements.Values) { Console.WriteLine($"{schemaElement.Name} is {schemaElement.GetType().Name}"); var t = schemaImporter.ImportTypeMapping(schemaElement.QualifiedName); codeExporter.ExportTypeMapping(t); } foreach (XmlSchemaType schemaType in xsd.SchemaTypes.Values) // XmlSchemaComplexType or XmlSchemaSimpleType { var t = schemaImporter.ImportSchemaType(schemaType.QualifiedName); Console.WriteLine($"{schemaType.Name} is a {schemaType.GetType().Name}"); // Generates far to many xmlroot attributes //codeExporter.ExportTypeMapping(schemaImporter.ImportSchemaType(schemaType.QualifiedName)); } } RemoveAttributes(codeNamespace); CodeGenerator.ValidateIdentifiers(codeNamespace); CSharpCodeProvider codeProvider = new CSharpCodeProvider(); CodeGeneratorOptions opts = new CodeGeneratorOptions { BlankLinesBetweenMembers = false, VerbatimOrder = true }; codeProvider.GenerateCodeFromNamespace(codeNamespace, Console.Out, opts); foreach (CodeTypeDeclaration codeType in codeNamespace.Types) { Console.WriteLine($"{codeType.Name} is a {codeType.GetType().Name}"); var t = codeType.TypeParameters; } Console.ReadLine(); }
static void Main(string[] args) { // identify the path to the xsd const string xsdFileName = @"schema.xsd"; var path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); var xsdPath = Path.Combine(path, xsdFileName); // load the xsd XmlSchema xsd; using (var stream = new FileStream(xsdPath, FileMode.Open, FileAccess.Read)) { xsd = XmlSchema.Read(stream, null); } var xsds = new XmlSchemas(); xsds.Add(xsd); xsds.Compile(null, true); var schemaImporter = new XmlSchemaImporter(xsds); // create the codedom var codeNamespace = new CodeNamespace("Generated"); var codeExporter = new XmlCodeExporter(codeNamespace); var maps = new List <XmlTypeMapping>(); foreach (XmlSchemaType schemaType in xsd.SchemaTypes.Values) { maps.Add(schemaImporter.ImportSchemaType(schemaType.QualifiedName)); } foreach (XmlSchemaElement schemaElement in xsd.Elements.Values) { maps.Add(schemaImporter.ImportTypeMapping(schemaElement.QualifiedName)); } foreach (var map in maps) { codeExporter.ExportTypeMapping(map); } PostProcess(codeNamespace); // Check for invalid characters in identifiers CodeGenerator.ValidateIdentifiers(codeNamespace); // output the C# code var codeProvider = new CSharpCodeProvider(); using (var writer = new StringWriter()) { codeProvider.GenerateCodeFromNamespace(codeNamespace, writer, new CodeGeneratorOptions()); Console.WriteLine(writer.GetStringBuilder().ToString()); } }
private static XmlSchemas LoadSchema(string fileName) { var schemas = new XmlSchemas(); using (var fs = new FileStream(fileName, FileMode.Open)) using (var r = XmlReader.Create(fs)) { var sset = new XmlSchemaSet(); sset.Add(null, r); foreach (var schema in sset.Schemas()) { schemas.Add(schema as XmlSchema); } } return(schemas); }
private ICodeGeneratorContext buildCodeGeneratorContext(Options.CodeGenOptions options) { XmlSchemas xmlSchemas = null; MetadataResolverOptions metadataResolverOptions = CodeGenOptionsParser.GetMetadataResolverOptions(options); // Generate from data contract files if (options.GenerateDataContractsOnly) { xmlSchemas = MetadataFactory.GetXmlSchemaSetFromDataContractFiles(metadataResolverOptions); } else // Generate from wsdl file { xmlSchemas = MetadataFactory.GetXmlSchemaSetFromWsdlFile(metadataResolverOptions); } return(new CodeGeneratorContext(xmlSchemas, options)); }
internal static void AddDocument(string path, object document, XmlSchemas schemas, ServiceDescriptionCollection descriptions, StringCollection warnings) { ServiceDescription serviceDescription = document as ServiceDescription; if (serviceDescription != null) { descriptions.Add(serviceDescription); } else { XmlSchema schema = document as XmlSchema; if (schema != null) { schemas.Add(schema); } } }
private CodeCompileUnit GenerateTypesWithXmlSchemaImporter(XmlSchemaSet schemas) { CodeNamespace ns = new CodeNamespace(this.targetNamespace); CodeCompileUnit unit = new CodeCompileUnit(); unit.Namespaces.Add(ns); schemas.ValidationEventHandler += this.validationEventHandler; try { // Validate schemas schemas.Compile(); XmlSchemas xsds = new XmlSchemas(); foreach (XmlSchema xsd in schemas.Schemas()) { xsds.Add(xsd); } foreach (XmlSchema schema in xsds) { XmlSchemaImporter importer = new XmlSchemaImporter(xsds); XmlCodeExporter exporter = new XmlCodeExporter(ns, unit); // export only elements foreach (XmlSchemaElement schemaElement in schema.Elements.Values) { exporter.ExportTypeMapping(importer.ImportTypeMapping(schemaElement.QualifiedName)); } CodeGenerator.ValidateIdentifiers(ns); } } catch (ArgumentException argumentException) { throw new InvalidOperationException(argumentException.Message, argumentException.InnerException); } finally { schemas.ValidationEventHandler -= this.validationEventHandler; } return(unit); }
/// <summary> /// Executes the code generation workflow. /// </summary> public CodeWriterOutput GenerateCode(CodeGenerationOptions options) { // Step 1 - Parse the code generation options and create the code provider. codeGenerationOptions = CodeGenerationOptionsParser.ParseCodeGenerationOptions(options); CreateCodeProvider(); ExtendedCodeDomTree extendedCodeDomTree; if (options.GenerateDataContracts) { // Step 2 - Build the set of XML schemas. XmlSchemas schemas = MetadataFactory.GetXmlSchemas(codeGenerationOptions.MetadataResolverOptions); // Step 3 - Generate the data contract code and get the CodeNamespace. DataContractGenerator dataContractGenerator = new DataContractGenerator(schemas, codeGenerationOptions.PrimaryOptions, codeProvider); CodeNamespace codeNamespace = dataContractGenerator.GenerateCode(); // Step 4 - Wrap the CodeDOM in the custom object model. extendedCodeDomTree = new ExtendedCodeDomTree(codeNamespace, codeGenerationOptions.WriterOptions.Language, null); } else { // Step 2 - Build the service metadata. MetadataSet metadataSet = MetadataFactory.GetMetadataSet(codeGenerationOptions.MetadataResolverOptions); // Step 3 - Generate the client/service code and get the CodeNamespace. ClientServiceGenerator clientServiceGenerator = new ClientServiceGenerator(metadataSet, codeGenerationOptions.PrimaryOptions, codeProvider); CodeNamespace codeNamespace = clientServiceGenerator.GenerateCode(); // Step 4 - Wrap the CodeDOM in the custom object model. extendedCodeDomTree = new ExtendedCodeDomTree(codeNamespace, codeGenerationOptions.WriterOptions.Language, clientServiceGenerator.Configuration); } // Step 5 - Apply the code decorations. CodeDecorators decorators = new CodeDecorators(); decorators.ApplyDecorations(extendedCodeDomTree, codeGenerationOptions.CustomOptions); // Step 6 - Restore the original CodeDOM. CodeNamespace cns = extendedCodeDomTree.UnwrapCodeDomTree(); // Step 6 - Finally, write out the code to physical files. return(CodeWriter.Write(cns, extendedCodeDomTree.Configuration, codeGenerationOptions.WriterOptions, extendedCodeDomTree.TextFiles, codeProvider)); }
// If the user schema is generated by WCF, it may contain references to some primitive WCF // types in the following namespaces. We need add those schemas to the schema set by default // so these types can be resolved correctly. // // * http://schemas.microsoft.com/2003/10/Serialization // * http://schemas.microsoft.com/2003/10/Serialization/Arrays // * http://microsoft.com/wsdl/types/ // * http://schemas.datacontract.org/2004/07/System private void AddSchemasForPrimitiveTypes(XmlSchemaSet schemas) { // Add DCS special types XsdDataContractExporter dataContractExporter = new XsdDataContractExporter(schemas); // We want to export Guid, Char, and TimeSpan, however even a single call causes all // schemas to be exported. dataContractExporter.Export(typeof(Guid)); // Export DateTimeOffset, DBNull, array types dataContractExporter.Export(typeof(DateTimeOffset)); dataContractExporter.Export(typeof(DBNull)); dataContractExporter.Export(typeof(bool[])); dataContractExporter.Export(typeof(DateTime[])); dataContractExporter.Export(typeof(decimal[])); dataContractExporter.Export(typeof(double[])); dataContractExporter.Export(typeof(float[])); dataContractExporter.Export(typeof(int[])); dataContractExporter.Export(typeof(long[])); dataContractExporter.Export(typeof(XmlQualifiedName[])); dataContractExporter.Export(typeof(short[])); dataContractExporter.Export(typeof(string[])); dataContractExporter.Export(typeof(uint[])); dataContractExporter.Export(typeof(ulong[])); dataContractExporter.Export(typeof(ushort[])); dataContractExporter.Export(typeof(Char[])); dataContractExporter.Export(typeof(TimeSpan[])); dataContractExporter.Export(typeof(Guid[])); // Arrays of DateTimeOffset and DBNull are not supported // Add XS special types // XmlSchemaExporter takes XmlSchemas so we need that temporarily XmlSchemas xmlSchemas = new XmlSchemas(); XmlReflectionImporter importer = new XmlReflectionImporter(); XmlSchemaExporter xmlExporter = new XmlSchemaExporter(xmlSchemas); xmlExporter.ExportTypeMapping(importer.ImportTypeMapping(typeof(Guid))); xmlExporter.ExportTypeMapping(importer.ImportTypeMapping(typeof(Char))); foreach (XmlSchema schema in xmlSchemas) { schemas.Add(schema); } }
public static void SchemaDoc(String[] args) { var docParameters = new ParameterParser <SchemaDocParameters>().Parse(args); XmlSchema outputXsd = new XmlSchema(); XmlSchemas outputSchemas = new XmlSchemas(); var schemaExporter = new XmlSchemaExporter(outputSchemas); var reflectionImporter = new XmlReflectionImporter(); Assembly loadedAssembly = Assembly.LoadFile(docParameters.Assembly); // Load the specified types foreach (var t in loadedAssembly.ExportedTypes.Where(o => o.GetCustomAttribute <XmlRootAttribute>() != null)) { var typeMapping = reflectionImporter.ImportTypeMapping(t); schemaExporter.ExportTypeMapping(typeMapping); } XmlDocument xmlDoc = new XmlDocument(); xmlDoc.Load(docParameters.XmlDocFile ?? Path.ChangeExtension(docParameters.Assembly, "xml")); // Schema set objects foreach (XmlSchema itm in outputSchemas) { foreach (object xtype in itm.Items) { if (xtype is XmlSchemaComplexType) { CreateAssemblyDoc(xtype as XmlSchemaComplexType, loadedAssembly.ExportedTypes.FirstOrDefault(o => o.GetCustomAttribute <XmlTypeAttribute>()?.TypeName == (xtype as XmlSchemaComplexType).Name), xmlDoc); } else if (xtype is XmlSchemaSimpleType) { CreateAssemblyDoc(xtype as XmlSchemaSimpleType, loadedAssembly.ExportedTypes.FirstOrDefault(o => o.GetCustomAttribute <XmlTypeAttribute>()?.TypeName == (xtype as XmlSchemaSimpleType).Name), xmlDoc); } } } // Schema writer using (var xwriter = File.Create(docParameters.Output ?? "out.xsd")) foreach (XmlSchema itm in outputSchemas) { itm.Write(xwriter); } }
void AddIncludingSchema(XmlSchemas list, string ns) { XmlSchema sc = Schemas [ns]; if (sc == null || list.Contains(sc)) { return; } list.Add(sc); foreach (XmlSchemaObject ob in sc.Includes) { XmlSchemaImport import = ob as XmlSchemaImport; if (import != null) { AddIncludingSchema(list, import.Namespace); } } }
/// <summary> /// Processes XML schema specified using file name. /// </summary> /// <param name="fileName">File name of the XML schema.</param> private void ProcessDirectiveCore(string fileName) { fileName = Environment.ExpandEnvironmentVariables(fileName); fileName = ResolvePath(Host.TemplateFile, fileName); XmlSchema schema = this.ReadSchema(fileName); XmlSchemas schemas = new XmlSchemas(); schemas.Add(schema); this.ReadExternalSchemas(schemas); this.CompileSchemas(schemas); CodeCompileUnit codeDom = this.GenerateCodeDom(schemas); this.LanguageProvider.GenerateCodeFromCompileUnit(codeDom, this.ClassCode, null); }
void AddIncludingSchema(XmlSchemas list, string ns) { foreach (XmlSchema sc in Schemas) { if (sc.TargetNamespace == ns && !list.Contains(sc)) { list.Add(sc); foreach (XmlSchemaObject ob in sc.Includes) { XmlSchemaImport import = ob as XmlSchemaImport; if (import != null) { AddIncludingSchema(list, import.Namespace); } } } } }
internal DiscoveryServerType(Type type, string uri) : base(typeof(DiscoveryServerProtocol)) { this.schemaTable = new Hashtable(); this.wsdlTable = new Hashtable(); uri = new Uri(uri, true).GetLeftPart(UriPartial.Path); this.methodInfo = new LogicalMethodInfo(typeof(DiscoveryServerProtocol).GetMethod("Discover", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance)); ServiceDescriptionReflector reflector = new ServiceDescriptionReflector(); reflector.Reflect(type, uri); XmlSchemas schemas = reflector.Schemas; this.description = reflector.ServiceDescription; XmlSerializer serializer = ServiceDescription.Serializer; this.AddSchemaImports(schemas, uri, reflector.ServiceDescriptions); for (int i = 1; i < reflector.ServiceDescriptions.Count; i++) { ServiceDescription description = reflector.ServiceDescriptions[i]; Import import = new Import { Namespace = description.TargetNamespace }; string key = "wsdl" + i.ToString(CultureInfo.InvariantCulture); import.Location = uri + "?wsdl=" + key; reflector.ServiceDescription.Imports.Add(import); this.wsdlTable.Add(key, description); } this.discoDoc = new DiscoveryDocument(); this.discoDoc.References.Add(new ContractReference(uri + "?wsdl", uri)); foreach (Service service in reflector.ServiceDescription.Services) { foreach (Port port in service.Ports) { SoapAddressBinding binding = (SoapAddressBinding)port.Extensions.Find(typeof(SoapAddressBinding)); if (binding != null) { System.Web.Services.Discovery.SoapBinding binding2 = new System.Web.Services.Discovery.SoapBinding { Binding = port.Binding, Address = binding.Location }; this.discoDoc.References.Add(binding2); } } } }
private void AddDocument(string path, object document, XmlSchemas schemas, ServiceDescriptionCollection descriptions) { var serviceDescription = document as ServiceDescription; if (serviceDescription != null) { if (descriptions[serviceDescription.TargetNamespace] == null) { descriptions.Add(serviceDescription); var w = new StringWriter(); var writer = new XmlTextWriter(w); writer.Formatting = Formatting.Indented; serviceDescription.Write(writer); wsdls.Add(w.ToString()); } else { CheckPoint(MessageType.Warning, string.Format(duplicateService, serviceDescription.TargetNamespace, path)); } } else { var schema = document as XmlSchema; if (schema != null) { if (schemas[schema.TargetNamespace] == null) { schemas.Add(schema); var writer3 = new StringWriter(); var writer4 = new XmlTextWriter(writer3); writer4.Formatting = Formatting.Indented; schema.Write(writer4); xsds.Add(writer3.ToString()); } else { CheckPoint(MessageType.Warning, string.Format(duplicateSchema, serviceDescription.TargetNamespace, path)); } } } }
/// <summary> /// Get Schema for a given body /// </summary> /// <param name="body"></param> /// <param name="isXmlSerializerType"></param> /// <returns></returns> private static Message GetXmlSchemaAsMessage(Type body, bool isXmlSerializerType) { System.Collections.IEnumerable schemas; if (isXmlSerializerType) { XmlReflectionImporter importer = new XmlReflectionImporter(); XmlTypeMapping typeMapping = importer.ImportTypeMapping(body); XmlSchemas s = new XmlSchemas(); XmlSchemaExporter exporter = new XmlSchemaExporter(s); exporter.ExportTypeMapping(typeMapping); schemas = s.GetSchemas(null); } else { XsdDataContractExporter exporter = new XsdDataContractExporter(); exporter.Export(body); schemas = exporter.Schemas.Schemas(); } using (MemoryStream stream = new MemoryStream()) { XmlWriterSettings xws = new XmlWriterSettings { Indent = true }; using (XmlWriter writer = XmlWriter.Create(stream, xws)) { if (writer != null) { writer.WriteStartElement("Schemas"); foreach (XmlSchema schema in schemas) { if (schema.TargetNamespace != "http://www.w3.org/2001/XMLSchema") { schema.Write(writer); } } } } stream.Seek(0, SeekOrigin.Begin); using (XmlReader reader = XmlReader.Create(stream)) { return(Message.CreateMessage(MessageVersion.None, null, XElement.Load(reader, LoadOptions.PreserveWhitespace))); } } }
public String GetSourceCode() { string proxynamespace = proxyNamespace; ServiceDescriptionCollection serviceDescriptions = GetServiceDescriptionCollection(protocol); XmlSchemas schemas = GetXmlSchemas(protocol); ServiceDescriptionImporter importer = new ServiceDescriptionImporter(); foreach (ServiceDescription description in serviceDescriptions) { importer.AddServiceDescription(description, null, null); } foreach (XmlSchema schema in schemas) { importer.Schemas.Add(schema); } importer.Style = ServiceDescriptionImportStyle.Client; importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties | CodeGenerationOptions.GenerateNewAsync; CodeNamespace codeNamespace = new CodeNamespace(proxyNamespace); CodeCompileUnit codeUnit = new CodeCompileUnit(); codeUnit.Namespaces.Add(codeNamespace); ServiceDescriptionImportWarnings warnings = importer.Import(codeNamespace, codeUnit); CodeDomProvider provider = project.LanguageProperties.CodeDomProvider; string SourceCode = ""; if (provider != null) { StringWriter sw = new StringWriter(); CodeGeneratorOptions options = new CodeGeneratorOptions(); options.BracingStyle = "C"; provider.GenerateCodeFromCompileUnit(codeUnit, (TextWriter)sw, options); SourceCode = sw.ToString(); sw.Close(); } return(SourceCode); }
private void AddDocument(string path, object document, XmlSchemas schemas, ServiceDescriptionCollection descriptions) { ServiceDescription description1 = document as ServiceDescription; if (description1 != null) { if (descriptions[description1.TargetNamespace] == null) { descriptions.Add(description1); StringWriter writer1 = new StringWriter(); XmlTextWriter writer2 = new XmlTextWriter(writer1); writer2.Formatting = Formatting.Indented; description1.Write(writer2); wsdls.Add(writer1.ToString()); } else { CheckPoint(MessageType.Warning, string.Format(duplicateService, description1.TargetNamespace, path)); } } else { XmlSchema schema1 = document as XmlSchema; if (schema1 != null) { if (schemas[schema1.TargetNamespace] == null) { schemas.Add(schema1); StringWriter writer3 = new StringWriter(); XmlTextWriter writer4 = new XmlTextWriter(writer3); writer4.Formatting = Formatting.Indented; schema1.Write(writer4); xsds.Add(writer3.ToString()); } else { CheckPoint(MessageType.Warning, string.Format(duplicateSchema, description1.TargetNamespace, path)); } } } }
private CodeNamespace GeneratedClassFromStream(Stream stream, string nameSpace) { try { XmlSchema xsd; stream.Seek(0, SeekOrigin.Begin); using (stream) { xsd = XmlSchema.Read(stream, null); } var xsds = new XmlSchemas(); xsds.Add(xsd); xsds.Compile(null, true); var schemaImporter = new XmlSchemaImporter(xsds); // create the codedom var codeNamespace = new CodeNamespace(nameSpace); var codeExporter = new XmlCodeExporter(codeNamespace); var maps = new List <XmlTypeMapping>(); foreach (XmlSchemaType schemaType in xsd.SchemaTypes.Values) { maps.Add(schemaImporter.ImportSchemaType(schemaType.QualifiedName)); } foreach (XmlSchemaElement schemaElement in xsd.Elements.Values) { maps.Add(schemaImporter.ImportTypeMapping(schemaElement.QualifiedName)); } foreach (XmlTypeMapping map in maps) { codeExporter.ExportTypeMapping(map); } return(codeNamespace); } catch (Exception e) { return(null); } }
internal void CheckDuplicateElement(XmlSchemaElement element, string elementNs) { if (element == null) { return; } // only check duplicate definitions for top-level element if (element.Parent == null || !(element.Parent is XmlSchema)) { return; } XmlSchemaObjectTable elements = null; if (Schema != null && Schema.TargetNamespace == elementNs) { #if !XMLSERIALIZERGENERATOR XmlSchemas.Preprocess(Schema); elements = Schema.Elements; #endif } else if (Schemas != null) { elements = Schemas.GlobalElements; } else { return; } foreach (XmlSchemaElement e in elements.Values) { if (e.Name == element.Name && e.QualifiedName.Namespace == elementNs) { if (Match(e, element)) { return; } // XmlSerializableRootDupName=Cannot reconcile schema for '{0}'. Please use [XmlRoot] attribute to change name or namepace of the top-level element to avoid duplicate element declarations: element name='{1} namespace='{2}'. throw new InvalidOperationException(SR.Format(SR.XmlSerializableRootDupName, _getSchemaMethod.DeclaringType.FullName, e.Name, elementNs)); } } }
/// <summary> /// /// Resolve the pointers to included schemas. /// /// When we generate the schemas from types, and more than one schema is generated, /// the "master" schema that contains the schema for the type that is the parameter /// for this method will "include" the other schemas that define the /// types it inherits from or the types that it returns in it's properties. /// If we read this schema off the disk, then the XmlSchemaExternal class's Schema property /// would contain a pointer to the included schema. This is not the case for generated /// schemas. /// /// What we do in this method is recurse through the generated schemas, and look for /// included schemas who's pointers are null. Then we find out what namespoace those /// include schemas are in, and look for that in the generated schemas collection. /// /// If we find it, we "fix" the pointer by setting it to the proper generated schema. /// /// This method modified the schemas in the schema collection /// </summary> /// <param name="xmlSchema">The master schema</param> /// <param name="schemas">the collection of generated schemas</param> private void ResolveImportedSchemas(XmlSchema xmlSchema, XmlSchemas schemas) { string baseSchemaName = GenerateName(); if (string.IsNullOrEmpty(xmlSchema.SourceUri)) { xmlSchema.Id = Path.GetFileNameWithoutExtension(baseSchemaName); xmlSchema.SourceUri = baseSchemaName; } foreach (XmlSchemaObject externalSchemaObj in xmlSchema.Includes) { XmlSchemaExternal externalSchema = externalSchemaObj as XmlSchemaExternal; if (externalSchema == null) { continue; } // if the external schema is not null, we have nothing to worry about if (externalSchema.Schema != null) { continue; } // if the external schema is null, find it in the schema set XmlSchemaImport importSchema = externalSchemaObj as XmlSchemaImport; if (importSchema != null) { if (schemas.Contains(importSchema.Namespace)) { XmlSchema referencedSchema = schemas[importSchema.Namespace]; importSchema.Schema = referencedSchema; string name = GenerateName(); importSchema.Schema.Id = Path.GetFileNameWithoutExtension(name); importSchema.Schema.SourceUri = name; importSchema.SchemaLocation = MakeRelative(xmlSchema.SourceUri, name); } } // resolve any included schemas in the external schema ResolveImportedSchemas(externalSchema.Schema, schemas); } }
// Constructors public SoapSchemaImporter(XmlSchemas schemas) { }
// Constructors public XmlSchemaExporter(XmlSchemas schemas) { }
// Constructors public SoapSchemaExporter(XmlSchemas schemas) { }
public XmlSchemaImporter(XmlSchemas schemas, CodeIdentifiers typeIdentifiers, CodeGenerationOptions options) { }
public XmlSchemaImporter(XmlSchemas schemas, CodeGenerationOptions options, ImportContext context) { }
public XmlSchemaImporter(XmlSchemas schemas, CodeGenerationOptions options, System.CodeDom.Compiler.CodeDomProvider codeProvider, ImportContext context) { }
// Constructors public XmlSchemaImporter(XmlSchemas schemas) { }
public XmlSchemaImporter(XmlSchemas schemas, CodeIdentifiers typeIdentifiers) { }