/// <summary> /// 保存配置到配置文件 /// </summary> /// <param name="fileName">配置文件名</param> public virtual void SaveConfig(String fileName) { System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(fileName, Encoding.UTF8); try { writer.Formatting = System.Xml.Formatting.Indented; writer.WriteStartDocument(); writer.WriteStartElement("Jeelu.WordSegmentor"); foreach (CfgItem item in GetCfgItems()) { writer.WriteComment(item.Comment); writer.WriteStartElement("Item"); writer.WriteAttributeString("Name", item.Pi.Name); writer.WriteAttributeString("Value", item.Pi.GetValue(this, null).ToString()); writer.WriteEndElement(); //Item } writer.WriteEndElement(); //Jeelu.WordSegmentor writer.WriteEndDocument(); writer.Flush(); writer.Close(); } catch (Exception e) { WriteLog(String.Format("Save config fail, errmsg:{0}", e.Message)); } }
/// <summary> /// Put the contents of the error and warning information to the /// passed in xml text writer. /// </summary> /// <param name="xmlOutput"></param> public void FlushTo(System.Xml.XmlTextWriter xmlOutput) { xmlOutput.Flush(); int ttlWarnings = m_Warnings.Count + m_sfmsWithOutData; // warnings and sfm's w/o data int ttlErrors = m_FatalErrors.Count + m_Errors.Count; // fatal and reg errors if (ttlErrors + ttlWarnings == 0) { xmlOutput.WriteComment(" There were No errors or warnings during the creation of this file"); } // put out the root error element xmlOutput.WriteComment(" This element contains error, warning and sfm data related information "); xmlOutput.WriteStartElement("ErrorLog"); OutputErrorElement(xmlOutput); // errors OutputWarningElement(xmlOutput); // warnings OutputOOOInfo(xmlOutput); // out of order cautions OutputDuplicateSfmWarnErrElement(xmlOutput); // duplicate SFM errors and warnings OutputSfmInfo(xmlOutput); // general statistics on sfm usage xmlOutput.WriteEndElement(); // end the "ErrorLog" element // remove all the errors and warnings m_Errors.Clear(); m_Warnings.Clear(); m_sfmWarningsAndErrors.Clear(); m_FatalErrors.Clear(); m_uniqueMsgs.Clear(); m_sfmsWithOutData = 0; m_sfmsWithData = 0; m_sfmData.Clear(); m_OOO.Clear(); m_OOOCnt = 0; m_OOOEntries.Clear(); m_OOOEntriesKEYS.Clear(); m_OOOEntriesOrdered.Clear(); }
private void GenerateEventSchemas(UPnPDevice d, System.IO.DirectoryInfo dirInfo, bool cleanSchema) { System.IO.MemoryStream ms = new MemoryStream(); System.Xml.XmlTextWriter X = new System.Xml.XmlTextWriter(ms,System.Text.Encoding.UTF8); X.Formatting = System.Xml.Formatting.Indented; foreach(UPnPDevice ed in d.EmbeddedDevices) { GenerateEventSchemas(ed,dirInfo,cleanSchema); } foreach(UPnPService s in d.Services) { Hashtable h = new Hashtable(); int j=1; foreach(string sn in s.GetSchemaNamespaces()) { h[sn] = "CT"+j.ToString(); ++j; } X.WriteStartDocument(); X.WriteStartElement("xsd","schema","http://www.w3.org/2001/XMLSchema"); X.WriteAttributeString("targetNamespace","urn:schemas-upnp-org:event-1-0"); X.WriteAttributeString("xmlns","upnp",null,"http://www.upnp.org/Schema/DataTypes"); X.WriteAttributeString("xmlns","urn:schemas-upnp-org:event-1-0"); foreach(UPnPStateVariable v in s.GetStateVariables()) { if (v.SendEvent) { X.WriteStartElement("xsd","element",null); // Element1 X.WriteAttributeString("name","propertyset"); X.WriteAttributeString("type","propertysetType"); if (!cleanSchema) { X.WriteComment("Note: Some schema validation tools may consider the following xsd:any element to be ambiguous in its placement"); X.WriteStartElement("xsd","any",null); X.WriteAttributeString("namespace","##other"); X.WriteAttributeString("minOccurs","0"); X.WriteAttributeString("maxOccurs","unbounded"); X.WriteAttributeString("processContents","lax"); X.WriteEndElement(); //ANY } X.WriteStartElement("xsd","complexType",null); X.WriteAttributeString("name","propertysetType"); X.WriteStartElement("xsd","sequence",null); X.WriteStartElement("xsd","element",null); // Element2 X.WriteAttributeString("name","property"); X.WriteAttributeString("maxOccurs","unbounded"); X.WriteStartElement("xsd","complexType",null); X.WriteStartElement("xsd","sequence",null); X.WriteStartElement("xsd","element",null); // Element3 X.WriteAttributeString("name",v.Name); if (v.ComplexType==null) { // Simple Type X.WriteStartElement("xsd","complexType",null); X.WriteStartElement("xsd","simpleContent",null); X.WriteStartElement("xsd","extension",null); X.WriteAttributeString("base","upnp:"+v.ValueType); if (!cleanSchema) { X.WriteStartElement("xsd","anyAttribute",null); X.WriteAttributeString("namespace","##other"); X.WriteAttributeString("processContents","lax"); X.WriteEndElement(); // anyAttribute } X.WriteEndElement(); // extension X.WriteEndElement(); // simpleContent X.WriteEndElement(); // complexType } else { // Complex Type X.WriteAttributeString("type",h[v.ComplexType.Name_NAMESPACE].ToString()+":"+v.ComplexType.Name_LOCAL); } X.WriteEndElement(); // Element3 if (!cleanSchema) { X.WriteStartElement("xsd","any",null); X.WriteAttributeString("namespace","##other"); X.WriteAttributeString("minOccurs","0"); X.WriteAttributeString("maxOccurs","unbounded"); X.WriteAttributeString("processContents","lax"); X.WriteEndElement(); // any } X.WriteEndElement(); // sequence if (!cleanSchema) { X.WriteStartElement("xsd","anyAttribute",null); X.WriteAttributeString("namespace","##other"); X.WriteAttributeString("processContents","lax"); X.WriteEndElement(); // anyAttribute } X.WriteEndElement(); // complexType X.WriteEndElement(); // Element2 if (!cleanSchema) { X.WriteStartElement("xsd","any",null); X.WriteAttributeString("namespace","##other"); X.WriteAttributeString("minOccurs","0"); X.WriteAttributeString("maxOccurs","unbounded"); X.WriteAttributeString("processContents","lax"); X.WriteEndElement(); // any } X.WriteEndElement(); // sequence if (!cleanSchema) { X.WriteStartElement("xsd","anyAttribute",null); X.WriteAttributeString("namespace","##other"); X.WriteAttributeString("processContents","lax"); X.WriteEndElement(); // anyAttribute } X.WriteEndElement(); // complexType; X.WriteEndElement(); // Element1 } } X.WriteEndElement(); // schema X.WriteEndDocument(); StreamWriter writer3; DText PP = new DText(); PP.ATTRMARK = ":"; PP[0] = s.ServiceURN; writer3 = File.CreateText(dirInfo.FullName + "\\"+PP[PP.DCOUNT()-1]+"_Events.xsd"); System.Text.UTF8Encoding U = new System.Text.UTF8Encoding(); X.Flush(); ms.Flush(); writer3.Write(U.GetString(ms.ToArray(),2,ms.ToArray().Length-2)); writer3.Close(); ms = new MemoryStream(); X = new System.Xml.XmlTextWriter(ms,System.Text.Encoding.UTF8); X.Formatting = System.Xml.Formatting.Indented; } }
private void GenerateControlSchemas(UPnPDevice d, System.IO.DirectoryInfo dirInfo, bool cleanSchema) { System.IO.MemoryStream ms = new MemoryStream(); System.Xml.XmlTextWriter X = new System.Xml.XmlTextWriter(ms,System.Text.Encoding.UTF8); X.Formatting = System.Xml.Formatting.Indented; foreach(UPnPDevice ed in d.EmbeddedDevices) { GenerateControlSchemas(ed,dirInfo,cleanSchema); } foreach(UPnPService s in d.Services) { Hashtable h = new Hashtable(); int j=1; foreach(string sn in s.GetSchemaNamespaces()) { h[sn] = "CT"+j.ToString(); ++j; } X.WriteStartDocument(); X.WriteStartElement("xsd","schema","http://www.w3.org/2001/XMLSchema"); X.WriteAttributeString("targetNamespace",s.ServiceURN); X.WriteAttributeString("xmlns",s.ServiceURN); X.WriteAttributeString("xmlns","upnp",null,"http://www.upnp.org/Schema/DataTypes"); IDictionaryEnumerator NE = h.GetEnumerator(); while(NE.MoveNext()) { X.WriteAttributeString("xmlns",NE.Value.ToString(),null,NE.Key.ToString()); } foreach(UPnPAction a in s.Actions) { X.WriteStartElement("xsd","element",null); X.WriteAttributeString("name",a.Name); X.WriteAttributeString("type",a.Name+"Type"); X.WriteEndElement(); X.WriteStartElement("xsd","element",null); X.WriteAttributeString("name",a.Name+"Response"); X.WriteAttributeString("type",a.Name+"ResponseType"); X.WriteEndElement(); if (!cleanSchema) { X.WriteComment("Note: Some schema validation tools may consider the following xsd:any element ambiguous in this placement"); X.WriteStartElement("xsd","any",null); X.WriteAttributeString("namespace","##other"); X.WriteAttributeString("minOccurs","0"); X.WriteAttributeString("maxOccurs","unbounded"); X.WriteAttributeString("processContents","lax"); X.WriteEndElement(); // ANY } X.WriteStartElement("xsd","complexType",null); X.WriteAttributeString("name",a.Name+"Type"); X.WriteStartElement("xsd","sequence",null); foreach(UPnPArgument arg in a.Arguments) { if (arg.Direction=="in") { X.WriteStartElement("xsd","element",null); X.WriteAttributeString("name",arg.Name); if (arg.RelatedStateVar.ComplexType==null) { // Simple Types X.WriteStartElement("xsd","complexType",null); X.WriteStartElement("xsd","simpleContent",null); X.WriteStartElement("xsd","extension",null); X.WriteAttributeString("base","upnp:"+arg.RelatedStateVar.ValueType); if (!cleanSchema) { X.WriteStartElement("xsd","anyAttribute",null); X.WriteAttributeString("namespace","##other"); X.WriteAttributeString("processContents","lax"); X.WriteEndElement(); // anyAttribute } X.WriteEndElement(); // Extension X.WriteEndElement(); // simpleConent X.WriteEndElement(); // complexType } else { // Complex Types X.WriteAttributeString("type",h[arg.RelatedStateVar.ComplexType.Name_NAMESPACE].ToString()+":"+arg.RelatedStateVar.ComplexType.Name_LOCAL); } X.WriteEndElement(); // element } } if (!cleanSchema) { X.WriteStartElement("xsd","any",null); X.WriteAttributeString("namespace","##other"); X.WriteAttributeString("minOccurs","0"); X.WriteAttributeString("maxOccurs","unbounded"); X.WriteAttributeString("processContents","lax"); X.WriteEndElement(); // any } X.WriteEndElement(); // sequence if (!cleanSchema) { X.WriteStartElement("xsd","anyAttribute",null); X.WriteAttributeString("namespace","##other"); X.WriteAttributeString("processContents","lax"); X.WriteEndElement(); // anyAttribute } X.WriteEndElement(); // complexType // ActionResponse X.WriteStartElement("xsd","complexType",null); X.WriteAttributeString("name",a.Name+"ResponseType"); X.WriteStartElement("xsd","sequence",null); foreach(UPnPArgument arg in a.Arguments) { if (arg.Direction=="out" || arg.IsReturnValue) { X.WriteStartElement("xsd","element",null); X.WriteAttributeString("name",arg.Name); if (arg.RelatedStateVar.ComplexType==null) { // Simple X.WriteStartElement("xsd","complexType",null); X.WriteStartElement("xsd","simpleContent",null); X.WriteStartElement("xsd","extension",null); X.WriteAttributeString("base","upnp:"+arg.RelatedStateVar.ValueType); if (!cleanSchema) { X.WriteStartElement("xsd","anyAttribute",null); X.WriteAttributeString("namespace","##other"); X.WriteAttributeString("processContents","lax"); X.WriteEndElement(); // anyAttribute } X.WriteEndElement(); // extension X.WriteEndElement(); // simpleContent X.WriteEndElement(); // complexType } else { // Complex X.WriteAttributeString("type",h[arg.RelatedStateVar.ComplexType.Name_NAMESPACE].ToString()+":"+arg.RelatedStateVar.ComplexType.Name_LOCAL); } X.WriteEndElement(); // Element } } // After all arguments if (!cleanSchema) { X.WriteStartElement("xsd","any",null); X.WriteAttributeString("namespace","##other"); X.WriteAttributeString("minOccurs","0"); X.WriteAttributeString("maxOccurs","unbounded"); X.WriteAttributeString("processContents","lax"); X.WriteEndElement(); // any } X.WriteEndElement(); // sequence if (!cleanSchema) { X.WriteStartElement("xsd","anyAttribute",null); X.WriteAttributeString("namespace","##other"); X.WriteAttributeString("processContents","lax"); X.WriteEndElement(); // anyAttribute } X.WriteEndElement(); // complexType } X.WriteEndElement(); //schema X.WriteEndDocument(); StreamWriter writer3; DText PP = new DText(); PP.ATTRMARK = ":"; PP[0] = s.ServiceURN; writer3 = File.CreateText(dirInfo.FullName + "\\"+PP[PP.DCOUNT()-1]+".xsd"); System.Text.UTF8Encoding U = new System.Text.UTF8Encoding(); X.Flush(); ms.Flush(); writer3.Write(U.GetString(ms.ToArray(),2,ms.ToArray().Length-2)); writer3.Close(); ms = new MemoryStream(); X = new System.Xml.XmlTextWriter(ms,System.Text.Encoding.UTF8); X.Formatting = System.Xml.Formatting.Indented; } }
/// <summary> Writes the mapping of the specified class in the specified stream. </summary> /// <param name="stream">Where the xml is written; can be null if you send the writer.</param> /// <param name="type">User-defined type containing a valid attribute (can be [Class] or [xSubclass]).</param> /// <param name="writer">The XmlTextWriter used to write the xml; can be null if you send the stream. You can also create it yourself, but don't forget to write the StartElement ("hibernate-mapping") before.</param> /// <param name="writeEndDocument">Tells if the EndElement of "hibernate-mapping" must be written; send false to append many classes in the same stream.</param> /// <returns>The parameter writer if it was not null; else it is a new writer (created using the stream). Send it back to append many classes in this stream.</returns> public virtual System.Xml.XmlTextWriter Serialize(System.IO.Stream stream, System.Type type, System.Xml.XmlTextWriter writer, bool writeEndDocument) { if(stream == null && writer == null) throw new System.ArgumentNullException("stream"); if(type == null) throw new System.ArgumentNullException("type"); if( writer == null ) { writer = new System.Xml.XmlTextWriter( stream, System.Text.Encoding.UTF8 ); writer.Formatting = System.Xml.Formatting.Indented; writer.WriteStartDocument(); if(WriteDateComment) writer.WriteComment( string.Format( "Generated by NHibernate.Mapping.Attributes on {0}.", System.DateTime.Now.ToString("u") ) ); WriteHibernateMapping(writer, type); } if( IsClass(type) ) HbmWriter.WriteClass(writer, type); else if( IsSubclass(type, typeof(SubclassAttribute)) ) HbmWriter.WriteSubclass(writer, type); else if( IsSubclass(type, typeof(JoinedSubclassAttribute)) ) HbmWriter.WriteJoinedSubclass(writer, type); else if( IsSubclass(type, typeof(UnionSubclassAttribute)) ) HbmWriter.WriteUnionSubclass(writer, type); else throw new System.ArgumentException("No valid attribute; looking for [Class] or [xSubclass].", "type"); if(writeEndDocument) { writer.WriteEndElement(); // </hibernate-mapping> writer.WriteEndDocument(); writer.Flush(); if( ! Validate ) return writer; // Validate the generated XML stream try { writer.BaseStream.Position = 0; System.Xml.XmlTextReader tr = new System.Xml.XmlTextReader(writer.BaseStream); System.Xml.XmlValidatingReader vr = new System.Xml.XmlValidatingReader(tr); // Open the Schema System.IO.Stream schema = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("NHibernate.Mapping.Attributes.nhibernate-mapping.xsd"); vr.Schemas.Add("urn:nhibernate-mapping-2.2", new System.Xml.XmlTextReader(schema)); vr.ValidationType = System.Xml.ValidationType.Schema; vr.ValidationEventHandler += new System.Xml.Schema.ValidationEventHandler(XmlValidationHandler); _stop = false; while(vr.Read() && !_stop) // Read to validate (stop at the first error) ; } catch(System.Exception ex) { Error.Append(ex.ToString()).Append(System.Environment.NewLine + System.Environment.NewLine); } } else writer.Flush(); return writer; }
/// <summary> Writes the mapping of all mapped classes of the specified assembly in the specified stream. </summary> /// <param name="stream">Where the xml is written.</param> /// <param name="assembly">Assembly used to extract user-defined types containing a valid attribute (can be [Class] or [xSubclass]).</param> public virtual void Serialize(System.IO.Stream stream, System.Reflection.Assembly assembly) { if(stream == null) throw new System.ArgumentNullException("stream"); if(assembly == null) throw new System.ArgumentNullException("assembly"); System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter( stream, System.Text.Encoding.UTF8 ); writer.Formatting = System.Xml.Formatting.Indented; writer.WriteStartDocument(); if(WriteDateComment) writer.WriteComment( string.Format( "Generated from NHibernate.Mapping.Attributes on {0}.", System.DateTime.Now.ToString("u") ) ); WriteHibernateMapping(writer, null); // Write imports (classes decorated with the [ImportAttribute]) foreach(System.Type type in assembly.GetTypes()) { object[] imports = type.GetCustomAttributes(typeof(ImportAttribute), false); foreach(ImportAttribute import in imports) { writer.WriteStartElement("import"); if(import.Class != null && import.Class != string.Empty) writer.WriteAttributeString("class", import.Class); else // Assume that it is the current type that must be imported writer.WriteAttributeString("class", HbmWriterHelper.GetNameWithAssembly(type)); if(import.Rename != null && import.Rename != string.Empty) writer.WriteAttributeString("rename", import.Rename); writer.WriteEndElement(); } } // Write classes and x-subclasses (classes must come first if inherited by "external" subclasses) int classCount = 0; System.Collections.ArrayList mappedClassesNames = new System.Collections.ArrayList(); foreach(System.Type type in assembly.GetTypes()) { if( ! IsClass(type) ) continue; HbmWriter.WriteClass(writer, type); mappedClassesNames.Add(HbmWriterHelper.GetNameWithAssembly(type)); classCount++; } System.Collections.ArrayList subclasses = new System.Collections.ArrayList(); System.Collections.Specialized.StringCollection extendedClassesNames = new System.Collections.Specialized.StringCollection(); foreach(System.Type type in assembly.GetTypes()) { if( ! IsSubclass(type) ) continue; bool map = true; System.Type t = type; while( (t=t.DeclaringType) != null ) if (IsClass(t) || AreSameSubclass(type, t)) // If a base class is also mapped... (Note: A x-subclass can only contain x-subclasses of the same family) { map = false; // This class's mapping is already included in the mapping of the base class break; } if(map) { subclasses.Add(type); if( IsSubclass(type, typeof(SubclassAttribute)) ) extendedClassesNames.Add((type.GetCustomAttributes(typeof(SubclassAttribute), false)[0] as SubclassAttribute).Extends); else if( IsSubclass(type, typeof(JoinedSubclassAttribute)) ) extendedClassesNames.Add((type.GetCustomAttributes(typeof(JoinedSubclassAttribute), false)[0] as JoinedSubclassAttribute).Extends); else if( IsSubclass(type, typeof(UnionSubclassAttribute)) ) extendedClassesNames.Add((type.GetCustomAttributes(typeof(UnionSubclassAttribute), false)[0] as UnionSubclassAttribute).Extends); } } classCount += subclasses.Count; MapSubclasses(subclasses, extendedClassesNames, mappedClassesNames, writer); writer.WriteEndElement(); // </hibernate-mapping> writer.WriteEndDocument(); writer.Flush(); if(classCount == 0) throw new MappingException("The following assembly contains no mapped classes: " + assembly.FullName); if( ! Validate ) return; // Validate the generated XML stream try { writer.BaseStream.Position = 0; System.Xml.XmlTextReader tr = new System.Xml.XmlTextReader(writer.BaseStream); System.Xml.XmlValidatingReader vr = new System.Xml.XmlValidatingReader(tr); // Open the Schema System.IO.Stream schema = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("NHibernate.Mapping.Attributes.nhibernate-mapping.xsd"); vr.Schemas.Add("urn:nhibernate-mapping-2.2", new System.Xml.XmlTextReader(schema)); vr.ValidationType = System.Xml.ValidationType.Schema; vr.ValidationEventHandler += new System.Xml.Schema.ValidationEventHandler(XmlValidationHandler); _stop = false; while(vr.Read() && !_stop) // Read to validate (stop at the first error) ; } catch(System.Exception ex) { Error.Append(ex.ToString()).Append(System.Environment.NewLine + System.Environment.NewLine); } }
public void Convert(string SfmFileName, string MappingFileName, string OutputFileName, string vernWs, string regWs, string natWs) { m_NumElements = 0; // Log.Open(LogFileName); if (!UseFiles(SfmFileName, MappingFileName, OutputFileName)) { return; } using (System.Xml.XmlTextWriter xmlOutput = new System.Xml.XmlTextWriter(m_OutputFileName, System.Text.Encoding.UTF8)) { xmlOutput.Formatting = System.Xml.Formatting.Indented; xmlOutput.Indentation = 2; WriteOutputFileComment(SfmFileName, MappingFileName, OutputFileName, xmlOutput); xmlOutput.WriteComment(" database is the root element for this file "); xmlOutput.WriteStartElement("database"); System.Xml.XmlDocument xmlMap = new System.Xml.XmlDocument(); try { xmlMap.Load(m_MappingFileName); } catch (System.Xml.XmlException e) { string ErrMsg = String.Format(Sfm2XmlStrings.InvalidMappingFile0_1, m_MappingFileName, e.Message); Log.AddError(ErrMsg); // put out the warnings and errors Log.FlushTo(xmlOutput); xmlOutput.WriteEndElement(); // Close the Database node xmlOutput.Close(); return; } ReadLanguages(xmlMap); // === Process the command line args relating to languages === // National ws if (natWs.ToLowerInvariant() == STATICS.Ignore) IgnoreWs("nat"); else if (natWs.ToLowerInvariant() == "no-convert") NoConvertWs("nat"); else if (natWs.Length > 0) ConvertWs("nat", natWs); // Regional ws if (regWs.ToLowerInvariant() == STATICS.Ignore) IgnoreWs("reg"); else if (regWs.ToLowerInvariant() == "no-convert") NoConvertWs("reg"); else if (regWs.Length > 0) ConvertWs("reg", regWs); // Vern ws // if (vernWs.ToLowerInvariant() == "ignore") // IgnoreWs("vern"); if (vernWs.ToLowerInvariant() == "no-convert") NoConvertWs("vern"); else if (vernWs.Length > 0) ConvertWs("vern", vernWs); try { ReadHierarchy(xmlMap); ReadAndOutputSettings(xmlMap, xmlOutput); // read the mapping file and build internal classes / objects and // add field descriptions to output file ReadFieldDescriptions(xmlMap); // ReadAndOutputFieldDescriptions(xmlMap, xmlOutput); ReadCustomFieldDescriptions(xmlMap); // read the mapping file inline markers ReadInFieldMarkers(xmlMap); // Now vaildate the data read in. This must be done in the follwoing order: // Languages, Field Descriptions, Hierarchy. Infield Markers must be validated // after Languages. This order is needed because the later checks rely on // success of the earlier ones. ValidateLanguages(); // throw if bad language data ValidateFieldDescriptions(); ValidateCustomFieldDescriptions(); ValidateHierarchy(); ValidateInfieldMarkers(); } catch (System.Exception e) { string ErrMsg = String.Format(Sfm2XmlStrings.UnhandledException0, e.Message); Log.AddError(ErrMsg); } string nl = System.Environment.NewLine; string comments = nl; comments += " ================================================================" + nl; comments += " Element: " + m_Root.Name + nl; comments += " This element contains the inputfile in an XML format." + nl; comments += " ================================================================" + nl; xmlOutput.WriteComment(comments); // xmlOutput.WriteComment(" This element contains the inputfile in an XML format "); try { // xmlOutput.WriteStartElement(m_Root.Name); // ProcessSfmFile(xmlOutput); ProcessSfmFileNewLogic(xmlOutput); } catch (System.Exception e) { string ErrMsg = String.Format(Sfm2XmlStrings.UnhandledException0, e.Message); Log.AddError(ErrMsg); } #if false if (m_autoFieldsUsed.Count > 0) { xmlOutput.WriteComment(" This is where the autofield info goes after the data has been processed. "); xmlOutput.WriteStartElement("autofields"); foreach(DictionaryEntry autoEntry in m_autoFieldsUsed) { AutoFieldInfo afi = autoEntry.Value as AutoFieldInfo; xmlOutput.WriteStartElement("field"); xmlOutput.WriteAttributeString("class", afi.className); xmlOutput.WriteAttributeString("sfm", afi.sfmName); xmlOutput.WriteAttributeString("fwid", afi.fwDest); xmlOutput.WriteEndElement(); } xmlOutput.WriteEndElement(); } #endif // put out the field descriptions with the autofield info integrated in: for xslt processing... comments = nl; comments += " ================================================================" + nl; comments += " Element: fieldDescriptions" + nl; comments += " This element is put out after the data so that auto fields can be" + nl; comments += " added here. Otherwise, we'd have to make two passes over the data." + nl; comments += " The additional information related to auto fields is used in the" + nl; comments += " XSLT processing for building the phase2 output file." + nl; comments += " ================================================================" + nl; xmlOutput.WriteComment(comments); xmlOutput.WriteStartElement("fieldDescriptions"); foreach(DictionaryEntry fieldEntry in m_FieldDescriptionsTable) { ClsFieldDescription fd = fieldEntry.Value as ClsFieldDescription; if (fd is ClsCustomFieldDescription) continue; // the custom fields will be put out in a CustomFields section following... if (m_autoFieldsBySFM.ContainsKey(fd.SFM)) { ArrayList afiBysfm = m_autoFieldsBySFM[fd.SFM] as ArrayList; foreach(AutoFieldInfo afi in afiBysfm) { fd.AddAutoFieldInfo(afi.className, afi.fwDest); } } fd.ToXmlLangString(xmlOutput); // string xmldata = fd.ToXmlLangString(xmlOutput); // xmlOutput.WriteRaw(xmldata); } xmlOutput.WriteEndElement(); // put out the field descriptions with the autofield info integrated in: for xslt processing... comments = nl; comments += " ================================================================" + nl; comments += " Element: CustomFieldDescriptions" + nl; comments += " ================================================================" + nl; xmlOutput.WriteComment(comments); xmlOutput.WriteStartElement("CustomFieldDescriptions"); foreach (DictionaryEntry fieldEntry in m_FieldDescriptionsTable) { ClsCustomFieldDescription fd = fieldEntry.Value as ClsCustomFieldDescription; if (fd == null) continue; // not a custom field fd.ToXmlLangString(xmlOutput); // string xmldata = fd.ToXmlLangString(xmlOutput); // xmlOutput.WriteRaw(xmldata); } xmlOutput.WriteEndElement(); // put out the infield descriptions for xslt processing... comments = nl; comments += " ================================================================" + nl; comments += " Element: inFieldMarkers" + nl; comments += " This is where the infield / inline markers are put out." + nl; comments += " ================================================================" + nl; xmlOutput.WriteComment(comments); OutputInFieldMarkers(xmlOutput); #if false <!-- This is where the autofield information goes. Needed to make sense -- of the field and Records elements that use autofields --> <autofields> <field class="Entry" sfm="dan" fwid="eires"/>
/// <summary> Writes the mapping of the specified class in the specified stream. </summary> /// <param name="stream">Where the xml is written; can be null if you send the writer.</param> /// <param name="type">User-defined type containing a valid attribute (can be [Class] or [xSubclass]).</param> /// <param name="writer">The XmlTextWriter used to write the xml; can be null if you send the stream. You can also create it yourself, but don't forget to write the StartElement ("hibernate-mapping") before.</param> /// <param name="writeEndDocument">Tells if the EndElement of "hibernate-mapping" must be written; send false to append many classes in the same stream.</param> /// <returns>The parameter writer if it was not null; else it is a new writer (created using the stream). Send it back to append many classes in this stream.</returns> public virtual System.Xml.XmlTextWriter Serialize(System.IO.Stream stream, System.Type type, System.Xml.XmlTextWriter writer, bool writeEndDocument) { if (stream == null && writer == null) { throw new System.ArgumentNullException("stream"); } if (type == null) { throw new System.ArgumentNullException("type"); } if (writer == null) { writer = new System.Xml.XmlTextWriter(stream, System.Text.Encoding.UTF8); writer.Formatting = System.Xml.Formatting.Indented; writer.WriteStartDocument(); if (WriteDateComment) { writer.WriteComment(string.Format("Generated by NHibernate.Mapping.Attributes on {0}.", System.DateTime.Now.ToString("u"))); } WriteHibernateMapping(writer, type); } if (IsClass(type)) { HbmWriter.WriteClass(writer, type); } else if (IsSubclass(type, typeof(SubclassAttribute))) { HbmWriter.WriteSubclass(writer, type); } else if (IsSubclass(type, typeof(JoinedSubclassAttribute))) { HbmWriter.WriteJoinedSubclass(writer, type); } else if (IsSubclass(type, typeof(UnionSubclassAttribute))) { HbmWriter.WriteUnionSubclass(writer, type); } else { throw new System.ArgumentException("No valid attribute; looking for [Class] or [xSubclass].", "type"); } if (writeEndDocument) { writer.WriteEndElement(); // </hibernate-mapping> writer.WriteEndDocument(); writer.Flush(); if (!Validate) { return(writer); } // Validate the generated XML stream try { writer.BaseStream.Position = 0; System.Xml.XmlTextReader tr = new System.Xml.XmlTextReader(writer.BaseStream); System.Xml.XmlValidatingReader vr = new System.Xml.XmlValidatingReader(tr); // Open the Schema System.IO.Stream schema = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("NHibernate.Mapping.Attributes.nhibernate-mapping.xsd"); vr.Schemas.Add("urn:nhibernate-mapping-2.2", new System.Xml.XmlTextReader(schema)); vr.ValidationType = System.Xml.ValidationType.Schema; vr.ValidationEventHandler += new System.Xml.Schema.ValidationEventHandler(XmlValidationHandler); _stop = false; while (vr.Read() && !_stop) // Read to validate (stop at the first error) { ; } } catch (System.Exception ex) { Error.Append(ex.ToString()).Append(System.Environment.NewLine + System.Environment.NewLine); } } else { writer.Flush(); } return(writer); }
/// <summary> Writes the mapping of all mapped classes of the specified assembly in the specified stream. </summary> /// <param name="stream">Where the xml is written.</param> /// <param name="assembly">Assembly used to extract user-defined types containing a valid attribute (can be [Class] or [xSubclass]).</param> public virtual void Serialize(System.IO.Stream stream, System.Reflection.Assembly assembly) { if (stream == null) { throw new System.ArgumentNullException("stream"); } if (assembly == null) { throw new System.ArgumentNullException("assembly"); } System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(stream, System.Text.Encoding.UTF8); writer.Formatting = System.Xml.Formatting.Indented; writer.WriteStartDocument(); if (WriteDateComment) { writer.WriteComment(string.Format("Generated from NHibernate.Mapping.Attributes on {0}.", System.DateTime.Now.ToString("u"))); } WriteHibernateMapping(writer, null); // Write imports (classes decorated with the [ImportAttribute]) foreach (System.Type type in assembly.GetTypes()) { object[] imports = type.GetCustomAttributes(typeof(ImportAttribute), false); foreach (ImportAttribute import in imports) { writer.WriteStartElement("import"); if (import.Class != null && import.Class != string.Empty) { writer.WriteAttributeString("class", import.Class); } else // Assume that it is the current type that must be imported { writer.WriteAttributeString("class", HbmWriterHelper.GetNameWithAssembly(type)); } if (import.Rename != null && import.Rename != string.Empty) { writer.WriteAttributeString("rename", import.Rename); } writer.WriteEndElement(); } } // Write classes and x-subclasses (classes must come first if inherited by "external" subclasses) int classCount = 0; System.Collections.ArrayList mappedClassesNames = new System.Collections.ArrayList(); foreach (System.Type type in assembly.GetTypes()) { if (!IsClass(type)) { continue; } HbmWriter.WriteClass(writer, type); mappedClassesNames.Add(HbmWriterHelper.GetNameWithAssembly(type)); classCount++; } System.Collections.ArrayList subclasses = new System.Collections.ArrayList(); System.Collections.Specialized.StringCollection extendedClassesNames = new System.Collections.Specialized.StringCollection(); foreach (System.Type type in assembly.GetTypes()) { if (!IsSubclass(type)) { continue; } bool map = true; System.Type t = type; while ((t = t.DeclaringType) != null) { if (IsClass(t) || AreSameSubclass(type, t)) // If a base class is also mapped... (Note: A x-subclass can only contain x-subclasses of the same family) { map = false; // This class's mapping is already included in the mapping of the base class break; } } if (map) { subclasses.Add(type); if (IsSubclass(type, typeof(SubclassAttribute))) { extendedClassesNames.Add((type.GetCustomAttributes(typeof(SubclassAttribute), false)[0] as SubclassAttribute).Extends); } else if (IsSubclass(type, typeof(JoinedSubclassAttribute))) { extendedClassesNames.Add((type.GetCustomAttributes(typeof(JoinedSubclassAttribute), false)[0] as JoinedSubclassAttribute).Extends); } else if (IsSubclass(type, typeof(UnionSubclassAttribute))) { extendedClassesNames.Add((type.GetCustomAttributes(typeof(UnionSubclassAttribute), false)[0] as UnionSubclassAttribute).Extends); } } } classCount += subclasses.Count; MapSubclasses(subclasses, extendedClassesNames, mappedClassesNames, writer); writer.WriteEndElement(); // </hibernate-mapping> writer.WriteEndDocument(); writer.Flush(); if (classCount == 0) { throw new MappingException("The following assembly contains no mapped classes: " + assembly.FullName); } if (!Validate) { return; } // Validate the generated XML stream try { writer.BaseStream.Position = 0; System.Xml.XmlTextReader tr = new System.Xml.XmlTextReader(writer.BaseStream); System.Xml.XmlValidatingReader vr = new System.Xml.XmlValidatingReader(tr); // Open the Schema System.IO.Stream schema = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream("NHibernate.Mapping.Attributes.nhibernate-mapping.xsd"); vr.Schemas.Add("urn:nhibernate-mapping-2.2", new System.Xml.XmlTextReader(schema)); vr.ValidationType = System.Xml.ValidationType.Schema; vr.ValidationEventHandler += new System.Xml.Schema.ValidationEventHandler(XmlValidationHandler); _stop = false; while (vr.Read() && !_stop) // Read to validate (stop at the first error) { ; } } catch (System.Exception ex) { Error.Append(ex.ToString()).Append(System.Environment.NewLine + System.Environment.NewLine); } }