public static void Xml_FromMappings() { var types = new[] { typeof(Guid), typeof(List<string>) }; XmlReflectionImporter importer = new XmlReflectionImporter(); XmlTypeMapping[] mappings = new XmlTypeMapping[types.Length]; for (int i = 0; i < types.Length; i++) { mappings[i] = importer.ImportTypeMapping(types[i]); } var serializers = XmlSerializer.FromMappings(mappings, typeof(object)); Xml_GuidAsRoot(serializers[0]); Xml_ListGenericRoot(serializers[1]); }
private void SerializeObject(string filename) { // Create an instance of the XmlSerializer Class. XmlTypeMapping mapp = (new SoapReflectionImporter()).ImportTypeMapping(typeof(Group)); XmlSerializer mySerializer = new XmlSerializer(mapp); // Writing the file requires a TextWriter. TextWriter writer = new StreamWriter(filename); // Create an instance of the Class that will be serialized. Group myGroup = new Group(); // Set the object properties. myGroup.GroupName = ".NET"; myGroup.Grouptype = GroupType.A; // Serialize the Class, and close the TextWriter. mySerializer.Serialize(writer, myGroup); writer.Close(); }
private static XmlTypeMapping GetXmlTypeMappingFromRoot(Type type, XmlRootAttribute xmlRootAttribute) { XmlTypeMapping result = null; int hash = 17; unchecked { hash = hash * 31 + type.GUID.GetHashCode(); hash = hash * 31 + xmlRootAttribute.GetHashCode(); } lock (rootMapCache) { if (!rootMapCache.ContainsKey(hash)) { XmlReflectionImporter importer = new XmlReflectionImporter(null, null); rootMapCache[hash] = importer.ImportTypeMapping(type, xmlRootAttribute, null); } result = rootMapCache[hash]; } return(result); }
public static XmlSchema GetDataSetSchema(XmlTypeMapping mapping, string dataSetName, string dataTableName) { // create schema XmlSchema xsd = new XmlSchema(); xsd.Id = dataSetName; // create dataset-element XmlSchemaElement xsdDataset = new XmlSchemaElement(); xsdDataset.Name = dataSetName; // anonymous complextype XmlSchemaComplexType xsdDatasetType = new XmlSchemaComplexType(); // anonymous sequence XmlSchemaSequence xsdDatasetSequence = new XmlSchemaSequence(); // add sequence to complextype xsdDatasetType.Particle = xsdDatasetSequence; // add complextype to dataset-element xsdDataset.SchemaType = xsdDatasetType; // add mapped type XmlSchemas schemas = new XmlSchemas(); schemas.Add(xsd); XmlSchemaExporter exporter = new XmlSchemaExporter(schemas); exporter.ExportTypeMapping(mapping); // get datatable-element and move it to dataset-sequence XmlSchemaObject o = xsd.Items[0]; xsd.Items.RemoveAt(0); xsdDatasetSequence.Items.Add(o); // add dataset-element to xsd xsd.Items.Add(xsdDataset); //schemas.Compile(null, false); // we only need the string return(schemas[mapping.Namespace]); }
internal static CodeNamespaceResult CreateCodeNamespace(PhysicalSchema schema, string targetNamespace) { XmlSchemaSet xset = new XmlSchemaSet(); foreach (var file in schema.Files) { var sr = new StringReader(file.Content); xset.Add(XmlSchema.Read(sr, null)); } xset.Compile(); XmlSchemas schemas = new XmlSchemas(); foreach (XmlSchema xmlSchema in xset.Schemas()) { schemas.Add(xmlSchema); } XmlSchemaImporter importer = new XmlSchemaImporter(schemas); var ns = new CodeNamespace(targetNamespace); var exporter = new XmlCodeExporter(ns); var result = new CodeNamespaceResult(); foreach (XmlSchemaElement element in xset.GlobalElements.Values) { XmlTypeMapping mapping = importer.ImportTypeMapping(element.QualifiedName); if (string.IsNullOrEmpty(result.RootElementName)) { result.RootElementName = mapping.TypeName; } exporter.ExportTypeMapping(mapping); } result.Code = ns; return(result); }
public static System.Xml.XmlTextReader Get_XSD_Clase(Type Tipo_Searializar, String strNamespace) { 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; if (!String.IsNullOrEmpty(strNamespace)) { schema = schemas[strNamespace]; } else { schema = schemas[0]; } System.IO.StringWriter sWriter = new System.IO.StringWriter(); schema.Write(sWriter); System.Xml.XmlTextReader txtReader = new System.Xml.XmlTextReader(new System.IO.StringReader(sWriter.ToString())); return(txtReader); }
private void GenerateTypeElement(object o, XmlTypeMapping xmlMapping) { ElementAccessor element = xmlMapping.Accessor; TypeMapping mapping = element.Mapping; WriteStartDocument(); if (o == null) { if (element.IsNullable) { if (mapping.IsSoap) { throw new PlatformNotSupportedException(); } else { WriteNullTagLiteral(element.Name, (element.Form == XmlSchemaForm.Qualified ? element.Namespace : "")); } } else { WriteEmptyTag(element.Name, (element.Form == XmlSchemaForm.Qualified ? element.Namespace : "")); } return; } if (!mapping.TypeDesc.IsValueType && !mapping.TypeDesc.Type.IsPrimitive) { TopLevelElement(); } WriteMember(o, null, new ElementAccessor[] { element }, null, null, mapping.TypeDesc, !element.IsSoap, xmlMapping); if (mapping.IsSoap) { WriteReferencedElements(); } }
private static XmlSerializer GetSerilizer(Type typeXS, string rootnodeName, bool IsSoapXml) { XmlSerializer rtVal; if (IsSoapXml) { XmlTypeMapping myTypeMapping = (new SoapReflectionImporter()).ImportTypeMapping(typeXS); rtVal = new XmlSerializer(myTypeMapping); } else { if (!string.IsNullOrEmpty(rootnodeName)) { rtVal = new XmlSerializer(typeXS, new XmlRootAttribute(rootnodeName)); } else { rtVal = new XmlSerializer(typeXS); } } return(rtVal); }
public static void Main() { Map map = new Map(); map.Add(new Item { key = "foo", value = "bar" }); map.Add(new Item { key = "quux", value = "barf" }); XmlTypeMapping mapping = (new SoapReflectionImporter()).ImportTypeMapping(map.GetType()); XmlSerializer serializer = new XmlSerializer(mapping); XmlTextWriter writer = new XmlTextWriter(System.Console.Out); writer.Formatting = Formatting.Indented; writer.WriteStartElement("root"); serializer.Serialize(writer, map); writer.WriteEndElement(); writer.Close(); }
public void DeserializeOriginal(string filename) { // Create an instance of the XmlSerializer class. XmlTypeMapping myMapping = (new SoapReflectionImporter().ImportTypeMapping( typeof(Group))); XmlSerializer mySerializer = new XmlSerializer(myMapping); // Reading the file requires an XmlTextReader. XmlTextReader reader = new XmlTextReader(filename); reader.ReadStartElement("wrapper"); // Deserialize and cast the object. Group myGroup; myGroup = (Group)mySerializer.Deserialize(reader); reader.ReadEndElement(); reader.Close(); }
public static CodeNamespace Process(string xsdSchema, string modelsNamespace) { // Load the XmlSchema and its collection. XmlSchema xsd; using (var fs = new StringReader(xsdSchema)) { xsd = XmlSchema.Read(fs, null); xsd.Compile(null); } XmlSchemas schemas = new XmlSchemas(); schemas.Add(xsd); // Create the importer for these schemas. XmlSchemaImporter importer = new XmlSchemaImporter(schemas); // System.CodeDom namespace for the XmlCodeExporter to put classes in. CodeNamespace ns = new CodeNamespace(modelsNamespace); XmlCodeExporter exporter = new XmlCodeExporter(ns); // Iterate schema top-level elements and export code for each. foreach (XmlSchemaElement element in xsd.Elements.Values) { // Import the mapping first. XmlTypeMapping mapping = importer.ImportTypeMapping( element.QualifiedName); // Export the code finally. exporter.ExportTypeMapping(mapping); } // execute extensions //var collectionsExt = new ArraysToCollectionsExtension(); //collectionsExt.Process(ns, xsd); //var filedsExt = new FieldsToPropertiesExtension(); //filedsExt.Process(ns, xsd); return(ns); }
} //method GenerateSchemaForDocument private CodeNamespace GenerateCodeForSchema(XmlSchema schema) { XmlSchemas schemas = new XmlSchemas(); schemas.Add(schema); XmlSchemaImporter imp = new XmlSchemaImporter(schemas); CodeNamespace tempSpace = new CodeNamespace(); XmlCodeExporter exp = new XmlCodeExporter(tempSpace); // Iterate schema items (top-level elements only) and generate code for each foreach (XmlSchemaObject item in schema.Items) { if (item is XmlSchemaElement) { // Import the mapping first XmlTypeMapping map = imp.ImportTypeMapping(new XmlQualifiedName(((XmlSchemaElement)item).Name, schema.TargetNamespace)); // Export the code finally exp.ExportTypeMapping(map); } //if } //foreach return(tempSpace); } //method GenerateCodeForSchema
internal XmlMembersMapping ImportFaultElement(FaultDescription fault, out XmlQualifiedName elementName) { XmlReflectionMember[] members = new XmlReflectionMember[1]; System.ServiceModel.Description.XmlName name = fault.ElementName; string ns = fault.Namespace; if (name == null) { XmlTypeMapping mapping = this.parent.importer.ImportTypeMapping(fault.DetailType, this.IsEncoded); name = new System.ServiceModel.Description.XmlName(mapping.ElementName, this.IsEncoded); ns = mapping.Namespace; if (name == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("SFxFaultTypeAnonymous", new object[] { this.Operation.Name, fault.DetailType.FullName }))); } } elementName = new XmlQualifiedName(name.DecodedName, ns); members[0] = XmlSerializerHelper.GetXmlReflectionMember(null, name, ns, fault.DetailType, null, false, this.IsEncoded, false); string mappingKey = "fault:" + name.DecodedName + ":" + ns; return(this.ImportMembersMapping(name.EncodedName, ns, members, false, this.IsRpc, mappingKey)); }
private static void GenerateClasses(CodeNamespace code, XmlSchema schema) { XmlSchemas schemas = new XmlSchemas(); schemas.Add(schema); XmlSchemaImporter importer = new XmlSchemaImporter(schemas); CodeCompileUnit codeCompileUnit = new CodeCompileUnit(); CodeGenerationOptions options = CodeGenerationOptions.None; XmlCodeExporter exporter = new XmlCodeExporter(code, codeCompileUnit, options); foreach (XmlSchemaObject item in schema.Items) { XmlSchemaElement element = item as XmlSchemaElement; if (element != null) { XmlQualifiedName name = new XmlQualifiedName(element.Name, schema.TargetNamespace); XmlTypeMapping map = importer.ImportTypeMapping(name); exporter.ExportTypeMapping(map); } } }
public XmlArray ToXmlArray_FromDictionary(Type type, IDictionary dictionary, string mainNodeName, XmlMappingContainer mappings = null) { var keyType = this.assemblyInfoService.GetDictionaryKeyType(type); var valueType = this.assemblyInfoService.GetDictionaryValueType(type); XmlTypeMapping mapping = null; if (mappings != null && mappings.Has(valueType)) { mapping = mappings.Get(valueType); } var nullableType = Nullable.GetUnderlyingType(valueType); if (nullableType != null) { return(this.DoToXmlArray_FromDictionary(type, keyType, nullableType, dictionary, mainNodeName, mappings)); } else { return(this.DoToXmlArray_FromDictionary(type, keyType, valueType, dictionary, mainNodeName, mappings)); } }
public static byte[] GetXmlSchemaFromType(Type type) { XmlSchemas sms = new XmlSchemas(); XmlSchemaExporter ex = new XmlSchemaExporter(sms); XmlReflectionImporter im = new XmlReflectionImporter(); XmlTypeMapping map = im.ImportTypeMapping(type); ex.ExportTypeMapping(map); sms.Compile(null, false); MemoryStream ms = new MemoryStream(); StreamWriter sw = new StreamWriter(ms); foreach (System.Xml.Schema.XmlSchema sm in sms) { sm.Write(sw); } sw.Close(); ms.Flush(); byte[] data = ms.ToArray(); return(data); }
internal static object[] GetInitializers(LogicalMethodInfo[] methodInfos) { if (methodInfos.Length == 0) { return(new object[0]); } WebServiceAttribute serviceAttribute = WebServiceReflector.GetAttribute(methodInfos); bool serviceDefaultIsEncoded = SoapReflector.ServiceDefaultIsEncoded(WebServiceReflector.GetMostDerivedType(methodInfos)); XmlReflectionImporter importer = SoapReflector.CreateXmlImporter(serviceAttribute.Namespace, serviceDefaultIsEncoded); WebMethodReflector.IncludeTypes(methodInfos, importer); ArrayList mappings = new ArrayList(); for (int i = 0; i < methodInfos.Length; i++) { LogicalMethodInfo methodInfo = methodInfos[i]; Type type = methodInfo.ReturnType; if (IsSupported(type)) { XmlAttributes a = new XmlAttributes(methodInfo.ReturnTypeCustomAttributeProvider); XmlTypeMapping mapping = importer.ImportTypeMapping(type, a.XmlRoot); mappings.Add(mapping); } } XmlSerializer[] serializers = XmlSerializer.FromMappings((XmlMapping[])mappings.ToArray(typeof(XmlMapping))); object[] initializers = new object[methodInfos.Length]; int count = 0; for (int i = 0; i < initializers.Length; i++) { if (IsSupported(methodInfos[i].ReturnType)) { initializers[i] = serializers[count++]; } } return(initializers); }
/// <summary> /// Imports the XML types. /// </summary> /// <param name="type">The type.</param> /// <param name="mappings">The mappings.</param> /// <param name="importedTypes">The imported types.</param> /// <param name="importer">The importer.</param> private static void ImportXmlTypes(Type type, List <XmlMapping> mappings, List <Type> importedTypes, XmlReflectionImporter importer) { XmlTypeMapping mapping = null; var importer2 = new XmlReflectionImporter(); try { mapping = importer2.ImportTypeMapping(type); } catch (Exception exception) { if (((exception is ThreadAbortException) || (exception is StackOverflowException)) || (exception is OutOfMemoryException)) { throw; } return; } if (mapping != null) { mapping = importer.ImportTypeMapping(type); mappings.Add(mapping); importedTypes.Add(type); } }
internal void ComputeOuterNameAndNs(out string name, out string ns) { Debug.Assert(_outerName == null, "All callers of this function should already check for a null outer name."); if (_dataContractSerializer != null) { Debug.Assert(_xmlSerializer == null, "only one of xmlserializer or datacontract serializer can be present"); XsdDataContractExporter dcExporter = new XsdDataContractExporter(); XmlQualifiedName qName = dcExporter.GetRootElementName(_extensionData.GetType()); if (qName != null) { name = qName.Name; ns = qName.Namespace; } else { // this can happen if an IXmlSerializable type is specified with IsAny=true ReadOuterNameAndNs(out name, out ns); } } else { Debug.Assert(_dataContractSerializer == null, "only one of xmlserializer or datacontract serializer can be present"); XmlReflectionImporter importer = new XmlReflectionImporter(); XmlTypeMapping typeMapping = importer.ImportTypeMapping(_extensionData.GetType()); if (typeMapping != null && !string.IsNullOrEmpty(typeMapping.ElementName)) { name = typeMapping.ElementName; ns = typeMapping.Namespace; } else { // this can happen if an IXmlSerializable type is specified with IsAny=true ReadOuterNameAndNs(out name, out ns); } } }
private XmlSerializer CreateOverrideSerializer() { SoapAttributeOverrides mySoapAttributeOverrides = new SoapAttributeOverrides(); SoapAttributes soapAtts = new SoapAttributes(); // Create a new DefaultValueAttribute object for the GroupName // property. DefaultValueAttribute newDefault = new DefaultValueAttribute("Team1"); soapAtts.SoapDefaultValue = newDefault; mySoapAttributeOverrides.Add(typeof(Group), "GroupName", soapAtts); // Create an XmlTypeMapping that is used to create an instance // of the XmlSerializer. Then return the XmlSerializer object. XmlTypeMapping myMapping = (new SoapReflectionImporter( mySoapAttributeOverrides)).ImportTypeMapping(typeof(Group)); XmlSerializer ser = new XmlSerializer(myMapping); return(ser); }
private void ImportType(Type type, ArrayList mappings, ArrayList importedTypes, XmlReflectionImporter importer) { XmlTypeMapping xmlTypeMapping = null; var localImporter = new XmlReflectionImporter(); try { xmlTypeMapping = localImporter.ImportTypeMapping(type); } catch (Exception e) { if (e is ThreadAbortException || e is StackOverflowException || e is OutOfMemoryException) { throw; } return; } if (xmlTypeMapping != null) { xmlTypeMapping = importer.ImportTypeMapping(type); mappings.Add(xmlTypeMapping); importedTypes.Add(type); } }
public XmlSerializer(XmlTypeMapping xmlTypeMapping);
public static byte[] ArrayToXmlSerializedDataSet <T>(T[] array, string DataSetName, XmlTypeMapping typeMapping, XmlSchema xsd) { return(XmlUtils.StringToXML(ArrayToXmlStringSerializedDataSet(array, DataSetName, typeMapping, xsd))); }
private static byte[] ArrayToXmlSerializedDataSet <T>(T[] array, string DataSetName, string DataTableName, XmlTypeMapping typeMapping) { return(XmlUtils.StringToXML(ArrayToXmlStringSerializedDataSet(array, DataSetName, DataTableName, typeMapping))); }
public static byte[] ArrayToXmlSerializedDataSet <T>(T[] array, XmlTypeMapping typeMapping) { return(XmlUtils.StringToXML(ArrayToXmlStringSerializedDataSet(array, typeMapping))); }
public static string ArrayToXmlStringSerializedDataSet <T>(T[] array, string DataSetName, XmlTypeMapping typeMapping, XmlSchema xsd) { using (MemoryStream stream = new MemoryStream()) { XmlWriterSettings settings = new XmlWriterSettings(); settings.OmitXmlDeclaration = true; settings.Indent = true; // create writer XmlWriter writer = XmlWriter.Create(stream, settings); try { // write start root element writer.WriteStartElement(DataSetName, String.Empty); // write schema xsd.Write(writer); // don´t need namespace information on table element XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add(String.Empty, String.Empty); // create xmlserializer XmlSerializer serializer = new XmlSerializer(typeMapping); // write dataset start element writer.WriteStartElement(String.Empty, DataSetName, String.Empty); if (array != null && array.Length > 0) { // serialize each array element as datable foreach (T element in array) { serializer.Serialize(writer, element, ns); } } // write dataset end element writer.WriteEndElement(); // write root end element writer.WriteEndElement(); } finally { writer.Flush(); writer.Close(); } stream.Seek(0, SeekOrigin.Begin); StreamReader reader = new StreamReader(stream); return(reader.ReadToEnd()); } }
/// <summary> /// Generates the <see cref="CodeNamespace"/> based on the provide context. /// </summary> /// <param name="codeGeneratorContext">The code generator context.</param> public CodeNamespace GenerateCode(ICodeGeneratorContext codeGeneratorContext) { CodeGenOptions codeGenOptions = codeGeneratorContext.CodeGenOptions; XmlSchemas xmlSchemas = codeGeneratorContext.XmlSchemas; CodeNamespace codeNamespace = new CodeNamespace(); // Generate DataContracts const CodeGenerationOptions generationOptions = CodeGenerationOptions.GenerateProperties; var exporter = new XmlCodeExporter(codeNamespace); var importer = new XmlSchemaImporter(xmlSchemas, generationOptions, new ImportContext(new CodeIdentifiers(), false)); // TypeName to XmlSchemaType mapping IDictionary <string, XmlSchemaType> typeName2schemaTypeMapping = codeGeneratorContext.TypeName2schemaTypeMapping; IDictionary <XmlQualifiedName, string> elementName2TypeNameMapping = codeGeneratorContext.ElementName2TypeNameMapping; IDictionary <string, string> elementName2TargetNamespaceMapping = codeGeneratorContext.ElementName2TargetNamespaceMapping; foreach (XmlSchema schema in xmlSchemas) { foreach (XmlSchemaElement element in schema.Elements.Values) { XmlTypeMapping typeMapping = importer.ImportTypeMapping(element.QualifiedName); if (element.IsAbstract) { continue; } exporter.ExportTypeMapping(typeMapping); if (typeMapping.XsdTypeName == "anyType") { continue; // ignore no type element } if (string.IsNullOrWhiteSpace(typeMapping.XsdTypeName)) { throw new Exception("Cannot use anonymous type for Request/Response element: " + element.Name + "."); } typeName2schemaTypeMapping[typeMapping.XsdTypeName] = element.ElementSchemaType; elementName2TypeNameMapping[element.QualifiedName] = typeMapping.XsdTypeName; elementName2TargetNamespaceMapping[element.QualifiedName.Name] = schema.TargetNamespace; } foreach (XmlSchemaType complexType in schema.SchemaTypes.Values) { XmlTypeMapping typeMapping = importer.ImportSchemaType(complexType.QualifiedName); if (DataContractGenerator.CouldBeAnArray(complexType)) { continue; } exporter.ExportTypeMapping(typeMapping); typeName2schemaTypeMapping[typeMapping.TypeName] = complexType; } } if (codeNamespace.Types.Count == 0) { throw new Exception("No types were generated."); } // Build type name to code type declaration mapping codeGeneratorContext.CodeTypeMap = DataContractGenerator.BuildCodeTypeMap(codeNamespace); // Decorate data contracts code ICodeExtension codeExtension = new CodeExtension(); codeExtension.Process(codeNamespace, codeGeneratorContext); codeNamespace.ImplementsBaijiSerialization(codeGeneratorContext); // Generate interface code string wsdlFile = codeGeneratorContext.CodeGenOptions.MetadataLocation; InterfaceContract interfaceContract = ServiceDescriptionEngine.GetInterfaceContract(wsdlFile); CodeTypeDeclaration codeType; CodeNamespaceImportCollection imports; this.buildInterfaceCode(codeGeneratorContext, interfaceContract, out codeType, out imports); codeNamespace.Types.Add(codeType); foreach (CodeNamespaceImport @import in imports) { codeNamespace.Imports.Add(@import); } // Import SOA common type namespace before removing code types codeNamespace.Imports.Add(new CodeNamespaceImport(Constants.C_SERVICE_STACK_COMMON_TYPES_NAMESPACE)); // Remove SOA common types since they have already been included in CSerivceStack DLL CodeExtension.RemoveSOACommonTypes(codeNamespace); CodeExtension.RemoveDefaultTypes(codeNamespace); return(codeNamespace); }
public static DataSet ArrayToDataSet <T>(T[] array, string DataSetName, string DataTableName, XmlTypeMapping typeMapping) { DataSet dataset = new DataSet(); using (MemoryStream stream = new MemoryStream()) { XmlWriterSettings settings = new XmlWriterSettings(); settings.OmitXmlDeclaration = true; settings.Indent = true; XmlWriter writer = XmlWriter.Create(stream, settings); try { XmlSerializer serializer = new XmlSerializer(typeMapping); // write dataset start element writer.WriteStartElement(DataSetName); if (array != null && array.Length > 0) { foreach (T element in array) { serializer.Serialize(writer, element); } } else { // need to insert a dummy element to // ensure that the scheme is serialized T dummy = (T)typeof(T).GetConstructor(new Type[] {}).Invoke(new object[] {}); serializer.Serialize(writer, dummy); } // write dataset end element writer.WriteEndElement(); } finally { writer.Close(); } stream.Seek(0, SeekOrigin.Begin); dataset.ReadXml(stream, XmlReadMode.InferTypedSchema); if (array == null || array.Length == 0) { dataset.Clear(); } dataset.Tables[0].TableName = DataTableName; dataset.AcceptChanges(); } return(dataset); }
public void AddMappingMetadata(System.CodeDom.CodeAttributeDeclarationCollection metadata, XmlTypeMapping mapping, string ns) { }
public XmlSerializer CreateSerializer(XmlTypeMapping xmlTypeMapping) { }
// Methods public void ExportTypeMapping(XmlTypeMapping xmlTypeMapping) { }
/// <include file='doc\XmlSerializerFactory.uex' path='docs/doc[@for="XmlSerializerFactory.CreateSerializer5"]/*' /> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public XmlSerializer CreateSerializer(XmlTypeMapping xmlTypeMapping) { return(new XmlSerializer(xmlTypeMapping)); }
/// <summary> /// .net assemblies (dll(s) when on disk) go in and .xsd file contents comes out /// </summary> /// <param name="assembly"></param> /// <param name="typeNames"></param> /// <returns></returns> public static List <string> ExportSchemas(Assembly assembly, List <string> typeNames = null, string xmlDefaultNamespace = null) { if (typeNames == null) { typeNames = new List <string>(); } XmlReflectionImporter xmlReflectionImporter = new XmlReflectionImporter(xmlDefaultNamespace); XmlSchemas xmlSchemas = new XmlSchemas(); XmlSchemaExporter xmlSchemaExporter = new XmlSchemaExporter(xmlSchemas); try { Type[] types = assembly.GetTypes(); for (int i = 0; i < types.Length; i++) { Type type = types[i]; if (type.IsPublic && (!type.IsAbstract || !type.IsSealed) && !type.IsInterface && !type.ContainsGenericParameters) { bool flag; if (typeNames.Count == 0) { flag = true; } else { flag = false; foreach (string text2 in typeNames) { if (type.FullName == text2 || type.Name == text2 || (text2.EndsWith(".*") && type.FullName.StartsWith(text2.Substring(0, text2.Length - 2)))) { flag = true; break; } } } if (flag) { XmlTypeMapping xmlTypeMapping = xmlReflectionImporter.ImportTypeMapping(type); xmlSchemaExporter.ExportTypeMapping(xmlTypeMapping); } } } xmlSchemas.Compile(ValidationCallbackWithErrorCode, false); } catch (Exception ex) { if (ex is ThreadAbortException || ex is StackOverflowException || ex is OutOfMemoryException) { throw; } throw new InvalidOperationException("General Error", ex); } List <string> xmlSchemasList = new List <string>(xmlSchemas.Count); foreach (XmlSchema _XmlSchema in xmlSchemas) { try { using (StringWriter _StringWriter = new StringWriter()) { XmlNamespaceManager namespaceManager = new XmlNamespaceManager(new NameTable()); //// the default namespace prefix of xs makes Microsoft word upset, it was found that a //namespaceManager.AddNamespace("xsd", "http://www.w3.org/2001/XMLSchema"); _XmlSchema.Write(_StringWriter, namespaceManager); xmlSchemasList.Add(_StringWriter.ToString()); } } catch (Exception ex2) { if (ex2 is ThreadAbortException || ex2 is StackOverflowException || ex2 is OutOfMemoryException) { throw; } throw new InvalidOperationException(Res.GetString("ErrGeneral", _XmlSchema.TargetNamespace), ex2); } } return(xmlSchemasList); }
public static string ArrayToXmlStringSerializedDataSet <T>(T[] array, string DataSetName, string DataTableName, XmlTypeMapping typeMapping) { XmlSchema xsd = GetDataSetSchema(typeMapping, DataSetName, DataTableName); return(XmlUtils.ArrayToXmlStringSerializedDataSet(array, DataSetName, typeMapping, xsd)); }
/// <summary> /// Generates the <see cref="CodeNamespace"/> based on the provide context. /// </summary> /// <param name="codeGeneratorContext">The code generator context.</param> public CodeNamespace[] GenerateCodes(ICodeGeneratorContext codeGeneratorContext) { CodeGenOptions codeGenOptions = codeGeneratorContext.CodeGenOptions; XmlSchemas xmlSchemas = codeGeneratorContext.XmlSchemas; List <CodeNamespace> codeNamespaces = new List <CodeNamespace>(); // Generate DataContracts const CodeGenerationOptions generationOptions = CodeGenerationOptions.GenerateProperties; IDictionary <string, XmlSchemaType> typeName2schemaTypeMapping = codeGeneratorContext.TypeName2schemaTypeMapping; IDictionary <XmlQualifiedName, string> elementName2TypeNameMapping = codeGeneratorContext.ElementName2TypeNameMapping; IDictionary <string, string> elementName2TargetNamespaceMapping = codeGeneratorContext.ElementName2TargetNamespaceMapping; foreach (XmlSchema schema in xmlSchemas) { CodeNamespace codeNamespace = new CodeNamespace(); codeNamespace.UserData.Add(Constants.SCHEMA, schema); // TypeName to XmlSchemaType mapping XmlCodeExporter exporter = new XmlCodeExporter(codeNamespace); XmlSchemaImporter importer = new XmlSchemaImporter(xmlSchemas, generationOptions, new ImportContext(new CodeIdentifiers(), false)); foreach (XmlSchemaElement element in schema.Elements.Values) { XmlTypeMapping typeMapping = importer.ImportTypeMapping(element.QualifiedName); if (element.IsAbstract) { continue; } exporter.ExportTypeMapping(typeMapping); if (typeMapping.XsdTypeName == "anyType") { continue; // ignore no type element } if (string.IsNullOrWhiteSpace(typeMapping.XsdTypeName)) { throw new Exception("Cannot use anonymous type for Request/Response element: " + element.Name + "."); } typeName2schemaTypeMapping[typeMapping.XsdTypeName] = element.ElementSchemaType; elementName2TypeNameMapping[element.QualifiedName] = typeMapping.XsdTypeName; elementName2TargetNamespaceMapping[element.QualifiedName.Name] = schema.TargetNamespace; } foreach (XmlSchemaType schemaType in schema.SchemaTypes.Values) { if (String.IsNullOrWhiteSpace(schemaType.SourceUri)) { schemaType.SourceUri = schema.SourceUri; } XmlTypeMapping typeMapping = importer.ImportSchemaType(schemaType.QualifiedName); if (DataContractGenerator.CouldBeAnArray(schemaType)) { continue; } exporter.ExportTypeMapping(typeMapping); typeName2schemaTypeMapping[typeMapping.TypeName] = schemaType; } if (codeNamespace.Types.Count > 0) { codeNamespaces.Add(codeNamespace); } } if (codeNamespaces.Count == 0) { throw new Exception("No types were generated."); } // Build type name to code type declaration mapping codeGeneratorContext.CodeTypeMap = DataContractGenerator.BuildCodeTypeMap(codeNamespaces.ToArray()); for (int i = 0; i < codeNamespaces.Count; i++) { CodeNamespace codeNamespace = codeNamespaces[i]; // Decorate data contracts code ICodeExtension codeExtension = new CodeExtension(); codeExtension.Process(codeNamespace, codeGeneratorContext); // Import SOA common type namespace before removing code types codeNamespace.Imports.Add(new CodeNamespaceImport(Constants.C_SERVICE_STACK_COMMON_TYPES_NAMESPACE)); // Remove SOA common types since they have already been included in CSerivceStack DLL CodeExtension.RemoveSOACommonTypes(codeNamespace); CodeExtension.RemoveDefaultTypes(codeNamespace); XmlSchema schema = codeNamespace.UserData[Constants.SCHEMA] as XmlSchema; List <CodeTypeDeclaration> types = new List <CodeTypeDeclaration>(); foreach (XmlSchemaType schemaType in schema.SchemaTypes.Values) { foreach (CodeTypeDeclaration codeType in codeNamespace.Types) { if (codeType.Name == schemaType.Name && schema.SourceUri == schemaType.SourceUri) { types.Add(codeType); } } } codeNamespace.Types.Clear(); codeNamespace.Types.AddRange(types.ToArray()); if (codeNamespace.Types.Count == 0) { codeNamespaces.RemoveAt(i--); } } codeNamespaces.ImplementsBaijiSerialization(codeGeneratorContext); //Add Interface CodeNamespace CodeNamespace interfaceNamespace = new CodeNamespace(codeGenOptions.ClrNamespace); // Generate interface code string wsdlFile = codeGeneratorContext.CodeGenOptions.MetadataLocation; InterfaceContract interfaceContract = ServiceDescriptionEngine.GetInterfaceContract(wsdlFile); CodeTypeDeclaration interfaceType; CodeNamespaceImportCollection imports; this.buildInterfaceCode(codeGeneratorContext, interfaceContract, out interfaceType, out imports); interfaceNamespace.Types.Add(interfaceType); foreach (CodeNamespaceImport @import in imports) { interfaceNamespace.Imports.Add(@import); } // Import SOA common type namespace before removing code types interfaceNamespace.Imports.Add(new CodeNamespaceImport(Constants.C_SERVICE_STACK_COMMON_TYPES_NAMESPACE)); // Remove SOA common types since they have already been included in CSerivceStack DLL CodeExtension.RemoveSOACommonTypes(interfaceNamespace); CodeExtension.RemoveDefaultTypes(interfaceNamespace); string fileName = null; if (codeGeneratorContext.CodeGenOptions.CodeGeneratorMode == CodeGeneratorMode.Service) { fileName = "I" + interfaceContract.ServiceName.Replace("Interface", string.Empty); } else { fileName = interfaceContract.ServiceName.Replace("Interface", string.Empty) + "Client"; } interfaceNamespace.UserData.Add(Constants.FILE_NAME, fileName); codeNamespaces.Add(interfaceNamespace); return(codeNamespaces.ToArray()); }