static void LoadOperationalTemplateSchemas(System.Xml.Schema.XmlSchemaSet xs) { if (!xs.Contains(RmXmlSerializer.OpenEhrNamespace)) { System.Xml.Schema.XmlSchema baseTypesSchema = RmXmlSerializer.GetOpenEhrSchema("BaseTypes"); System.Xml.Schema.XmlSchema resourceSchema = RmXmlSerializer.GetOpenEhrSchema("Resource"); resourceSchema.Includes.Clear(); System.Xml.Schema.XmlSchemaInclude include = new System.Xml.Schema.XmlSchemaInclude(); include.Schema = baseTypesSchema; resourceSchema.Includes.Add(include); System.Xml.Schema.XmlSchema archetypeSchema = RmXmlSerializer.GetOpenEhrSchema("Archetype"); archetypeSchema.Includes.Clear(); include = new System.Xml.Schema.XmlSchemaInclude(); include.Schema = resourceSchema; archetypeSchema.Includes.Add(include); System.Xml.Schema.XmlSchema openEhrProfileSchema = RmXmlSerializer.GetOpenEhrSchema("OpenehrProfile"); openEhrProfileSchema.Includes.Clear(); include = new System.Xml.Schema.XmlSchemaInclude(); include.Schema = archetypeSchema; openEhrProfileSchema.Includes.Add(include); System.Xml.Schema.XmlSchema templateSchema = RmXmlSerializer.GetOpenEhrSchema("Template"); templateSchema.Includes.Clear(); include = new System.Xml.Schema.XmlSchemaInclude(); include.Schema = openEhrProfileSchema; templateSchema.Includes.Add(include); xs.Add(templateSchema); xs.Compile(); } }
public bool IsValid(string xml, System.Xml.Schema.XmlSchema xd, bool reportWarnings = false) { // Create the schema object System.Xml.Schema.XmlSchemaSet sc = new System.Xml.Schema.XmlSchemaSet(); _xml = xml; sc.Add(xd); // Create reader settings System.Xml.XmlReaderSettings settings = new System.Xml.XmlReaderSettings(); // Attach event handler whic will be fired when validation error occurs settings.ValidationEventHandler += XmlReader_ValidationCallBack; // Set validation type to schema settings.ValidationType = System.Xml.ValidationType.Schema; if (reportWarnings) { settings.ValidationFlags |= System.Xml.Schema.XmlSchemaValidationFlags.ReportValidationWarnings; } //settings.ValidationFlags = settings.ValidationFlags Or System.Xml.Schema.XmlSchemaValidationFlags.ProcessInlineSchema //settings.ValidationFlags = settings.ValidationFlags Or System.Xml.Schema.XmlSchemaValidationFlags.ProcessSchemaLocation // Add to the collection of schemas in readerSettings settings.Schemas.Add(sc); //settings.ProhibitDtd = False // Create object of XmlReader using XmlReaderSettings System.IO.StringReader xmlMs = new System.IO.StringReader(xml); System.Xml.XmlReader reader = System.Xml.XmlReader.Create(xmlMs, settings); Exceptions = new List <System.Xml.Schema.XmlSchemaException>(); // Parse the file. while (reader.Read()) { } return(Exceptions.Count == 0); }
/// <summary>Called when extension shall processs generated CodeDOM</summary> /// <param name="code">Object tree representing generated CodeDOM</param> /// <param name="schema">Input XML schema</param> /// <param name="provider">CodeDOM provider (the language)</param> /// <version version="1.5.3">Added documentation</version> /// <version version="1.5.3">Parameter <c>Provider</c> renamed to <c>provider</c></version> public void Process(System.CodeDom.CodeNamespace code, System.Xml.Schema.XmlSchema schema, CodeDomProvider provider) { foreach (CodeTypeDeclaration type in code.Types) { ParseType(type); } }
public void Process(CodeNamespace code, System.Xml.Schema.XmlSchema schema) { foreach (CodeTypeDeclaration type in code.Types) { if (type.IsClass || type.IsStruct) { // Copy the colletion to an array for safety. We will be // changing this collection. CodeTypeMember[] members = new CodeTypeMember[type.Members.Count]; type.Members.CopyTo(members, 0); foreach (CodeTypeMember member in members) { // Process fields only. if (member is CodeMemberField) { CodeMemberProperty prop = new CodeMemberProperty(); prop.Name = member.Name; prop.Attributes = member.Attributes; prop.Type = ((CodeMemberField)member).Type; // Copy attributes from field to the property. prop.CustomAttributes.AddRange(member.CustomAttributes); member.CustomAttributes.Clear(); // Copy comments from field to the property. prop.Comments.AddRange(member.Comments); member.Comments.Clear(); // Modify the field. member.Attributes = MemberAttributes.Private; Char[] letters = member.Name.ToCharArray(); letters[0] = Char.ToLower(letters[0]); member.Name = String.Concat("_", new string(letters)); prop.HasGet = true; prop.HasSet = true; // Add get/set statements pointing to field. Generates: // return this._fieldname; prop.GetStatements.Add( new CodeMethodReturnStatement( new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), member.Name))); // Generates: // this._fieldname = value; prop.SetStatements.Add( new CodeAssignStatement( new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), member.Name), new CodeArgumentReferenceExpression("value"))); // Finally add the property to the type type.Members.Add(prop); } } } } }
/// <summary> /// Walk the schema definition to find the parameters of the given message. /// </summary> /// <param name="serviceDescription"> /// <param name="messagePartName"> /// <returns></returns> private static Parameter[] GetParameters(ServiceDescription serviceDescription, string messagePartName) { List <Parameter> parameters = new List <Parameter>(); Types types = serviceDescription.Types; System.Xml.Schema.XmlSchema xmlSchema = types.Schemas[0]; foreach (object item in xmlSchema.Items) { if (item is System.Xml.Schema.XmlSchemaElement schemaElement && schemaElement.Name == messagePartName) { System.Xml.Schema.XmlSchemaType schemaType = schemaElement.SchemaType; if (schemaType is System.Xml.Schema.XmlSchemaComplexType complexType) { System.Xml.Schema.XmlSchemaParticle particle = complexType.Particle; if (particle is System.Xml.Schema.XmlSchemaSequence sequence) { foreach (System.Xml.Schema.XmlSchemaElement childElement in sequence.Items) { string parameterName = childElement.Name; string parameterType = childElement.SchemaTypeName.Name; parameters.Add(new Parameter(parameterName, parameterType)); } } } } } return(parameters.ToArray()); }
private void LoadSqlPodXml() { //リソースからxsdファイルを読み込む Assembly myAssembly = Assembly.GetExecutingAssembly(); Stream xsdStream = myAssembly.GetManifestResourceStream("SqlAccessor.XmlSchema.sqlPod.xsd"); System.Xml.Schema.XmlSchema sqlPodSchema = System.Xml.Schema.XmlSchema.Read(xsdStream, null); //XMLの妥当性を検証するためのXML Schema System.Xml.Schema.XmlSchemaSet schemaSet = new System.Xml.Schema.XmlSchemaSet(); schemaSet.Add(sqlPodSchema); //XMLの妥当性は検証する XmlReaderSettings readerSettings = new XmlReaderSettings(); readerSettings.ValidationType = ValidationType.Schema; readerSettings.Schemas = schemaSet; //コメント及び空白はスキップする readerSettings.IgnoreComments = true; readerSettings.IgnoreWhitespace = true; XmlReader aXmlReader = XmlReader.Create(_sqlPodXml, readerSettings); XmlSimpleReader xmlSimpleReader = new XmlSimpleReader(aXmlReader); var lookaheadReader = new LookaheadEnumerator <XmlSimpleReader.XmlElement>(xmlSimpleReader); using (lookaheadReader) { this.ParseSqlPodElement(lookaheadReader); } }
private static System.Xml.Schema.XmlSchema GetCapabilitiesSchema() { //Get XML Schema System.IO.Stream stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("SharpMap.Web.Wms.Schemas._1._3._0.capabilities_1_3_0.xsd"); System.Xml.Schema.XmlSchema schema = System.Xml.Schema.XmlSchema.Read(stream, new System.Xml.Schema.ValidationEventHandler(ValidationError)); stream.Close(); return(schema); }
public static string GetDesignSchemaXML() { System.Xml.Schema.XmlSchema schema = ReportDesign.GetDesignSchemaXML(); MemoryStream stream = new MemoryStream(); schema.Write(stream); return(Encoding.UTF8.GetString(stream.GetBuffer())); }
public System.Xml.Schema.XmlSchema GetSchema() { //throw new NotImplementedException(); System.Xml.Schema.XmlSchema xmlSchema = new System.Xml.Schema.XmlSchema() { Id = "FFFF" }; return(xmlSchema); }
private ServiceContractGenerator BuildServiceContractGenerator(XmlTextReader xmlreader) { // make sure xml describes a valid wsdl if (!System.Web.Services.Description.ServiceDescription.CanRead(xmlreader)) { throw new Exception("Invalid Web Service Description"); } // parse wsdl System.Web.Services.Description.ServiceDescription serviceDescription = System.Web.Services.Description.ServiceDescription.Read(xmlreader); MetadataSection section = MetadataSection.CreateFromServiceDescription(serviceDescription); MetadataSet metaDocs = new MetadataSet(new MetadataSection[] { section }); WsdlImporter importer = new WsdlImporter(metaDocs); // Add any imported files foreach (System.Xml.Schema.XmlSchema wsdlSchema in serviceDescription.Types.Schemas) { foreach (System.Xml.Schema.XmlSchemaObject externalSchema in wsdlSchema.Includes) { if (externalSchema is System.Xml.Schema.XmlSchemaImport) { Uri baseUri = webServiceUri; if (string.IsNullOrEmpty(((System.Xml.Schema.XmlSchemaExternal)externalSchema).SchemaLocation)) { continue; } Uri schemaUri = new Uri(baseUri, ((System.Xml.Schema.XmlSchemaExternal)externalSchema).SchemaLocation); Console.WriteLine("== xml schema " + schemaUri); Console.WriteLine("~~~~~~~~~~~~~~~~~~~~~~~~~~~~"); StreamReader sr = GetHttpWebResponse(schemaUri.ToString()); System.Xml.Schema.XmlSchema schema = System.Xml.Schema.XmlSchema.Read(sr, null); importer.XmlSchemas.Add(schema); } } } ServiceContractGenerator generator = new ServiceContractGenerator(); IEnumerable <ContractDescription> contracts = importer.ImportAllContracts(); importer.ImportAllEndpoints(); foreach (ContractDescription contract in contracts) { generator.GenerateServiceContractType(contract); } if (generator.Errors.Count != 0) { throw new Exception("There were errors during code compilation."); } return(generator); }
/// <summary> /// Gerar a estrutura e o grafo da classe /// </summary> private CodeNamespace GerarGrafo() { #region Gerar a estrutura da classe do serviço //Gerar a estrutura da classe do serviço ServiceDescriptionImporter importer = new ServiceDescriptionImporter(); importer.AddServiceDescription(this.serviceDescription, string.Empty, string.Empty); //Definir o nome do protocolo a ser utilizado //Não posso definir, tenho que deixar por conta do WSDL definir, ou pode dar erro em alguns estados //importer.ProtocolName = "Soap12"; //importer.ProtocolName = "Soap"; //Tipos deste serviço devem ser gerados como propriedades e não como simples campos importer.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties; #endregion #region Se a NFSe for padrão DUETO/WEBISS/SALVADOR_BA/PRONIN preciso importar os schemas do WSDL if (Propriedade.TipoAplicativo == TipoAplicativo.Nfse && (PadraoNFSe == PadroesNFSe.DUETO || PadraoNFSe == PadroesNFSe.WEBISS || PadraoNFSe == PadroesNFSe.SALVADOR_BA || PadraoNFSe == PadroesNFSe.GIF || PadraoNFSe == PadroesNFSe.PRONIN)) { //Tive que utilizar a WebClient para que a OpenRead funcionasse, não foi possível fazer funcionar com a SecureWebClient. Tem que analisar melhor. Wandrey e Renan 10/09/2013 WebClient client = new WebClient(); Stream stream = client.OpenRead(ArquivoWSDL); //Esta sim tem que ser com a SecureWebClient pq tem que ter o certificado. Wandrey 10/09/2013 SecureWebClient client2 = new SecureWebClient(oCertificado); // Add any imported files foreach (System.Xml.Schema.XmlSchema wsdlSchema in serviceDescription.Types.Schemas) { foreach (System.Xml.Schema.XmlSchemaObject externalSchema in wsdlSchema.Includes) { if (externalSchema is System.Xml.Schema.XmlSchemaImport) { Uri baseUri = new Uri(ArquivoWSDL); Uri schemaUri = new Uri(baseUri, ((System.Xml.Schema.XmlSchemaExternal)externalSchema).SchemaLocation); stream = client2.OpenRead(schemaUri); System.Xml.Schema.XmlSchema schema = System.Xml.Schema.XmlSchema.Read(stream, null); importer.Schemas.Add(schema); } } } } #endregion #region Gerar o o grafo da classe para depois gerar o código CodeNamespace @namespace = new CodeNamespace(); CodeCompileUnit unit = new CodeCompileUnit(); unit.Namespaces.Add(@namespace); ServiceDescriptionImportWarnings warmings = importer.Import(@namespace, unit); #endregion return(@namespace); }
public static String Get_XSD_String_Clase(Type Tipo_Searializar) { XmlReflectionImporter importer = new XmlReflectionImporter(); XmlSchemas schemas = new XmlSchemas(); XmlSchemaExporter exporter = new XmlSchemaExporter(schemas); XmlTypeMapping mapping = importer.ImportTypeMapping(Tipo_Searializar); exporter.ExportTypeMapping(mapping); System.Xml.Schema.XmlSchema schema = schemas[0]; System.IO.StringWriter sWriter = new System.IO.StringWriter(); schema.Write(sWriter); return(sWriter.ToString()); }
/// <summary> /// Gets the target namespace for the specified part of an XLANG message. /// </summary> /// <param name="msg">The XLANG message.</param> /// <param name="partNumber">The part number.</param> /// <returns>The target namespace.</returns> public static string GetNamespace(XLANGMessage msg, int partNumber) { XLANGPart part = msg[partNumber]; System.Xml.Schema.XmlSchema sch = part.XmlSchema; if (sch == null) { return(String.Empty); } else { return(sch.TargetNamespace); } }
/// <summary> /// This method is reserved and should not be used. When implementing the IXmlSerializable interface, you should return null (Nothing in Visual Basic) from this method, and instead, if specifying a custom schema is required, apply the <see cref="T:System.Xml.Serialization.XmlSchemaProviderAttribute"/> to the class. /// </summary> /// <returns> /// An <see cref="T:System.Xml.Schema.XmlSchema"/> that describes the XML representation of the object that is produced by the <see cref="M:System.Xml.Serialization.IXmlSerializable.WriteXml(System.Xml.XmlWriter)"/> method and consumed by the <see cref="M:System.Xml.Serialization.IXmlSerializable.ReadXml(System.Xml.XmlReader)"/> method. /// </returns> public System.Xml.Schema.XmlSchema GetSchema() { string xsd = @"<?xml version=""1.0"" encoding=""UTF-8""?> <schema targetNamespace=""http://www.opengis.net/ows/1.1"" xmlns:ows=""http://www.opengis.net/ows/1.1"" xmlns:xlink=""http://www.w3.org/1999/xlink"" xmlns=""http://www.w3.org/2001/XMLSchema"" elementFormDefault=""qualified"" version=""1.1.0"" xml:lang=""en""> <complexType name=""ValueType""> <simpleContent> <extension base=""string""></extension> </simpleContent> </complexType> </schema>"; System.Xml.Schema.XmlSchema schema = System.Xml.Schema.XmlSchema.Read(new StringReader(xsd), null); return(schema); }
static void Main(string[] args) { XmlDocument myXMLDoc = new XmlDocument(); myXMLDoc.Load("C:\\Opgaver\\Mobile\\XML\\XMLRequest.XML"); System.Xml.Schema.XmlSchema XS = new System.Xml.Schema.XmlSchema(); XS = "C:\\Development\\CreateXMLFromXSD\\CreateXMLFromXSD\\XMLSchema1.xsd"; myXMLDoc.Schemas.Add(XS); System.Xml.Schema.ValidationEventHandler VE; myXMLDoc.Validate(VE); string st = Console.ReadLine(); pick myPickXML = new pick(); myPickXML.PickHeaders.PickHeaderProperties. }
/// <summary> /// Recupera o esquema da biblioteca. /// </summary> /// <returns></returns> public static System.Xml.Schema.XmlSchema GetSchema() { var path = "Colosoft.Validation.Schemas.Validation.xsd"; System.Xml.Schema.XmlSchema schema = null; var schemaSerializer = new System.Xml.Serialization.XmlSerializer(typeof(System.Xml.Schema.XmlSchema)); using (var stream = typeof(Namespaces).Assembly.GetManifestResourceStream(path)) { if (stream == null) { return(null); } schema = (System.Xml.Schema.XmlSchema)schemaSerializer.Deserialize(new System.Xml.XmlTextReader(stream), null); } return(schema); }
private string CreateProcessXmlFieldSchemaString(string name) { System.Xml.Schema.XmlSchema xmlSchema = new System.Xml.Schema.XmlSchema(); System.Xml.Schema.XmlSchemaComplexType complexType = new System.Xml.Schema.XmlSchemaComplexType(); System.Xml.Schema.XmlSchemaSequence sequence = new System.Xml.Schema.XmlSchemaSequence(); complexType.Particle = sequence; System.Xml.Schema.XmlSchemaElement rootElement = new System.Xml.Schema.XmlSchemaElement(); rootElement.SchemaType = complexType; rootElement.Name = name; xmlSchema.Items.Add(rootElement); System.IO.StringWriter stream = new System.IO.StringWriter(); xmlSchema.Write(stream); string outString = stream.ToString(); stream.Close(); stream.Dispose(); return(outString); }
public void StartParsing(XmlReader reader, string targetNamespace) { string str; this.reader = reader; this.positionInfo = PositionInfo.GetPositionInfo(reader); this.namespaceManager = reader.NamespaceManager; if (this.namespaceManager == null) { this.namespaceManager = new XmlNamespaceManager(this.nameTable); this.isProcessNamespaces = true; } else { this.isProcessNamespaces = false; } while ((reader.NodeType != XmlNodeType.Element) && reader.Read()) { } this.markupDepth = 0x7fffffff; this.schemaXmlDepth = reader.Depth; SchemaType rootType = this.schemaNames.SchemaTypeFromRoot(reader.LocalName, reader.NamespaceURI); if (!this.CheckSchemaRoot(rootType, out str)) { throw new XmlSchemaException(str, reader.BaseURI, this.positionInfo.LineNumber, this.positionInfo.LinePosition); } if (this.schemaType == SchemaType.XSD) { this.schema = new System.Xml.Schema.XmlSchema(); this.schema.BaseUri = new Uri(reader.BaseURI, UriKind.RelativeOrAbsolute); this.builder = new XsdBuilder(reader, this.namespaceManager, this.schema, this.nameTable, this.schemaNames, this.eventHandler); } else { this.xdrSchema = new SchemaInfo(); this.xdrSchema.SchemaType = SchemaType.XDR; this.builder = new XdrBuilder(reader, this.namespaceManager, this.xdrSchema, targetNamespace, this.nameTable, this.schemaNames, this.eventHandler); ((XdrBuilder)this.builder).XmlResolver = this.xmlResolver; } }
/// <summary> /// Recupera o esquema da biblioteca. /// </summary> /// <param name="name"></param> /// <returns></returns> public static System.Xml.Schema.XmlSchema GetSchema(string name) { var path = string.Format("Colosoft.Query.Schemas.{0}.xsd", name); System.Xml.Schema.XmlSchema schema = null; if (_schemas.TryGetValue(path, out schema)) { return(schema); } var schemaSerializer = new System.Xml.Serialization.XmlSerializer(typeof(System.Xml.Schema.XmlSchema)); using (var stream = typeof(SchemasHelper).Assembly.GetManifestResourceStream(path)) { if (stream == null) { return(null); } schema = (System.Xml.Schema.XmlSchema)schemaSerializer.Deserialize(new System.Xml.XmlTextReader(stream), null); _schemas.Add(path, schema); } return(schema); }
public System.Xml.Schema.XmlSchema ExportXsd <T>(params Type[] knownTypes) { Type tp = typeof(T); XsdDataContractExporter exporter = new XsdDataContractExporter(); // Use the ExportOptions to add the Possessions type to the // collection of KnownTypes. if (knownTypes != null) { ExportOptions eOptions = new ExportOptions(); foreach (Type kt in knownTypes) { eOptions.KnownTypes.Add(kt); } exporter.Options = eOptions; } System.IO.MemoryStream ms = new System.IO.MemoryStream(); if (exporter.CanExport(tp)) { exporter.Export(tp); //Console.WriteLine("number of schemas: {0}", exporter.Schemas.Count) //Console.WriteLine() var mySchemas = exporter.Schemas; var XmlNameValue = exporter.GetRootElementName(tp); string EmployeeNameSpace = XmlNameValue.Namespace; System.Xml.Schema.XmlSchema schema = null; foreach (System.Xml.Schema.XmlSchema schema_loopVariable in mySchemas.Schemas(EmployeeNameSpace)) { schema = schema_loopVariable; schema.Write(ms); } } System.Xml.Schema.XmlSchema xd = new System.Xml.Schema.XmlSchema(); ms.Position = 0; xd = System.Xml.Schema.XmlSchema.Read(ms, new System.Xml.Schema.ValidationEventHandler(XmlSchema_ValidationCallBack)); return(xd); }
public static void LoadArchetypeSchema(System.Xml.Schema.XmlSchemaSet xs) { if (!xs.Contains(OpenEhrNamespace)) { archetypeSchema = GetOpenEhrSchema("Archetype"); System.Xml.Schema.XmlSchema resourceSchema = GetOpenEhrSchema("Resource"); System.Xml.Schema.XmlSchemaInclude schemaInclude; archetypeSchema.Includes.RemoveAt(0); foreach (System.Xml.Schema.XmlSchemaObject item in resourceSchema.Items) archetypeSchema.Items.Add(item); System.Xml.Schema.XmlSchema baseTypesSchema = GetOpenEhrSchema("BaseTypes"); foreach (System.Xml.Schema.XmlSchemaObject item in baseTypesSchema.Items) archetypeSchema.Items.Add(item); xs.Add(archetypeSchema); xs.Compile(); } }
public Assembly CompileWebService(string url, string ns, string protocolName) { this.lastErrorText = new StringBuilder(); if (url == null) { this.lastErrorText.Append("未指定服务地址!"); return(null); } WebClient http = new WebClient(); Stream stream = http.OpenRead(url + "?WSDL"); ServiceDescription serviceDesc = ServiceDescription.Read(stream); ServiceDescriptionImporter sdImporter = new ServiceDescriptionImporter(); sdImporter.ProtocolName = protocolName; sdImporter.AddServiceDescription(serviceDesc, "", ""); foreach (Import schemaImport in serviceDesc.Imports) { Uri baseUri = new Uri(url + "?WSDL"); string schemaLocation = schemaImport.Location; if (schemaLocation == null) { continue; } Uri schemaUri = new Uri(baseUri, schemaLocation); using (Stream schemaStream = http.OpenRead(schemaUri)) { try { ServiceDescription sdImport = ServiceDescription.Read(schemaStream, true); sdImport.Namespaces.Add("wsdl", schemaImport.Namespace); sdImporter.AddServiceDescription(sdImport, null, null); } catch { } } } foreach (System.Xml.Schema.XmlSchema wsdlSchema in serviceDesc.Types.Schemas) { foreach (System.Xml.Schema.XmlSchemaObject externalSchema in wsdlSchema.Includes) { if (externalSchema is System.Xml.Schema.XmlSchemaImport) { Uri baseUri = new Uri(url + "?WSDL"); string exSchemaLocation = ((System.Xml.Schema.XmlSchemaExternal)externalSchema).SchemaLocation; if (string.IsNullOrEmpty(exSchemaLocation)) { continue; } Uri schemaUri = new Uri(baseUri, exSchemaLocation); using (Stream schemaStream = http.OpenRead(schemaUri)) { try { System.Xml.Schema.XmlSchema schema = System.Xml.Schema.XmlSchema.Read(schemaStream, null); sdImporter.Schemas.Add(schema); } catch { } } } } } System.CodeDom.CodeNamespace codeNamespace = new System.CodeDom.CodeNamespace(ns); System.CodeDom.CodeCompileUnit codeCompileUnit = new System.CodeDom.CodeCompileUnit(); codeCompileUnit.Namespaces.Add(codeNamespace); sdImporter.Import(codeNamespace, codeCompileUnit); this.parameters.ReferencedAssemblies.Add("System.XML.dll"); this.parameters.ReferencedAssemblies.Add("System.Web.Services.dll"); this.parameters.ReferencedAssemblies.Add("System.Data.dll"); CompilerResults compilerResults = this.provider.CompileAssemblyFromDom(this.parameters, codeCompileUnit); if (true == compilerResults.Errors.HasErrors) { foreach (CompilerError compilerError in compilerResults.Errors) { this.lastErrorText.Append(string.Format("ErrorNumber:{0} Line:{1} {2}", compilerError.ErrorNumber, compilerError.Line, compilerError.ErrorText)); this.lastErrorText.Append("\r\n"); } return(null); } return(compilerResults.CompiledAssembly); }
static void Main() { try { log.Info("Generation of NHibernate.Mapping.Attributes"); // Open the Schema (in /NHMA/ directory) System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader("../../../../NHibernate.Mapping.Attributes/nhibernate-mapping.xsd"); schema = System.Xml.Schema.XmlSchema.Read(reader, null); Refly.CodeDom.NamespaceDeclaration nd = new Refly.CodeDom.NamespaceDeclaration("NHibernate.Mapping.Attributes", conformer); nd.Imports.Clear(); // remove "using System;" conformer.Capitalize = true; Refly.CodeDom.ClassDeclaration hbmWriter = nd.AddClass("HbmWriter"); hbmWriter.Attributes = System.Reflection.TypeAttributes.Public; hbmWriter.Doc.Summary.AddText(" Write a XmlSchemaElement from attributes in a System.Type. "); // Create the <summary /> Refly.CodeDom.FieldDeclaration fdDefaultHelper = hbmWriter.AddField("HbmWriterHelper", "DefaultHelper"); fdDefaultHelper.InitExpression = new Refly.CodeDom.Expressions.SnippetExpression("new HbmWriterHelperEx()"); // Add its public property with a comment Refly.CodeDom.PropertyDeclaration pdDefaultHelper = hbmWriter.AddProperty(fdDefaultHelper, true, true, false); pdDefaultHelper.Doc.Summary.AddText(" Gets or sets the HbmWriterHelper used by HbmWriter "); // Create the <summary /> Refly.CodeDom.FieldDeclaration fdStartQuote = hbmWriter.AddField(typeof(string), "StartQuote"); // Add its public property with a comment Refly.CodeDom.PropertyDeclaration pdStartQuote = hbmWriter.AddProperty(fdStartQuote, false, true, false); pdStartQuote.Get.Add(new Refly.CodeDom.Expressions.SnippetExpression(@"if(_startQuote==null || _startQuote.Length==0) _startQuote = ""{{""; return _startQuote" )); pdStartQuote.Doc.Summary.AddText(" Gets or sets the beginning string used when declaring an identifier for an AttributeIdenfierAttribute "); // Create the <summary /> Refly.CodeDom.FieldDeclaration fdEndQuote = hbmWriter.AddField(typeof(string), "EndQuote"); // Add its public property with a comment Refly.CodeDom.PropertyDeclaration pdEndQuote = hbmWriter.AddProperty(fdEndQuote, false, true, false); pdEndQuote.Get.Add(new Refly.CodeDom.Expressions.SnippetExpression(@"if(_endQuote==null || _endQuote.Length==0) _endQuote = ""}}""; return _endQuote" )); pdEndQuote.Doc.Summary.AddText(" Gets or sets the ending string used when declaring an identifier for an AttributeIdenfierAttribute "); // Create the <summary /> Refly.CodeDom.FieldDeclaration fdPatterns = hbmWriter.AddField(typeof(System.Collections.Hashtable), "Patterns"); // Add its public property with a comment Refly.CodeDom.PropertyDeclaration pdPatterns = hbmWriter.AddProperty(fdPatterns, false, true, false); pdPatterns.Get.Add(new Refly.CodeDom.Expressions.SnippetExpression(@"if(_patterns==null) { _patterns = new System.Collections.Hashtable(); _patterns.Add(@""Nullables.Nullable(\w+), Nullables"", ""Nullables.NHibernate.Nullable$1Type, Nullables.NHibernate""); _patterns.Add(@""System.Data.SqlTypes.Sql(\w+), System.Data"", ""NHibernate.UserTypes.SqlTypes.Sql$1Type, NHibernate.UserTypes.SqlTypes""); } return _patterns" )); pdPatterns.Doc.Summary.AddText(" Gets or sets the Patterns to convert properties types (the key is the pattern string and the value is the replacement string) "); // Create the <summary /> HbmWriterGenerator.FillFindAttributedMembers(hbmWriter.AddMethod("FindAttributedMembers")); HbmWriterGenerator.FillGetSortedAttributes(hbmWriter.AddMethod("GetSortedAttributes")); HbmWriterGenerator.FillIsNextElement(hbmWriter.AddMethod("IsNextElement"), schema.Items); HbmWriterGenerator.FillGetXmlEnumValue(hbmWriter.AddMethod("GetXmlEnumValue")); HbmWriterGenerator.FillGetAttributeValue(hbmWriter.AddMethod("GetAttributeValue")); HbmWriterGenerator.FillWriteUserDefinedContent(hbmWriter.AddMethod("WriteUserDefinedContent"), hbmWriter.AddMethod("WriteUserDefinedContent")); log.Info("Browse Schema.Items (Count=" + schema.Items.Count + ")"); foreach (System.Xml.Schema.XmlSchemaObject obj in schema.Items) { if (obj is System.Xml.Schema.XmlSchemaAttributeGroup) { // Ignore (used by Elements: <xs:attributeGroup ref="..." />) log.Debug("Ignore AttributeGroup: " + (obj as System.Xml.Schema.XmlSchemaAttributeGroup).Name + string.Format(", nh-mapping.xsd({0})", obj.LineNumber)); } else if (obj is System.Xml.Schema.XmlSchemaGroup) { // Ignore (used by Elements: <xs:group ref="..." />) log.Debug("Ignore Group: " + (obj as System.Xml.Schema.XmlSchemaGroup).Name + string.Format(", nh-mapping.xsd({0})", obj.LineNumber)); } else if (obj is System.Xml.Schema.XmlSchemaSimpleType) { System.Xml.Schema.XmlSchemaSimpleType elt = obj as System.Xml.Schema.XmlSchemaSimpleType; log.Debug("Generate Enumeration for SimpleType: " + elt.Name + string.Format(", nh-mapping.xsd({0})", elt.LineNumber)); AttributeAndEnumGenerator.GenerateEnumeration(elt, nd.AddEnum(Utils.Capitalize(elt.Name), false)); } else if (obj is System.Xml.Schema.XmlSchemaElement) { System.Xml.Schema.XmlSchemaElement elt = obj as System.Xml.Schema.XmlSchemaElement; System.Xml.Schema.XmlSchemaComplexType type = null; if (!elt.SchemaTypeName.IsEmpty) // eg: <xs:element name="cache" type="cacheType" /> { foreach (System.Xml.Schema.XmlSchemaObject o in schema.Items) { System.Xml.Schema.XmlSchemaComplexType t = o as System.Xml.Schema.XmlSchemaComplexType; if (t != null && t.Name == elt.SchemaTypeName.Name) { type = t; break; } } } string eltName = Utils.Capitalize(elt.Name); log.Debug("Generate Attrib and EltWriter for Elt: " + elt.Name + string.Format(", nh-mapping.xsd({0})", elt.LineNumber)); AttributeAndEnumGenerator.GenerateAttribute(elt, nd.AddClass(eltName + "Attribute"), type); HbmWriterGenerator.GenerateElementWriter(elt, eltName, hbmWriter.AddMethod("Write" + eltName), type, schema.Items); if (Utils.IsRoot(eltName)) { HbmWriterGenerator.FillWriteNestedTypes(eltName, hbmWriter.AddMethod("WriteNested" + eltName + "Types")); } } else if (obj is System.Xml.Schema.XmlSchemaComplexType) { // Ignore (Note: Make sure that it is used by Elements only like this: <xs:element name="XXX" type="YYY" />) System.Xml.Schema.XmlSchemaComplexType elt = obj as System.Xml.Schema.XmlSchemaComplexType; log.Debug("Don't generate ComplexType: " + elt.Name + string.Format(", nh-mapping.xsd({0})", elt.LineNumber)); // like <query> and <sql-query> } else { log.Warn("Unknown Object: " + obj.ToString() + string.Format(", nh-mapping.xsd({0})", obj.LineNumber)); } } // Generate the source code // Note: NameConformer.WordSplit() has been replaced in Refly. Refly.CodeDom.CodeGenerator gen = new Refly.CodeDom.CodeGenerator(); gen.Options.IndentString = " "; // Tab gen.CreateFolders = false; #region Copyright gen.Copyright = string.Format(@" NHibernate.Mapping.Attributes This product is under the terms of the GNU Lesser General Public License. ------------------------------------------------------------------------------ <autogenerated> This code was generated by a tool. Runtime Version: {0}.{1}.{2}.x Changes to this file may cause incorrect behavior and will be lost if the code is regenerated. </autogenerated> ------------------------------------------------------------------------------ This source code was auto-generated by Refly, Version={3} (modified). ", System.Environment.Version.Major, System.Environment.Version.Minor, System.Environment.Version.Build, gen.GetType().Assembly.GetName(false).Version); #endregion log.Info("CodeGenerator.GenerateCode()... Classes=" + nd.Classes.Count + ", Enums=" + nd.Enums.Count); gen.GenerateCode(@"../../../../NHibernate.Mapping.Attributes", nd); log.Info("Done !"); } catch (System.Exception ex) { log.Error("Unexpected Exception", ex); } }
/// <summary> /// Create data contract attribute /// </summary> /// <param name="type">Code type declaration</param> /// <param name="schema">XML schema</param> protected override void CreateDataContractAttribute(System.CodeDom.CodeTypeDeclaration type, System.Xml.Schema.XmlSchema schema) { // No data contracts in the Net.20 }
public static System.ServiceModel.Description.MetadataSection CreateFromSchema(System.Xml.Schema.XmlSchema schema) { Contract.Requires(schema != null); Contract.Ensures(Contract.Result <System.ServiceModel.Description.MetadataSection>() != null); return(default(System.ServiceModel.Description.MetadataSection)); }
static void Main() { try { log.Info("Generation of NHibernate.Mapping.Attributes"); // Open the Schema (in /NHMA/ directory) System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader("../../../nhibernate-mapping.xsd"); schema = System.Xml.Schema.XmlSchema.Read(reader, null); Refly.CodeDom.NamespaceDeclaration nd = new Refly.CodeDom.NamespaceDeclaration("NHibernate.Mapping.Attributes", conformer); nd.Imports.Clear(); // remove "using System;" conformer.Capitalize = true; Refly.CodeDom.ClassDeclaration hbmWriter = nd.AddClass("HbmWriter"); hbmWriter.Attributes = System.Reflection.TypeAttributes.Public; hbmWriter.Doc.Summary.AddText(" Write a XmlSchemaElement from attributes in a System.Type. "); // Create the <summary /> Refly.CodeDom.FieldDeclaration fdDefaultHelper = hbmWriter.AddField("HbmWriterHelper", "DefaultHelper"); fdDefaultHelper.InitExpression = new Refly.CodeDom.Expressions.SnippetExpression("new HbmWriterHelperEx()"); // Add its public property with a comment Refly.CodeDom.PropertyDeclaration pdDefaultHelper = hbmWriter.AddProperty(fdDefaultHelper, true, true, false); pdDefaultHelper.Doc.Summary.AddText(" Gets or sets the HbmWriterHelper used by HbmWriter "); // Create the <summary /> Refly.CodeDom.FieldDeclaration fdStartQuote = hbmWriter.AddField(typeof(string), "StartQuote"); // Add its public property with a comment Refly.CodeDom.PropertyDeclaration pdStartQuote = hbmWriter.AddProperty(fdStartQuote, false, true, false); pdStartQuote.Get.Add( new Refly.CodeDom.Expressions.SnippetExpression(@"if(_startQuote==null || _startQuote.Length==0) _startQuote = ""{{""; return _startQuote") ); pdStartQuote.Doc.Summary.AddText(" Gets or sets the beginning string used when declaring an identifier for an AttributeIdenfierAttribute "); // Create the <summary /> Refly.CodeDom.FieldDeclaration fdEndQuote = hbmWriter.AddField(typeof(string), "EndQuote"); // Add its public property with a comment Refly.CodeDom.PropertyDeclaration pdEndQuote = hbmWriter.AddProperty(fdEndQuote, false, true, false); pdEndQuote.Get.Add( new Refly.CodeDom.Expressions.SnippetExpression(@"if(_endQuote==null || _endQuote.Length==0) _endQuote = ""}}""; return _endQuote") ); pdEndQuote.Doc.Summary.AddText(" Gets or sets the ending string used when declaring an identifier for an AttributeIdenfierAttribute "); // Create the <summary /> Refly.CodeDom.FieldDeclaration fdPatterns = hbmWriter.AddField(typeof(System.Collections.Hashtable), "Patterns"); // Add its public property with a comment Refly.CodeDom.PropertyDeclaration pdPatterns = hbmWriter.AddProperty(fdPatterns, false, true, false); pdPatterns.Get.Add( new Refly.CodeDom.Expressions.SnippetExpression(@"if(_patterns==null) { _patterns = new System.Collections.Hashtable(); _patterns.Add(@""Nullables.Nullable(\w+), Nullables"", ""Nullables.NHibernate.Nullable$1Type, Nullables.NHibernate""); _patterns.Add(@""System.Data.SqlTypes.Sql(\w+), System.Data"", ""NHibernate.UserTypes.SqlTypes.Sql$1Type, NHibernate.UserTypes.SqlTypes""); } return _patterns") ); pdPatterns.Doc.Summary.AddText(" Gets or sets the Patterns to convert properties types (the key is the pattern string and the value is the replacement string) "); // Create the <summary /> HbmWriterGenerator.FillFindAttributedMembers(hbmWriter.AddMethod("FindAttributedMembers")); HbmWriterGenerator.FillGetSortedAttributes(hbmWriter.AddMethod("GetSortedAttributes")); HbmWriterGenerator.FillIsNextElement(hbmWriter.AddMethod("IsNextElement"), schema.Items); HbmWriterGenerator.FillGetXmlEnumValue(hbmWriter.AddMethod("GetXmlEnumValue")); HbmWriterGenerator.FillGetAttributeValue(hbmWriter.AddMethod("GetAttributeValue")); HbmWriterGenerator.FillWriteUserDefinedContent( hbmWriter.AddMethod("WriteUserDefinedContent"), hbmWriter.AddMethod("WriteUserDefinedContent") ); log.Info("Browse Schema.Items (Count=" + schema.Items.Count + ")"); foreach(System.Xml.Schema.XmlSchemaObject obj in schema.Items) { if(obj is System.Xml.Schema.XmlSchemaAttributeGroup) { // Ignore (used by Elements: <xs:attributeGroup ref="..." />) log.Debug("Ignore AttributeGroup: " + (obj as System.Xml.Schema.XmlSchemaAttributeGroup).Name + string.Format(", nh-mapping.xsd({0})", obj.LineNumber)); } else if(obj is System.Xml.Schema.XmlSchemaGroup) { // Ignore (used by Elements: <xs:group ref="..." />) log.Debug("Ignore Group: " + (obj as System.Xml.Schema.XmlSchemaGroup).Name + string.Format(", nh-mapping.xsd({0})", obj.LineNumber)); } else if(obj is System.Xml.Schema.XmlSchemaSimpleType) { System.Xml.Schema.XmlSchemaSimpleType elt = obj as System.Xml.Schema.XmlSchemaSimpleType; log.Debug("Generate Enumeration for SimpleType: " + elt.Name + string.Format(", nh-mapping.xsd({0})", elt.LineNumber)); AttributeAndEnumGenerator.GenerateEnumeration(elt, nd.AddEnum(Utils.Capitalize(elt.Name), false)); } else if(obj is System.Xml.Schema.XmlSchemaElement) { System.Xml.Schema.XmlSchemaElement elt = obj as System.Xml.Schema.XmlSchemaElement; System.Xml.Schema.XmlSchemaComplexType type = null; if(!elt.SchemaTypeName.IsEmpty) // eg: <xs:element name="cache" type="cacheType" /> foreach(System.Xml.Schema.XmlSchemaObject o in schema.Items) { System.Xml.Schema.XmlSchemaComplexType t = o as System.Xml.Schema.XmlSchemaComplexType; if(t != null && t.Name == elt.SchemaTypeName.Name) { type = t; break; } } string eltName = Utils.Capitalize(elt.Name); log.Debug("Generate Attrib and EltWriter for Elt: " + elt.Name + string.Format(", nh-mapping.xsd({0})", elt.LineNumber)); AttributeAndEnumGenerator.GenerateAttribute(elt, nd.AddClass(eltName + "Attribute"), type); HbmWriterGenerator.GenerateElementWriter(elt, eltName, hbmWriter.AddMethod("Write" + eltName), type, schema.Items); if(Utils.IsRoot(eltName)) HbmWriterGenerator.FillWriteNestedTypes(eltName, hbmWriter.AddMethod("WriteNested" + eltName + "Types")); } else if(obj is System.Xml.Schema.XmlSchemaComplexType) { // Ignore (Note: Make sure that it is used by Elements only like this: <xs:element name="XXX" type="YYY" />) System.Xml.Schema.XmlSchemaComplexType elt = obj as System.Xml.Schema.XmlSchemaComplexType; log.Debug("Don't generate ComplexType: " + elt.Name + string.Format(", nh-mapping.xsd({0})", elt.LineNumber)); // like <query> and <sql-query> } else log.Warn("Unknown Object: " + obj.ToString() + string.Format(", nh-mapping.xsd({0})", obj.LineNumber)); } // Generate the source code // Note: NameConformer.WordSplit() has been replaced in Refly. Refly.CodeDom.CodeGenerator gen = new Refly.CodeDom.CodeGenerator(); gen.Options.IndentString = " "; // Tab gen.CreateFolders = false; #region Copyright gen.Copyright = string.Format(@" NHibernate.Mapping.Attributes This product is under the terms of the GNU Lesser General Public License. ------------------------------------------------------------------------------ <autogenerated> This code was generated by a tool. Runtime Version: {0}.{1}.{2}.x Changes to this file may cause incorrect behavior and will be lost if the code is regenerated. </autogenerated> ------------------------------------------------------------------------------ This source code was auto-generated by Refly, Version={3} (modified). ", System.Environment.Version.Major, System.Environment.Version.Minor, System.Environment.Version.Build, gen.GetType().Assembly.GetName(false).Version); #endregion log.Info("CodeGenerator.GenerateCode()... Classes=" + nd.Classes.Count + ", Enums=" + nd.Enums.Count); gen.GenerateCode("..\\..\\..", nd); log.Info("Done !"); } catch(System.Exception ex) { log.Error("Unexpected Exception", ex); } catch { log.Error("Unexpected non-CLSCompliant Exception"); } }
public void StartParsing(XmlReader reader, string targetNamespace) { string str; this.reader = reader; this.positionInfo = PositionInfo.GetPositionInfo(reader); this.namespaceManager = reader.NamespaceManager; if (this.namespaceManager == null) { this.namespaceManager = new XmlNamespaceManager(this.nameTable); this.isProcessNamespaces = true; } else { this.isProcessNamespaces = false; } while ((reader.NodeType != XmlNodeType.Element) && reader.Read()) { } this.markupDepth = 0x7fffffff; this.schemaXmlDepth = reader.Depth; SchemaType rootType = this.schemaNames.SchemaTypeFromRoot(reader.LocalName, reader.NamespaceURI); if (!this.CheckSchemaRoot(rootType, out str)) { throw new XmlSchemaException(str, reader.BaseURI, this.positionInfo.LineNumber, this.positionInfo.LinePosition); } if (this.schemaType == SchemaType.XSD) { this.schema = new System.Xml.Schema.XmlSchema(); this.schema.BaseUri = new Uri(reader.BaseURI, UriKind.RelativeOrAbsolute); this.builder = new XsdBuilder(reader, this.namespaceManager, this.schema, this.nameTable, this.schemaNames, this.eventHandler); } else { this.xdrSchema = new SchemaInfo(); this.xdrSchema.SchemaType = SchemaType.XDR; this.builder = new XdrBuilder(reader, this.namespaceManager, this.xdrSchema, targetNamespace, this.nameTable, this.schemaNames, this.eventHandler); ((XdrBuilder) this.builder).XmlResolver = this.xmlResolver; } }