public void CanExportTest () { XsdDataContractExporter xdce = new XsdDataContractExporter (); Assert.IsTrue (xdce.CanExport (typeof (int)), "#1"); Assert.IsTrue (xdce.CanExport (typeof (dc)), "#2"); //No DataContract/Serializable etc -> changed in 3.5 Assert.IsTrue (xdce.CanExport (this.GetType ()), "#3"); }
public static bool IsValidParameter(Type type, ICustomAttributeProvider attributeProvider, bool allowReferences) { object[] attributes = System.ServiceModel.Description.ServiceReflector.GetCustomAttributes(attributeProvider, typeof(MarshalAsAttribute), true); foreach (MarshalAsAttribute attr in attributes) { UnmanagedType marshalAs = attr.Value; if (marshalAs == UnmanagedType.IDispatch || marshalAs == UnmanagedType.Interface || marshalAs == UnmanagedType.IUnknown) { return allowReferences; } } XsdDataContractExporter exporter = new XsdDataContractExporter(); if (!exporter.CanExport(type)) { return false; } return true; }
public void ExportXSDUsingDataContractExporter() { //create schema XsdDataContractExporter _exporter = new XsdDataContractExporter(); Type _ConfigurationDataType = typeof(ConfigurationData); Assert.IsTrue(_exporter.CanExport(_ConfigurationDataType)); _exporter.Export(_ConfigurationDataType); Console.WriteLine("number of schemas: {0}", _exporter.Schemas.Count); Console.WriteLine(); //write out the schema XmlSchemaSet _Schemas = _exporter.Schemas; XmlQualifiedName XmlNameValue = _exporter.GetRootElementName(_ConfigurationDataType); string EmployeeNameSpace = XmlNameValue.Namespace; foreach (XmlSchema _schema in _Schemas.Schemas(EmployeeNameSpace)) _schema.Write(Console.Out); }
public static string GetXsd(Type operationType) { if (operationType == null) return null; var sb = new StringBuilder(); var exporter = new XsdDataContractExporter(); if (exporter.CanExport(operationType)) { exporter.Export(operationType); var mySchemas = exporter.Schemas; var qualifiedName = exporter.GetRootElementName(operationType); if (qualifiedName == null) return null; foreach (XmlSchema schema in mySchemas.Schemas(qualifiedName.Namespace)) { schema.Write(new StringWriter(sb)); } } return sb.ToString(); }
public static bool IsValidParameter(Type type, ICustomAttributeProvider attributeProvider, bool allowReferences) { foreach (MarshalAsAttribute attribute in ServiceReflector.GetCustomAttributes(attributeProvider, typeof(MarshalAsAttribute), true)) { switch (attribute.Value) { case UnmanagedType.IDispatch: case UnmanagedType.Interface: case UnmanagedType.IUnknown: return allowReferences; } } XsdDataContractExporter exporter = new XsdDataContractExporter(); if (!exporter.CanExport(type)) { return false; } return true; }
// This is a helper method called after a type has been selected to determine whether the type is valid // for use as a parameter type. This check it too expensive to perform during filtering. public static bool IsValidType(Type type) { bool result = true; if (!IsExemptType(type)) { try { XsdDataContractExporter exporter = new XsdDataContractExporter(); if (!exporter.CanExport(type)) { result = false; } } catch (InvalidDataContractException exception) { DiagnosticUtility.TraceHandledException(exception, TraceEventType.Warning); result = false; } catch (NotImplementedException exception) { // This occurs when a design-time type is involved (for example, as a type parameter), in // which case we don't want to exclude the type from use as parameter type. DiagnosticUtility.TraceHandledException(exception, TraceEventType.Information); } } return result; }
public static bool IsValidParameter(Type type, ICustomAttributeProvider attributeProvider, bool allowReferences, out string typeMismatchDetails) { typeMismatchDetails = type.ToString() + " "; object[] attributes = attributeProvider.GetCustomAttributes(typeof(MarshalAsAttribute), true); foreach (MarshalAsAttribute attr in attributes) { UnmanagedType marshalAs = attr.Value; if (marshalAs == UnmanagedType.IDispatch || marshalAs == UnmanagedType.Interface || marshalAs == UnmanagedType.IUnknown) { if (!allowReferences) typeMismatchDetails += SR.GetString(SR.HasMarshalAsAttributeOfType, marshalAs); return allowReferences; } } XsdDataContractExporter exporter = new XsdDataContractExporter(); if (!exporter.CanExport(type)) { typeMismatchDetails += SR.GetString(SR.CannotBeExportedByDataContractExporter); return false; } return true; }
Message CreateExample(Type type, OperationDescription od, bool generateJson) { bool usesXmlSerializer = od.Behaviors.Contains(typeof(XmlSerializerOperationBehavior)); XmlQualifiedName name; XmlSchemaSet schemaSet = new XmlSchemaSet(); IDictionary<XmlQualifiedName, Type> knownTypes = new Dictionary<XmlQualifiedName, Type>(); if (usesXmlSerializer) { XmlReflectionImporter importer = new XmlReflectionImporter(); XmlTypeMapping typeMapping = importer.ImportTypeMapping(type); name = new XmlQualifiedName(typeMapping.ElementName, typeMapping.Namespace); XmlSchemas schemas = new XmlSchemas(); XmlSchemaExporter exporter = new XmlSchemaExporter(schemas); exporter.ExportTypeMapping(typeMapping); foreach (XmlSchema schema in schemas) { schemaSet.Add(schema); } } else { XsdDataContractExporter exporter = new XsdDataContractExporter(); List<Type> listTypes = new List<Type>(od.KnownTypes); listTypes.Add(type); exporter.Export(listTypes); if (!exporter.CanExport(type)) { throw new NotSupportedException(String.Format("Example generation is not supported for type '{0}'", type)); } name = exporter.GetRootElementName(type); foreach (Type knownType in od.KnownTypes) { XmlQualifiedName knownTypeName = exporter.GetSchemaTypeName(knownType); if (!knownTypes.ContainsKey(knownTypeName)) { knownTypes.Add(knownTypeName, knownType); } } foreach (XmlSchema schema in exporter.Schemas.Schemas()) { schemaSet.Add(schema); } } schemaSet.Compile(); XmlWriterSettings settings = new XmlWriterSettings { CloseOutput = false, Indent = true, }; if (generateJson) { var jsonExample = new XDocument(); using (XmlWriter writer = XmlWriter.Create(jsonExample.CreateWriter(), settings)) { HelpExampleGenerator.GenerateJsonSample(schemaSet, name, writer, knownTypes); } var reader = jsonExample.CreateReader(); reader.MoveToContent(); var message = Message.CreateMessage(MessageVersion.None, (string)null, reader); WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain"; message.Properties[WebBodyFormatMessageProperty.Name] = new WebBodyFormatMessageProperty(WebContentFormat.Json); return message; } else { var xmlExample = new XDocument(); using (XmlWriter writer = XmlWriter.Create(xmlExample.CreateWriter(), settings)) { HelpExampleGenerator.GenerateXmlSample(schemaSet, name, writer); } var reader = xmlExample.CreateReader(); reader.MoveToContent(); var message = Message.CreateMessage(MessageVersion.None, (string)null, reader); message.Properties[WebBodyFormatMessageProperty.Name] = new WebBodyFormatMessageProperty(WebContentFormat.Xml); WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml"; return message; } }
/// <summary> /// Returns the sequence of properties of the specified type. /// </summary> /// <param name="type">The type.</param> /// <param name="schema">The schema.</param> /// <param name="schemaSet">The schema set.</param> /// <param name="serializationManager">The serialization manager.</param> /// <param name="exportedTypes">The exported types.</param> /// <returns>Sequence containing all properties.</returns> private static XmlSchemaSequence GetPropertiesSequence(Type type, XmlSchema schema, XmlSchemaSet schemaSet, ISerializationManager serializationManager, HashSet<string> exportedTypes) { Argument.IsNotNull("type", type); Argument.IsNotNull("schema", schema); Argument.IsNotNull("schemaSet", schemaSet); var propertiesSequence = new XmlSchemaSequence(); if (type.IsModelBase()) { var members = new List<MemberMetadata>(); members.AddRange(from field in serializationManager.GetFieldsToSerialize(type) select field.Value); members.AddRange(from property in serializationManager.GetCatelPropertiesToSerialize(type) select property.Value); members.AddRange(from property in serializationManager.GetRegularPropertiesToSerialize(type) select property.Value); foreach (var member in members) { var propertySchemaElement = new XmlSchemaElement(); propertySchemaElement.Name = member.MemberName; var memberType = member.MemberType; propertySchemaElement.IsNillable = memberType.IsNullableType(); propertySchemaElement.MinOccurs = 0; var exporter = new XsdDataContractExporter(schemaSet); var alreadyExported = IsAlreadyExported(schemaSet, memberType, exporter, exportedTypes); if (!alreadyExported) { if (!exportedTypes.Contains(memberType.FullName)) { exportedTypes.Add(memberType.FullName); } try { if (exporter.CanExport(memberType)) { exporter.Export(memberType); } } catch (Exception) { // Ignore } } propertySchemaElement.SchemaType = exporter.GetSchemaType(memberType); propertySchemaElement.SchemaTypeName = exporter.GetSchemaTypeName(memberType); propertiesSequence.Items.Add(propertySchemaElement); } } return propertiesSequence; }
public override bool CanConvert(Type type) { XsdDataContractExporter exporter = new XsdDataContractExporter(); return exporter.CanExport(type); }
internal MessageHelpInformation(OperationDescription od, bool isRequest, Type type, bool wrapped) { this.Type = type; this.SupportsJson = WebHttpBehavior.SupportsJsonFormat(od); string direction = isRequest ? SR2.GetString(SR2.HelpPageRequest) : SR2.GetString(SR2.HelpPageResponse); if (wrapped && !typeof(void).Equals(type)) { this.BodyDescription = SR2.GetString(SR2.HelpPageBodyIsWrapped, direction); this.FormatString = SR2.GetString(SR2.HelpPageUnknown); } else if (typeof(void).Equals(type)) { this.BodyDescription = SR2.GetString(SR2.HelpPageBodyIsEmpty, direction); this.FormatString = SR2.GetString(SR2.HelpPageNA); } else if (typeof(Message).IsAssignableFrom(type)) { this.BodyDescription = SR2.GetString(SR2.HelpPageIsMessage, direction); this.FormatString = SR2.GetString(SR2.HelpPageUnknown); } else if (typeof(Stream).IsAssignableFrom(type)) { this.BodyDescription = SR2.GetString(SR2.HelpPageIsStream, direction); this.FormatString = SR2.GetString(SR2.HelpPageUnknown); } else if (typeof(Atom10FeedFormatter).IsAssignableFrom(type)) { this.BodyDescription = SR2.GetString(SR2.HelpPageIsAtom10Feed, direction); this.FormatString = WebMessageFormat.Xml.ToString(); } else if (typeof(Atom10ItemFormatter).IsAssignableFrom(type)) { this.BodyDescription = SR2.GetString(SR2.HelpPageIsAtom10Entry, direction); this.FormatString = WebMessageFormat.Xml.ToString(); } else if (typeof(AtomPub10ServiceDocumentFormatter).IsAssignableFrom(type)) { this.BodyDescription = SR2.GetString(SR2.HelpPageIsAtomPubServiceDocument, direction); this.FormatString = WebMessageFormat.Xml.ToString(); } else if (typeof(AtomPub10CategoriesDocumentFormatter).IsAssignableFrom(type)) { this.BodyDescription = SR2.GetString(SR2.HelpPageIsAtomPubCategoriesDocument, direction); this.FormatString = WebMessageFormat.Xml.ToString(); } else if (typeof(Rss20FeedFormatter).IsAssignableFrom(type)) { this.BodyDescription = SR2.GetString(SR2.HelpPageIsRSS20Feed, direction); this.FormatString = WebMessageFormat.Xml.ToString(); } else if (typeof(SyndicationFeedFormatter).IsAssignableFrom(type)) { this.BodyDescription = SR2.GetString(SR2.HelpPageIsSyndication, direction); this.FormatString = WebMessageFormat.Xml.ToString(); } else if (typeof(XElement).IsAssignableFrom(type) || typeof(XmlElement).IsAssignableFrom(type)) { this.BodyDescription = SR2.GetString(SR2.HelpPageIsXML, direction); this.FormatString = WebMessageFormat.Xml.ToString(); } else { try { bool usesXmlSerializer = od.Behaviors.Contains(typeof(XmlSerializerOperationBehavior)); XmlQualifiedName name; this.SchemaSet = new XmlSchemaSet(); IDictionary<XmlQualifiedName, Type> knownTypes = new Dictionary<XmlQualifiedName, Type>(); if (usesXmlSerializer) { XmlReflectionImporter importer = new XmlReflectionImporter(); XmlTypeMapping typeMapping = importer.ImportTypeMapping(this.Type); name = new XmlQualifiedName(typeMapping.ElementName, typeMapping.Namespace); XmlSchemas schemas = new XmlSchemas(); XmlSchemaExporter exporter = new XmlSchemaExporter(schemas); exporter.ExportTypeMapping(typeMapping); foreach (XmlSchema schema in schemas) { this.SchemaSet.Add(schema); } } else { XsdDataContractExporter exporter = new XsdDataContractExporter(); List<Type> listTypes = new List<Type>(od.KnownTypes); bool isQueryable; Type dataContractType = DataContractSerializerOperationFormatter.GetSubstituteDataContractType(this.Type, out isQueryable); listTypes.Add(dataContractType); exporter.Export(listTypes); if (!exporter.CanExport(dataContractType)) { this.BodyDescription = SR2.GetString(SR2.HelpPageCouldNotGenerateSchema); this.FormatString = SR2.GetString(SR2.HelpPageUnknown); return; } name = exporter.GetRootElementName(dataContractType); DataContract typeDataContract = DataContract.GetDataContract(dataContractType); if (typeDataContract.KnownDataContracts != null) { foreach (XmlQualifiedName dataContractName in typeDataContract.KnownDataContracts.Keys) { knownTypes.Add(dataContractName, typeDataContract.KnownDataContracts[dataContractName].UnderlyingType); } } foreach (Type knownType in od.KnownTypes) { XmlQualifiedName knownTypeName = exporter.GetSchemaTypeName(knownType); if (!knownTypes.ContainsKey(knownTypeName)) { knownTypes.Add(knownTypeName, knownType); } } foreach (XmlSchema schema in exporter.Schemas.Schemas()) { this.SchemaSet.Add(schema); } } this.SchemaSet.Compile(); XmlWriterSettings settings = new XmlWriterSettings { CloseOutput = false, Indent = true, }; if (this.SupportsJson) { XDocument exampleDocument = new XDocument(); using (XmlWriter writer = XmlWriter.Create(exampleDocument.CreateWriter(), settings)) { HelpExampleGenerator.GenerateJsonSample(this.SchemaSet, name, writer, knownTypes); } this.JsonExample = exampleDocument.Root; } if (name.Namespace != "http://schemas.microsoft.com/2003/10/Serialization/") { foreach (XmlSchema schema in this.SchemaSet.Schemas(name.Namespace)) { this.Schema = schema; } } XDocument XmlExampleDocument = new XDocument(); using (XmlWriter writer = XmlWriter.Create(XmlExampleDocument.CreateWriter(), settings)) { HelpExampleGenerator.GenerateXmlSample(this.SchemaSet, name, writer); } this.XmlExample = XmlExampleDocument.Root; } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } this.BodyDescription = SR2.GetString(SR2.HelpPageCouldNotGenerateSchema); this.FormatString = SR2.GetString(SR2.HelpPageUnknown); this.Schema = null; this.JsonExample = null; this.XmlExample = null; } } }
public static string GetSchema(IEnumerable<Type> typesToExport) { XsdDataContractExporter exporter = new XsdDataContractExporter(); Type headType = null; foreach (Type t in typesToExport) { if(headType ==null) headType = t; if (!exporter.CanExport(t)) throw new ArgumentException("cannot export type: " + t.ToString()); exporter.Export(t); Console.WriteLine("number of schemas: {0}", exporter.Schemas.Count); Console.WriteLine(); } XmlSchemaSet schemas = exporter.Schemas; XmlQualifiedName XmlNameValue = exporter.GetRootElementName(headType); string ns = XmlNameValue.Namespace; StringWriter w = new StringWriter(); foreach (XmlSchema schema in schemas.Schemas(ns)) { //if(schema. schema.Write(w); } Debug.WriteLine(w.ToString()); return schemas.ToString(); }
/// <summary> /// Returns the sequence of properties of the specified type. /// </summary> /// <param name="type">The type.</param> /// <param name="schema">The schema.</param> /// <param name="schemaSet">The schema set.</param> /// <param name="serializationManager">The serialization manager.</param> /// <param name="exportedTypes">The exported types.</param> /// <returns>Sequence containing all properties.</returns> private static XmlSchemaSequence GetPropertiesSequence(Type type, XmlSchema schema, XmlSchemaSet schemaSet, ISerializationManager serializationManager, HashSet<string> exportedTypes) { Argument.IsNotNull("type", type); Argument.IsNotNull("schema", schema); Argument.IsNotNull("schemaSet", schemaSet); var propertiesSequence = new XmlSchemaSequence(); if (typeof(ModelBase).IsAssignableFromEx(type)) { var members = new List<MemberInfo>(); members.AddRange(from field in serializationManager.GetFieldsToSerialize(type) select type.GetFieldEx(field)); members.AddRange(from property in serializationManager.GetPropertiesToSerialize(type) select type.GetPropertyEx(property)); foreach (var member in members) { var propertySchemaElement = new XmlSchemaElement(); propertySchemaElement.Name = member.Name; var memberType = typeof(object); var fieldInfo = member as FieldInfo; if (fieldInfo != null) { memberType = fieldInfo.FieldType; } var propertyInfo = member as PropertyInfo; if (propertyInfo != null) { memberType = propertyInfo.PropertyType; } propertySchemaElement.IsNillable = memberType.IsNullableType(); propertySchemaElement.MinOccurs = 0; var exporter = new XsdDataContractExporter(schemaSet); var alreadyExported = IsAlreadyExported(schemaSet, memberType, exporter, exportedTypes); if (!alreadyExported) { if (!exportedTypes.Contains(memberType.FullName)) { exportedTypes.Add(memberType.FullName); } try { if (exporter.CanExport(memberType)) { exporter.Export(memberType); } } catch (Exception) { // Ignore } } propertySchemaElement.SchemaType = exporter.GetSchemaType(memberType); propertySchemaElement.SchemaTypeName = exporter.GetSchemaTypeName(memberType); propertiesSequence.Items.Add(propertySchemaElement); } } return propertiesSequence; }