Exemplo n.º 1
0
 private void ExportDataContract(MessagePartDescription md)
 {
     if (data_contract_importer == null)
     {
         data_contract_importer = md.DataContractImporter;
     }
     else if (md.DataContractImporter != null && data_contract_importer != md.DataContractImporter)
     {
         throw new Exception("INTERNAL ERROR: should not happen");
     }
     if (xml_serialization_importer == null)
     {
         xml_serialization_importer = md.XmlSerializationImporter;
     }
     else if (md.XmlSerializationImporter != null && xml_serialization_importer != md.XmlSerializationImporter)
     {
         throw new Exception("INTERNAL ERROR: should not happen");
     }
 }
Exemplo n.º 2
0
        public void ImportTest()
        {
            XsdDataContractImporter xsdi    = GetImporter();
            XmlSchemaElement        element = new XmlSchemaElement();

            //Assert.IsTrue (xsdi.CanImport (xss, element));
            Assert.AreEqual(new XmlQualifiedName("anyType", XmlSchema.Namespace), xsdi.Import(xss, element), "#i02");

            CodeCompileUnit ccu = xsdi.CodeCompileUnit;

            Assert.AreEqual(1, ccu.Namespaces.Count, "#i03");
            Assert.AreEqual("", ccu.Namespaces [0].Name, "#i04");

            Assert.AreEqual(1, ccu.Namespaces [0].Types.Count, "#i05");

            Dictionary <string, string> mbrs = new Dictionary <string, string> ();

            mbrs.Add("foo", "System.String");
            CheckDC(ccu.Namespaces [0].Types [0], "dc", mbrs, "#i06");
        }
Exemplo n.º 3
0
    static void ImportSchemas(XmlSchemaSet schemas)
    {
        Console.WriteLine("Now doing schema import.");
        // The following code demonstrates schema import with
        // a surrogate. The surrogate is used to indicate that
        // the Person class already exists and that there is no
        // need to generate a new class when importing the
        // PersonSurrogated data contract. If the surrogate
        // was not used, schema import would generate a
        // PersonSurrogated class, and the person field
        // of Employee would be imported as
        // PersonSurrogated and not Person.
        XsdDataContractImporter xsdimp = new XsdDataContractImporter();

        xsdimp.Options = new ImportOptions();
        xsdimp.Options.DataContractSurrogate = new LegacyPersonTypeSurrogate();
        xsdimp.Import(schemas);

        // Write out the imported schema to a C-Sharp file.
        // The code contains data contract types.
        FileStream fs4 = new FileStream("sample.cs", FileMode.Create);

        try
        {
            StreamWriter tw = new StreamWriter(fs4);
            Microsoft.CSharp.CSharpCodeProvider cdp = new Microsoft.CSharp.CSharpCodeProvider();
            cdp.GenerateCodeFromCompileUnit(xsdimp.CodeCompileUnit, tw, null);
            tw.Flush();
        }
        finally
        {
            fs4.Dispose();
        }


        Console.WriteLine("\t  To see the results of schema export and import,");
        Console.WriteLine(" see SAMPLE.XSD and SAMPLE.CS.");

        Console.WriteLine(" Press ENTER to terminate the sample.");
        Console.ReadLine();
    }
		public void ImportGivesAppropriateNamespaces ()
		{
			var ccu = new CodeCompileUnit ();
			var xdi = new XsdDataContractImporter (ccu);
			var xss = new XmlSchemaSet ();
			xss.Add (null, "Test/Resources/Schemas/schema1.xsd");
			xss.Add (null, "Test/Resources/Schemas/schema2.xsd");
			xss.Add (null, "Test/Resources/Schemas/schema3.xsd");
			xdi.Import (xss);
			var sw = new StringWriter ();
			bool t = false, te = false;
			foreach (CodeNamespace cns in ccu.Namespaces) {
				if (cns.Name == "tempuri.org")
					t = true;
				else if (cns.Name == "tempuri.org.ext")
					te = true;
				Assert.AreEqual ("GetSearchDataResponse", cns.Types [0].Name, "#1." + cns.Name);
			}
			Assert.IsTrue (t, "t");
			Assert.IsTrue (t, "te");
		}
Exemplo n.º 5
0
        public void Build_CodeGeneratorOptions_NamespaceMappings()
        {
            const string expectedMappingKey1 = "1";
            const string expectedMappingKey2 = "2";
            const string expectedNamespace1  = "Namespace1";
            const string expectedNamespace2  = "Namespace2";

            Dictionary <string, string> mappings = new Dictionary <string, string>
            {
                { expectedMappingKey1, expectedNamespace1 },
                { expectedMappingKey2, expectedNamespace2 }
            };
            CodeGeneratorOptions options = new CodeGeneratorOptions {
                NamespaceMappings = mappings
            };
            XsdDataContractImporter      importer   = PerformBuild(options);
            IDictionary <string, string> namespaces = importer.Options.Namespaces;

            Assert.That(namespaces, Has.Count.EqualTo(2));
            Assert.That(namespaces[expectedMappingKey1], Is.EqualTo(expectedNamespace1));
            Assert.That(namespaces[expectedMappingKey2], Is.EqualTo(expectedNamespace2));
        }
Exemplo n.º 6
0
        public void WithSurrogateBinding()
        {
            XsdDataContractExporter exporter = new XsdDataContractExporter();

            exporter.Options = new ExportOptions();
            exporter.Options.DataContractSurrogate = new SurrogateProvider(true);
            for (int i = 0; i < testTypes.Length; i++)
            {
                exporter.Export((Type)testTypes[i]);
            }

            XsdDataContractImporter importer = new XsdDataContractImporter();

            importer         = new XsdDataContractImporter();
            importer.Options = new ImportOptions();
            importer.Options.DataContractSurrogate = exporter.Options.DataContractSurrogate;
            importer.Options.ImportXmlType         = true;
            importer.Options.ReferencedTypes.Add(typeof(Circle));
            importer.Import(exporter.Schemas);

            string code = SchemaUtils.DumpCode(importer.CodeCompileUnit);

            _output.WriteLine(code);

            Assert.Contains(@"[assembly: System.Runtime.Serialization.ContractNamespaceAttribute(""http://special1.tempuri.org"", ClrNamespace=""special1.tempuri.org"")]", code);
            Assert.DoesNotContain(@"[assembly: System.Runtime.Serialization.ContractNamespaceAttribute("""", ClrNamespace="""")]", code);

            Assert.Contains(@"namespace special1.tempuri.org", code);
            Assert.Matches(@"\[System.Runtime.Serialization.DataContractAttribute\(Name=""CircleContainer"", Namespace=""http://special1.tempuri.org""\)\]\s*public partial class CircleContainer : object, System.Runtime.Serialization.IExtensibleDataObject", code);
            Assert.Contains(@"private System.Runtime.Serialization.Schema.Tests.DataContracts.SerializableCircle[] circlesField;", code);
            Assert.Contains(@"private System.Runtime.Serialization.Schema.Tests.DataContracts.SerializableCircle CircleField;", code);
            Assert.Matches(@"\[System.Runtime.Serialization.DataMemberAttribute\(\)\]\s*public System.Runtime.Serialization.Schema.Tests.DataContracts.SerializableCircle Circle", code);

            Assert.DoesNotContain(@"namespace System.Runtime.Serialization.Schema.Tests.DataContracts", code);
            Assert.DoesNotContain(@"class SerializableSquare", code);
            Assert.DoesNotContain(@"class SerializableNode", code);
            Assert.DoesNotContain(@"class XmlSerializerPerson", code);
        }
Exemplo n.º 7
0
        void AddStateForDataContractSerializerImport(WsdlImporter importer)
        {
            var xsdDataContractImporter =
                new XsdDataContractImporter(codeCompileUnit);

            xsdDataContractImporter.Options = new ImportOptions();
            xsdDataContractImporter.Options.ImportXmlType =
                (options.FormatMode ==
                 DynamicProxyFactoryOptions.FormatModeOptions.DataContractSerializer);

            xsdDataContractImporter.Options.CodeProvider = codeDomProvider;
            importer.State.Add(typeof(XsdDataContractImporter),
                               xsdDataContractImporter);

            foreach (var importExtension in importer.WsdlImportExtensions)
            {
                if (importExtension is DataContractSerializerMessageContractImporter dcConverter)
                {
                    dcConverter.Enabled = options.FormatMode ==
                                          DynamicProxyFactoryOptions.FormatModeOptions.XmlSerializer ? false : true;
                }
            }
        }
Exemplo n.º 8
0
        private void SyncUpCodeCompileUnit(Dictionary <object, object> state)
        {
            if (state == null)
            {
                return;
            }

            foreach (KeyValuePair <object, object> pair in state)
            {
                XsdDataContractImporter dcImporter = pair.Value as XsdDataContractImporter;
                if (dcImporter != null)
                {
                    this.codeCompileUnit = dcImporter.CodeCompileUnit;
                    return;
                }
                XmlSerializerImportOptions xmlImporter = pair.Value as XmlSerializerImportOptions;
                if (xmlImporter != null)
                {
                    this.codeCompileUnit = xmlImporter.CodeCompileUnit;
                    return;
                }
            }
        }
        //<snippet2>
        //<snippet3>
        static CodeCompileUnit Import(XmlSchemaSet schemas)
        {
            XsdDataContractImporter imp = new XsdDataContractImporter();

            // The EnableDataBinding option adds a RaisePropertyChanged method to
            // the generated code. The GenerateInternal causes code access to be
            // set to internal.
            ImportOptions iOptions = new ImportOptions();

            iOptions.EnableDataBinding = true;
            iOptions.GenerateInternal  = true;
            imp.Options = iOptions;

            if (imp.CanImport(schemas))
            {
                imp.Import(schemas);
                return(imp.CodeCompileUnit);
            }
            else
            {
                return(null);
            }
        }
        public void CanImportTest()
        {
            NewXmlSchemaSet();
            XsdDataContractImporter xsdi = GetImporter();

            Assert.IsFalse(xss.IsCompiled, "#ci01");

            Assert.IsTrue(xsdi.CanImport(xss, new XmlQualifiedName("dc", "http://schemas.datacontract.org/2004/07/")), "#ci02");
            Assert.IsTrue(xss.IsCompiled, "#ci03");

            Assert.IsFalse(xsdi.CanImport(xss, new XmlQualifiedName("Echo", "http://myns/echo")), "#ci04");
            Assert.IsTrue(xsdi.CanImport(xss, new XmlQualifiedName("int", "http://www.w3.org/2001/XMLSchema")), "#ci05");

            Assert.IsTrue(xsdi.CanImport(xss), "#ci06");

            Assert.IsTrue(xsdi.CanImport(xss,
                                         xss.GlobalElements [new XmlQualifiedName("dc", "http://schemas.datacontract.org/2004/07/")] as XmlSchemaElement),
                          "#ci07");

            Assert.IsTrue(xsdi.CanImport(xss,
                                         xss.GlobalElements [new XmlQualifiedName("Echo", "http://myns/echo")] as XmlSchemaElement),
                          "#ci08");
        }
Exemplo n.º 11
0
        public void ReferencedTypes(XmlSchemaSet schemas, XmlQualifiedName qname, Type[] referencedTypes, Type expectedExceptionType = null, string msg = null)
        {
            XsdDataContractImporter importer = SchemaUtils.CreateImporterWithDefaultOptions();

            for (int i = 0; i < referencedTypes.Length; i++)
            {
                importer.Options.ReferencedTypes.Add(referencedTypes[i]);
            }

            if (expectedExceptionType == null)
            {
                importer.Import(schemas, qname);
                _output.WriteLine(SchemaUtils.DumpCode(importer.CodeCompileUnit));
            }
            else
            {
                var ex = Assert.Throws(expectedExceptionType, () => importer.Import(schemas, qname));

                if (!string.IsNullOrEmpty(msg))
                {
                    Assert.StartsWith(msg, ex.Message);
                }
            }
        }
Exemplo n.º 12
0
        public void DefaultScenario()
        {
            XsdDataContractExporter exporter = new XsdDataContractExporter();

            exporter.Options = new ExportOptions();
            exporter.Options.DataContractSurrogate = new SurrogateProvider(false);
            for (int i = 0; i < testTypes.Length; i++)
            {
                exporter.Export((Type)testTypes[i]);
            }

            XsdDataContractImporter importer = new XsdDataContractImporter();

            importer.Options = new ImportOptions();
            importer.Options.DataContractSurrogate = exporter.Options.DataContractSurrogate;
            importer.Options.ImportXmlType         = true;
            importer.Import(exporter.Schemas);

            string code = SchemaUtils.DumpCode(importer.CodeCompileUnit);

            _output.WriteLine(code);

            Assert.Contains(@"[assembly: System.Runtime.Serialization.ContractNamespaceAttribute(""http://special1.tempuri.org"", ClrNamespace=""special1.tempuri.org"")]", code);
            Assert.Contains(@"[assembly: System.Runtime.Serialization.ContractNamespaceAttribute("""", ClrNamespace="""")]", code);

            Assert.Contains(@"namespace special1.tempuri.org", code);
            Assert.Matches(@"\[System.Runtime.Serialization.DataContractAttribute\(Name=""CircleContainer"", Namespace=""http://special1.tempuri.org""\)\]\s*public partial class CircleContainer : object, System.Runtime.Serialization.IExtensibleDataObject", code);
            Assert.Contains(@"private System.Runtime.Serialization.Schema.Tests.DataContracts.SerializableSquare[] circlesField;", code);
            Assert.Contains(@"private System.Runtime.Serialization.Schema.Tests.DataContracts.SerializableSquare CircleField;", code);
            Assert.Matches(@"\[System.Runtime.Serialization.DataMemberAttribute\(\)\]\s*public System.Runtime.Serialization.Schema.Tests.DataContracts.SerializableSquare Circle", code);
            Assert.Contains(@"public partial class SerializableSquare : object, System.Runtime.Serialization.IExtensibleDataObject", code);

            Assert.Contains(@"namespace System.Runtime.Serialization.Schema.Tests.DataContracts", code);
            Assert.Matches(@"\[System.Runtime.Serialization.DataContractAttribute\(Name\s*=\s*""SerializableNode"", Namespace\s*=\s*""http://schemas.datacontract.org/2004/07/System.Runtime.Serialization.Schema.Tests""\s*\+\s*"".DataContracts""\)\]\s*public partial class SerializableNode : object, System.Runtime.Serialization.IExtensibleDataObject", code);
            Assert.Matches(@"\[System.Xml.Serialization.XmlSchemaProviderAttribute\(""ExportSchema""\)\]\s*\[System.Xml.Serialization.XmlRootAttribute\(ElementName\s*=\s*""XmlSerializerPersonElement"", Namespace\s*=\s*""""\)\]\s*public partial class XmlSerializerPerson : object, System.Xml.Serialization.IXmlSerializable", code);
        }
        public void ImportTestNullSchemas()
        {
            XsdDataContractImporter xsdi = GetImporter();

            xsdi.Import(null);
        }
        public void CanImportNullTest3()
        {
            XsdDataContractImporter xsdi = GetImporter();

            xsdi.CanImport(xss, (XmlSchemaElement)null);
        }
        public void CanImportNullTest2()
        {
            XsdDataContractImporter xsdi = GetImporter();

            xsdi.CanImport(xss, (XmlQualifiedName)null);
        }
        public void CanImportNullTest1()
        {
            XsdDataContractImporter xsdi = GetImporter();

            xsdi.CanImport(null);
        }
        public void GetCodeTypeReferenceTest()
        {
            XsdDataContractImporter xsdi = GetImporter();

            xsdi.GetCodeTypeReference(new XmlQualifiedName("dc", "http://schemas.datacontract.org/2004/07/"));
        }
Exemplo n.º 18
0
        }     //end subtraction webservice Invoke function..

        private void calculateMultiplication(Uri multiplicationServiceURI, Multiplication.MathData[] cmplxTyp_ip)
        {
            try
            {
                Uri mexAddress = multiplicationServiceURI;
                MetadataExchangeClientMode mexMode = MetadataExchangeClientMode.HttpGet;
                string contractName   = "IMultiplication";
                string operationName  = "GetDataUsingDataContract";
                string operationName1 = "MultiplyArray";

                Multiplication.CompositeType ip = new Multiplication.CompositeType()
                {
                    BoolValue   = true,
                    StringValue = "---test string--"
                };

                object[] operationParameters  = new object[] { ip };
                object[] operationParameters1 = new object[] { cmplxTyp_ip };

                MetadataExchangeClient mexClient = new MetadataExchangeClient(mexAddress, mexMode);
                mexClient.ResolveMetadataReferences = true;
                MetadataSet metaSet = mexClient.GetMetadata();

                WsdlImporter importer = new WsdlImporter(metaSet);
                //BEGIN INSERT
                XsdDataContractImporter xsd = new XsdDataContractImporter();
                xsd.Options = new ImportOptions();
                xsd.Options.ImportXmlType        = true;
                xsd.Options.GenerateSerializable = true;
                //xsd.Options.ReferencedTypes.Add(typeof(KeyValuePair<string, string>));
                //xsd.Options.ReferencedTypes.Add(typeof(System.Collections.Generic.List<KeyValuePair<string, string>>));

                xsd.Options.ReferencedTypes.Add(typeof(Multiplication.CompositeType));
                xsd.Options.ReferencedTypes.Add(typeof(Multiplication.MathData));
                xsd.Options.ReferencedTypes.Add(typeof(System.Collections.Generic.List <Multiplication.MathData>));


                importer.State.Add(typeof(XsdDataContractImporter), xsd);
                //END INSERT


                Collection <ContractDescription> contracts    = importer.ImportAllContracts();
                ServiceEndpointCollection        allEndpoints = importer.ImportAllEndpoints();

                ServiceContractGenerator generator = new ServiceContractGenerator();
                var endpointsForContracts          = new Dictionary <string, IEnumerable <ServiceEndpoint> >();

                foreach (ContractDescription contract in contracts)
                {
                    generator.GenerateServiceContractType(contract);
                    endpointsForContracts[contract.Name] = allEndpoints.Where(
                        se => se.Contract.Name == contract.Name).ToList();
                }

                if (generator.Errors.Count != 0)
                {
                    throw new Exception("There were errors during code compilation.");
                }

                CodeGeneratorOptions options = new CodeGeneratorOptions();
                options.BracingStyle = "C";
                CodeDomProvider codeDomProvider = CodeDomProvider.CreateProvider("C#");

                CompilerParameters compilerParameters = new CompilerParameters(
                    new string[] {
                    "System.dll", "System.ServiceModel.dll",
                    "System.Runtime.Serialization.dll"
                });
                compilerParameters.GenerateInMemory = true;

                CompilerResults results = codeDomProvider.CompileAssemblyFromDom(
                    compilerParameters, generator.TargetCompileUnit);

                if (results.Errors.Count > 0)
                {
                    throw new Exception("There were errors during generated code compilation");
                }
                else
                {
                    Type clientProxyType = results.CompiledAssembly.GetTypes().First(
                        t => t.IsClass &&
                        t.GetInterface(contractName) != null &&
                        t.GetInterface(typeof(ICommunicationObject).Name) != null);

                    ServiceEndpoint se = endpointsForContracts[contractName].First();

                    object instance = results.CompiledAssembly.CreateInstance(
                        clientProxyType.Name,
                        false,
                        System.Reflection.BindingFlags.CreateInstance,
                        null,
                        new object[] { se.Binding, se.Address },
                        CultureInfo.CurrentCulture, null);


                    var methodInfo  = instance.GetType().GetMethod(operationName);
                    var methodInfo1 = instance.GetType().GetMethod(operationName1);

                    object  retVal  = methodInfo.Invoke(instance, BindingFlags.InvokeMethod, null, operationParameters, null);
                    dynamic retVal1 = methodInfo1.Invoke(instance, BindingFlags.InvokeMethod, null, operationParameters1, null);
                    Console.WriteLine(retVal.ToString());

                    for (int x = 0; x < cmplxTyp_ip.Length; x++)
                    {
                        Console.WriteLine(" --Multiplication output RECORD {0 } ----", x);
                        Console.WriteLine(" FArg1 *farg2 : {0 } ", retVal1[x].FRsltArg);
                        Console.WriteLine(" strFArg1 * arg2 : {0 }", retVal1[x].StrConcatRslt);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            } //end of mex binding try block
        }     //end of MULTIPLICATION webservice Invoke function...
        public void ImportTestNullCollection()
        {
            XsdDataContractImporter xsdi = GetImporter();

            xsdi.Import(new XmlSchemaSet(), (ICollection <XmlQualifiedName>)null);
        }
        public void ImportTestNullTypeName()
        {
            XsdDataContractImporter xsdi = GetImporter();

            xsdi.Import(new XmlSchemaSet(), (XmlQualifiedName)null);
        }
        public void ImportTestNullSchemas2()
        {
            XsdDataContractImporter xsdi = GetImporter();

            xsdi.Import(null, new XmlQualifiedName("foo"));
        }
 public void ImportContract(XsdDataContractImporter importer)
 {
 }
        public void ImportTestNullSchemas3()
        {
            XsdDataContractImporter xsdi = GetImporter();

            xsdi.Import(null, new List <XmlQualifiedName> ());
        }
Exemplo n.º 24
0
        static void Main()
        {
            Inventory store1 = new Inventory();

            store1.pencils = 5;
            store1.pens    = 10;
            store1.paper   = 15;
            DataContractSerializer surrogateDcs =
                new DataContractSerializer(typeof(Inventory), null, int.MaxValue, false, false, new InventoryTypeSurrogate());

            // Plug in the surrogate in order to use the serializer.
            Console.WriteLine("Plug in a surrogate for the Inventory class\n");
            StringWriter sw2 = new StringWriter();
            XmlWriter    xw2 = XmlWriter.Create(sw2);

            try
            {
                surrogateDcs.WriteObject(xw2, store1);
            }
            catch (InvalidDataContractException)
            {
                Console.WriteLine(" We should never get here");
            }
            xw2.Flush();
            sw2.Flush();
            Console.Write(sw2.ToString());
            Console.WriteLine("\n\n Serialization succeeded. Now doing deserialization...\n");

            StringReader tr       = new StringReader(sw2.ToString());
            XmlReader    xr       = XmlReader.Create(tr);
            Inventory    newstore = (Inventory)surrogateDcs.ReadObject(xr);

            Console.Write("Deserialized Inventory data: \nPens:" + newstore.pens + "\nPencils: " + newstore.pencils + "\nPaper: " + newstore.paper);

            Console.WriteLine("\n\n Deserialization succeeded. Now doing schema export/import...\n");

            //The following code demonstrates schema export with a surrogate.
            //The surrogate indicates how to export the non-DataContract Inventory type.
            //Without the surrogate, schema export would fail.
            XsdDataContractExporter xsdexp = new XsdDataContractExporter();

            xsdexp.Options = new ExportOptions();
            xsdexp.Options.DataContractSurrogate = new InventoryTypeSurrogate();
            try
            {
                xsdexp.Export(typeof(Inventory));
            }
            catch (Exception) { }

            //Write out exported schema to a file
            using (FileStream fs = new FileStream("sample.xsd", FileMode.Create))
            {
                foreach (XmlSchema sch in xsdexp.Schemas.Schemas())
                {
                    sch.Write(fs);
                }
            }

            //The following code demonstrates schema import with a surrogate.
            //The surrogate is used to indicate that the Inventory class already exists
            //and that there is no need to generate a new class when importing the
            //"InventorySurrogated" data contract.

            XsdDataContractImporter xsdimp = new XsdDataContractImporter();

            xsdimp.Options = new ImportOptions();
            xsdimp.Options.DataContractSurrogate = new InventoryTypeSurrogate();
            xsdimp.Import(xsdexp.Schemas);

            //Write out the imported schema to a C-Sharp file
            using (FileStream fs = new FileStream("sample.cs", FileMode.Create))
            {
                TextWriter      tw  = new StreamWriter(fs);
                CodeDomProvider cdp = new Microsoft.CSharp.CSharpCodeProvider();
                cdp.GenerateCodeFromCompileUnit(xsdimp.CodeCompileUnit, tw, null);
                tw.Flush();
            }

            Console.WriteLine("\n\n To see the results of schema export and import,");
            Console.WriteLine(" see SAMPLE.XSD and SAMPLE.CS.\n");

            Console.WriteLine(" Press ENTER to terminate the sample.\n");
            Console.ReadLine();
        }
        public void ImportTestNullElement()
        {
            XsdDataContractImporter xsdi = GetImporter();

            xsdi.Import(new XmlSchemaSet(), (XmlSchemaElement)null);
        }
Exemplo n.º 26
0
        public void GenerateProxyClass()
        {
            EndpointAddress metadataAddress = new EndpointAddress("http://localhost/Sofka.Automation.Dummy.Wcf/Loan.svc?wsdl");
            //string  = "http://localhost/Sofka.Automation.Dummy.Wcf/Loan.svc";
            string outputFile = @"d:\dev\Sofka\Test\TempFiles";
            MetadataExchangeClient mexClient = new MetadataExchangeClient(metadataAddress);

            mexClient.ResolveMetadataReferences = false;
            MetadataSet metaDocs = mexClient.GetMetadata();

            WsdlImporter             importer  = new WsdlImporter(metaDocs);
            ServiceContractGenerator generator = new ServiceContractGenerator();

            // Add our custom DCAnnotationSurrogate
            // to write XSD annotations into the comments.
            object dataContractImporter;
            XsdDataContractImporter xsdDCImporter;

            if (!importer.State.TryGetValue(typeof(XsdDataContractImporter), out dataContractImporter))
            {
                Console.WriteLine("Couldn't find the XsdDataContractImporter! Adding custom importer.");
                xsdDCImporter         = new XsdDataContractImporter();
                xsdDCImporter.Options = new ImportOptions();
                importer.State.Add(typeof(XsdDataContractImporter), xsdDCImporter);
            }
            else
            {
                xsdDCImporter = (XsdDataContractImporter)dataContractImporter;
                if (xsdDCImporter.Options == null)
                {
                    Console.WriteLine("There were no ImportOptions on the importer.");
                    xsdDCImporter.Options = new ImportOptions();
                }
            }
            //xsdDCImporter.Options.DataContractSurrogate = new DCAnnotationSurrogate();

            // Uncomment the following code if you are going to do your work programmatically rather than add
            // the WsdlDocumentationImporters through a configuration file.

            /*
             * // The following code inserts a custom WsdlImporter without removing the other
             * // importers already in the collection.
             * System.Collections.Generic.IEnumerable<IWsdlImportExtension> exts = importer.WsdlImportExtensions;
             * System.Collections.Generic.List<IWsdlImportExtension> newExts
             * = new System.Collections.Generic.List<IWsdlImportExtension>();
             * foreach (IWsdlImportExtension ext in exts)
             * {
             * Console.WriteLine("Default WSDL import extensions: {0}", ext.GetType().Name);
             * newExts.Add(ext);
             * }
             * newExts.Add(new WsdlDocumentationImporter());
             * System.Collections.Generic.IEnumerable<IPolicyImportExtension> polExts = importer.PolicyImportExtensions;
             * importer = new WsdlImporter(metaDocs, polExts, newExts);
             */

            System.Collections.ObjectModel.Collection <ContractDescription> contracts
                = importer.ImportAllContracts();
            importer.ImportAllEndpoints();
            foreach (ContractDescription contract in contracts)
            {
                generator.GenerateServiceContractType(contract);
            }
            if (generator.Errors.Count != 0)
            {
                throw new Exception("There were errors during code compilation.");
            }

            // Write the code dom
            System.CodeDom.Compiler.CodeGeneratorOptions options
                = new System.CodeDom.Compiler.CodeGeneratorOptions();
            options.BracingStyle = "C";
            System.CodeDom.Compiler.CodeDomProvider codeDomProvider
                = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("C#");
            System.CodeDom.Compiler.IndentedTextWriter textWriter
                = new System.CodeDom.Compiler.IndentedTextWriter(new System.IO.StreamWriter(outputFile));
            codeDomProvider.GenerateCodeFromCompileUnit(
                generator.TargetCompileUnit, textWriter, options
                );
            textWriter.Close();
        }
        public void ImportMessageEcho()
        {
            XsdDataContractImporter xsdi = GetImporter();

            xsdi.Import(xss, new XmlQualifiedName("Echo", "http://myns/echo"));
        }
Exemplo n.º 28
0
 void IXsdImportExtension.ImportContract(XsdDataContractImporter importer)
 {
     _xsdDataContractImporter = importer;
 }
Exemplo n.º 29
0
        private static void GenerateCSCodeForServiceThread()
        {
            try
            {
                string outputFile = "WSDL-Output";

                MetadataExchangeClient mexClient = new MetadataExchangeClient(server.metaAddress, MetadataExchangeClientMode.HttpGet);
                mexClient.ResolveMetadataReferences = true;
                mexClient.OperationTimeout          = TimeSpan.FromSeconds(60);
                mexClient.MaximumResolvedReferences = 1000;

                MetadataSet metaDocs = mexClient.GetMetadata();

                WsdlImporter             importer  = new WsdlImporter(metaDocs);
                ServiceContractGenerator generator = new ServiceContractGenerator();

                // Add our custom DCAnnotationSurrogate
                // to write XSD annotations into the comments.
                object dataContractImporter;

                XsdDataContractImporter xsdDCImporter;
                if (!importer.State.TryGetValue(typeof(XsdDataContractImporter), out dataContractImporter))
                {
                    Console.WriteLine("Couldn't find the XsdDataContractImporter! Adding custom importer.");
                    xsdDCImporter         = new XsdDataContractImporter();
                    xsdDCImporter.Options = new ImportOptions();
                    importer.State.Add(typeof(XsdDataContractImporter), xsdDCImporter);
                }
                else
                {
                    xsdDCImporter = (XsdDataContractImporter)dataContractImporter;
                    if (xsdDCImporter.Options == null)
                    {
                        Console.WriteLine("There were no ImportOptions on the importer.");
                        xsdDCImporter.Options = new ImportOptions();
                    }
                }
                ////TODO: This is a customer implementation using the IDataContractSurrogate interface
                // xsdDCImporter.Options.DataContractSurrogate = new DCAnnotationSurrogate();

                // Uncomment the following code if you are going to do your work programmatically rather than add
                // the WsdlDocumentationImporters through a configuration file.

                /*
                 * // The following code inserts a custom WsdlImporter without removing the other
                 * // importers already in the collection.
                 * System.Collections.Generic.IEnumerable<IWsdlImportExtension> exts = importer.WsdlImportExtensions;
                 * System.Collections.Generic.List<IWsdlImportExtension> newExts
                 * = new System.Collections.Generic.List<IWsdlImportExtension>();
                 * foreach (IWsdlImportExtension ext in exts)
                 * {
                 * Console.WriteLine("Default WSDL import extensions: {0}", ext.GetType().Name);
                 * newExts.Add(ext);
                 * }
                 * newExts.Add(new WsdlDocumentationImporter());
                 * System.Collections.Generic.IEnumerable<IPolicyImportExtension> polExts = importer.PolicyImportExtensions;
                 * importer = new WsdlImporter(metaDocs, polExts, newExts);
                 */

                System.Collections.ObjectModel.Collection <ContractDescription> contracts = importer.ImportAllContracts();

                importer.ImportAllEndpoints();

                foreach (ContractDescription contract in contracts)
                {
                    generator.GenerateServiceContractType(contract);
                }

                if (generator.Errors.Count != 0)
                {
                    throw new Exception("There were errors during code compilation.");
                }

                // Write the code dom
                System.CodeDom.Compiler.CodeGeneratorOptions options = new System.CodeDom.Compiler.CodeGeneratorOptions();
                options.BracingStyle = "C";
                System.CodeDom.Compiler.CodeDomProvider    codeDomProvider = System.CodeDom.Compiler.CodeDomProvider.CreateProvider("C#");
                System.CodeDom.Compiler.IndentedTextWriter textWriter      = new System.CodeDom.Compiler.IndentedTextWriter(new System.IO.StreamWriter(outputFile));

                codeDomProvider.GenerateCodeFromCompileUnit(generator.TargetCompileUnit, textWriter, options);

                textWriter.Close();
            }
            catch (FaultException fx)
            {
                MessageBox.Show(fx.Message + " > " + fx.Reason + " > " + fx.Action + " > " + fx.Data + " > " + fx.Code + " > " + fx.InnerException);
            }
            catch (TimeoutException tx)
            {
                MessageBox.Show(tx.Message + " > " + tx.Data + " > " + tx.InnerException);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Exemplo n.º 30
0
 void IWsdlImportExtension.ImportContract(WsdlImporter importer, WsdlContractConversionContext context)
 {
     _xsdDataContractImporter = importer.Get <XsdDataContractImporter>();
     context.Contract.ContractBehaviors.Add(this);
 }