Exemple #1
0
        public static string GetXsd(Type operationType)
        {
            if (operationType == null)
            {
                return(null);
            }
            var sb       = StringBuilderCache.Allocate();
            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(StringBuilderCache.ReturnAndFree(sb));
        }
Exemple #2
0
    //</snippet1>

    //<snippet2>
    static void GetXmlElementName()
    {
        XsdDataContractExporter myExporter     = new XsdDataContractExporter();
        XmlQualifiedName        xmlElementName = myExporter.GetRootElementName(typeof(Employee));

        Console.WriteLine("Namespace: {0}", xmlElementName.Namespace);
        Console.WriteLine("Name: {0}", xmlElementName.Name);
        Console.WriteLine("IsEmpty: {0}", xmlElementName.IsEmpty);
    }
Exemple #3
0
        /// <summary>
        /// Serialize object schema to XSD file.
        /// </summary>
        /// <param name="o">The object to serialize.</param>
        /// <param name="path">The file name to write to.</param>
        /// <param name="encoding">The encoding to use (default is UTF8).</param>
        public static void SerializeToXsdFile(object o, string path, Encoding encoding = null, bool omitXmlDeclaration = false, int attempts = 2, int waitTime = 500)
        {
            if (o == null)
            {
                WriteFile(path, new byte[0], attempts, waitTime);
                return;
            }
            encoding = encoding ?? Encoding.UTF8;
            // Create serialization settings.
            XmlWriterSettings settings = new XmlWriterSettings();

            settings.OmitXmlDeclaration = omitXmlDeclaration;
            settings.Encoding           = encoding;
            settings.Indent             = true;
            // Serialize in memory first, so file will be locked for shorter times.
            MemoryStream  ms         = new MemoryStream();
            XmlWriter     xw         = XmlWriter.Create(ms, settings);
            XmlSerializer serializer = GetXmlSerializer(o.GetType());

            try
            {
                XsdDataContractExporter exporter = new XsdDataContractExporter();
                if (exporter.CanExport(o.GetType()))
                {
                    exporter.Export(o.GetType());
                    //Console.WriteLine("number of schemas: {0}", exporter.Schemas.Count);
                    XmlSchemaSet     schemas      = exporter.Schemas;
                    XmlQualifiedName XmlNameValue = exporter.GetRootElementName(o.GetType());
                    string           nameSpace    = XmlNameValue.Namespace;
                    foreach (XmlSchema schema in schemas.Schemas(nameSpace))
                    {
                        schema.Write(xw);
                    }
                }
            }
            catch (Exception)
            {
                xw.Close();
                // CA2202: Do not dispose objects multiple times
                //ms.Close();
                xw = null;
                ms = null;
                throw;
            }
            xw.Flush();
            byte[] bytes = ms.ToArray();
            xw.Close();
            // CA2202: Do not dispose objects multiple times
            //ms.Close();
            xw = null;
            ms = null;
            // Write serialized data into file.
            WriteFile(path, bytes, attempts, waitTime);
        }
Exemple #4
0
        public void ExportXsdToFile(Type type, string filename, System.Text.Encoding encoding, params Type[] knownTypes)
        {
            var exporter = new XsdDataContractExporter();

            // Use the ExportOptions to add the Possessions type to the
            // collection of KnownTypes.
            if (knownTypes.Length > 0)
            {
                var eo = new ExportOptions();
                foreach (var kt in knownTypes)
                {
                    eo.KnownTypes.Add(kt);
                }
                exporter.Options = eo;
            }
            if (exporter.CanExport(type))
            {
                exporter.Export(type);

                var       XmlNameValue = exporter.GetRootElementName(type);
                var       nameSpace    = XmlNameValue.Namespace;
                XmlSchema mainSchema   = null;
                foreach (XmlSchema schema in exporter.Schemas.Schemas(nameSpace))
                {
                    mainSchema = schema;
                }
                var i = 0;
                foreach (XmlSchema schema in exporter.Schemas.Schemas())
                {
                    if (schema == mainSchema)
                    {
                        var file = new System.Xml.XmlTextWriter(filename, encoding);
                        file.Formatting = System.Xml.Formatting.Indented;
                        schema.Write(file);
                        file.Flush();
                        file.Close();
                    }
                    else
                    {
                        var dir     = System.IO.Path.GetDirectoryName(filename);
                        var nam     = System.IO.Path.GetFileNameWithoutExtension(filename);
                        var ext     = System.IO.Path.GetExtension(filename);
                        var newName = System.IO.Path.Combine(dir, nam + "." + (i++) + ext);
                        var file    = new System.Xml.XmlTextWriter(newName, encoding);
                        file.Formatting = System.Xml.Formatting.Indented;
                        schema.Write(file);
                        file.Flush();
                        file.Close();
                    }
                }
            }
        }
Exemple #5
0
        public static void AddMessagePartDescription(OperationDescription operation, bool isResponse,
                                                     MessageDescription message, Type type, SerializerOption serializerOption)
        {
            if (type != null)
            {
                string partName;
                string partNamespace;

                if (serializerOption == SerializerOption.DataContractSerializer)
                {
                    XmlQualifiedName xmlQualifiedName = XsdDataContractExporter.GetRootElementName(type);
                    if (xmlQualifiedName == null)
                    {
                        xmlQualifiedName = XsdDataContractExporter.GetSchemaTypeName(type);
                    }

                    if (!xmlQualifiedName.IsEmpty)
                    {
                        partName      = xmlQualifiedName.Name;
                        partNamespace = xmlQualifiedName.Namespace;
                    }
                    else
                    {
                        // For anonymous type, we assign CLR type name and contract namespace to MessagePartDescription
                        partName      = type.Name;
                        partNamespace = operation.DeclaringContract.Namespace;
                    }
                }
                else
                {
                    XmlTypeMapping xmlTypeMapping = XmlReflectionImporter.ImportTypeMapping(type);
                    partName      = xmlTypeMapping.ElementName;
                    partNamespace = xmlTypeMapping.Namespace;
                }

                MessagePartDescription messagePart = new MessagePartDescription(NamingHelper.XmlName(partName), partNamespace)
                {
                    Index = 0,
                    Type  = type

                            // We do not infer MessagePartDescription.ProtectionLevel
                };

                message.Body.Parts.Add(messagePart);
            }

            if (isResponse)
            {
                SetReturnValue(message, operation);
            }
        }
Exemple #6
0
        /// <summary>
        /// Declares a native type.  Not required, but encouraged.
        /// </summary>
        /// <param name="nativeType">Type of the native.</param>
        public void RegisterType(Type nativeType)
        {
            if ((nativeType == null) ||
                (nativeType.IsBuiltinDataType()))
            {
                return;
            }

            lock (_registeredTypes)
            {
                if (_registeredTypes.Contains(nativeType))
                {
                    return;
                }

                var dataContractExporter = new XsdDataContractExporter();
                dataContractExporter.Export(nativeType);

                var rootElementName      = dataContractExporter.GetRootElementName(nativeType);
                var rootElementSchemaSet = dataContractExporter.Schemas;

                using (var wrapper = CreateControlManager())
                {
                    WithExceptionHandling(
                        delegate
                    {
                        var controlManager      = wrapper.Channel;
                        var eventTypeDefinition = new NativeTypeDefinition(
                            rootElementName,
                            rootElementSchemaSet);

                        controlManager.RegisterType(_instanceId, eventTypeDefinition);
                    });
                }

                _registeredTypes.Add(nativeType);

                Log.Info("RegisterType: Type '{0}' registered", nativeType.FullName);

                if (TypeRegistered != null)
                {
                    TypeRegistered(this, new TypeEventArgs(nativeType));
                }
            }
        }
Exemple #7
0
        public void GetRootElementName(string testname, Type t, XmlQualifiedName rName, Type expectedExceptionType = null, string msg = null)
        {
            _output.WriteLine($"=============== {testname} ===============");
            XsdDataContractExporter exporter = new XsdDataContractExporter();

            if (expectedExceptionType == null)
            {
                XmlQualifiedName rootTypeName = exporter.GetRootElementName(t);
                Assert.Equal(rName, rootTypeName);
            }
            else
            {
                var ex = Assert.Throws(expectedExceptionType, () => exporter.GetSchemaTypeName(t));
                if (!string.IsNullOrEmpty(msg))
                {
                    Assert.Equal(msg, ex.Message);
                }
            }
        }
Exemple #8
0
 public static void AddMessagePartDescription(OperationDescription operation, bool isResponse, MessageDescription message, Type type, SerializerOption serializerOption)
 {
     if (type != null)
     {
         string name;
         string str2;
         if (serializerOption == SerializerOption.DataContractSerializer)
         {
             XmlQualifiedName rootElementName = XsdDataContractExporter.GetRootElementName(type);
             if (rootElementName == null)
             {
                 rootElementName = XsdDataContractExporter.GetSchemaTypeName(type);
             }
             if (!rootElementName.IsEmpty)
             {
                 name = rootElementName.Name;
                 str2 = rootElementName.Namespace;
             }
             else
             {
                 name = type.Name;
                 str2 = operation.DeclaringContract.Namespace;
             }
         }
         else
         {
             XmlTypeMapping mapping = XmlReflectionImporter.ImportTypeMapping(type);
             name = mapping.ElementName;
             str2 = mapping.Namespace;
         }
         MessagePartDescription item = new MessagePartDescription(NamingHelper.XmlName(name), str2)
         {
             Index = 0,
             Type  = type
         };
         message.Body.Parts.Add(item);
     }
     if (isResponse)
     {
         SetReturnValue(message, operation);
     }
 }
Exemple #9
0
    //<snippet1>
    static void ExportXSD()
    {
        XsdDataContractExporter exporter = new XsdDataContractExporter();

        if (exporter.CanExport(typeof(Employee)))
        {
            exporter.Export(typeof(Employee));
            Console.WriteLine("number of schemas: {0}", exporter.Schemas.Count);
            Console.WriteLine();
            XmlSchemaSet mySchemas = exporter.Schemas;

            XmlQualifiedName XmlNameValue      = exporter.GetRootElementName(typeof(Employee));
            string           EmployeeNameSpace = XmlNameValue.Namespace;

            foreach (XmlSchema schema in mySchemas.Schemas(EmployeeNameSpace))
            {
                schema.Write(Console.Out);
            }
        }
    }
 internal void ComputeOuterNameAndNs(out string name, out string ns)
 {
     if (_outerName != null)
     {
         Debug.Assert(_xmlSerializer == null, "outer name is not null for data contract extension only");
         name = _outerName;
         ns   = _outerNamespace;
     }
     else 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);
         }
     }
 }
        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);
            }
        }
Exemple #12
0
        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);
        }
Exemple #13
0
        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());
        }
        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;
                }
            }
        }
Exemple #15
0
        /// <summary>
        ///     first response performance critical
        /// </summary>
        /// <returns></returns>
        public override MetadataSet GetGeneratedMetadata()
        {
            ImporterController.TryDocRevImporting();

            int i = 0;
            // let the base build up metadata for the service contracts as these are static
            MetadataSet _MetadataSet = base.GetGeneratedMetadata();

            foreach (DirectoryInfo _DirectoryInfo in Directory
                     .EnumerateDirectories(FilesystemTemplateController.DirectoryPath)
                     .Select(path => new DirectoryInfo(path)))
            {
                // persist the datacontract xml schema for the datacontract to the user's temporary directory
                //TODO:combine this logic and Runtime's that calculates it's dll output location
                int key = Math.Abs(File.ReadAllText(
                                       RequestPaths.GetPhysicalApplicationPath(
                                           "doc",
                                           _DirectoryInfo.Name,
                                           Runtime.MYSCHEMA_XSD_FILE_NAME)).GetHashCode()
                                   ^ WindowsIdentity.GetCurrent().User.Value.GetHashCode()); // just incase the user changes due to an apppool change

                string tempDataContractXsdPath = string.Format("{0}\\{1}.xsd", Path.GetTempPath(), Base36.Encode(key));

                if (!File.Exists(tempDataContractXsdPath))
                {
                    // the datacontracts are the things that are dynamic & change according to what DocTypes are present
                    XsdDataContractExporter _XsdDataContractExporter = new XsdDataContractExporter();
                    Type DocType = Runtime.ActivateBaseDocType(_DirectoryInfo.Name, TemplateController.Instance.TopDocRev(_DirectoryInfo.Name));
                    _XsdDataContractExporter.Export(DocType);
                    // _XsdDataContractExporter.Schemas.CompilationSettings.EnableUpaCheck = true;
                    _XsdDataContractExporter.Schemas.Compile();

                    foreach (XmlSchema _XmlSchema in _XsdDataContractExporter.Schemas.Schemas(_XsdDataContractExporter.GetRootElementName(DocType).Namespace))
                    {
                        using (Stream _Stream = File.OpenWrite(tempDataContractXsdPath))
                        {
                            _MetadataSet.MetadataSections.Add(MetadataSection.CreateFromSchema(_XmlSchema));
                            _XmlSchema.Write(_Stream);
                            break;
                        }
                    }
                }

                using (Stream _Stream = File.OpenRead(tempDataContractXsdPath))
                    _MetadataSet.MetadataSections.Add(MetadataSection.CreateFromSchema(
                                                          XmlSchema.Read(_Stream, (s, o) =>
                    {
                        /*if (o != null && o.Exception != null) throw o.Exception;*/
                    })));
            }

            return(_MetadataSet);
        }
Exemple #16
0
        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);
            }
        }