void IWsdlImportExtension.ImportContract (WsdlImporter importer,
			WsdlContractConversionContext context)
		{
			if (!enabled)
				return;

			if (importer == null)
				throw new ArgumentNullException ("importer");
			if (context == null)
				throw new ArgumentNullException ("context");
			if (this.importer != null || this.context != null)
				throw new SystemException ("INTERNAL ERROR: unexpected recursion of ImportContract method call");

			dc_importer = new XsdDataContractImporter ();
			schema_set_in_use = new XmlSchemaSet ();
			schema_set_in_use.Add (importer.XmlSchemas);
			foreach (WSDL wsdl in importer.WsdlDocuments)
				foreach (XmlSchema xs in wsdl.Types.Schemas)
					schema_set_in_use.Add (xs);

			// commenting out this import operation, but might be required (I guess not).
			//dc_importer.Import (schema_set_in_use);
			schema_set_in_use.Compile ();

			this.importer = importer;
			this.context = context;
			try {
				DoImportContract ();
			} finally {
				this.importer = null;
				this.context = null;
			}
		}
		void IWsdlImportExtension.ImportContract (WsdlImporter importer,
			WsdlContractConversionContext context)
		{
			if (!enabled)
				return;

			if (importer == null)
				throw new ArgumentNullException ("importer");
			if (context == null)
				throw new ArgumentNullException ("context");
			if (this.importer != null || this.context != null)
				throw new SystemException ("INTERNAL ERROR: unexpected recursion of ImportContract method call");

#if USE_DATA_CONTRACT_IMPORTER
			dc_importer = new XsdDataContractImporter ();
			schema_set_in_use = new XmlSchemaSet ();
			schema_set_in_use.Add (importer.XmlSchemas);
			foreach (WSDL wsdl in importer.WsdlDocuments)
				foreach (XmlSchema xs in wsdl.Types.Schemas)
					schema_set_in_use.Add (xs);
			dc_importer.Import (schema_set_in_use);
#endif

			this.importer = importer;
			this.context = context;
			try {
				DoImportContract ();
			} finally {
				this.importer = null;
				this.context = null;
			}
		}
Exemple #3
0
 internal static DcNS.XsdDataContractImporter CreateDCImporter(CommandProcessorOptions options, CodeCompileUnit codeCompileUnit)
 {
     DcNS.XsdDataContractImporter importer  = new DcNS.XsdDataContractImporter(codeCompileUnit);
     DcNS.ImportOptions           dcOptions = CreateDCImportOptions(options);
     importer.Options = dcOptions;
     return(importer);
 }
Exemple #4
0
        static void Generate(string url, TextWriter writer)
        {
            var cr = new ContractReference();
            cr.Url = url;

            var protocol = new DiscoveryClientProtocol();

            var wc = new WebClient();
            using (var stream = wc.OpenRead(cr.Url))
                protocol.Documents.Add(cr.Url, cr.ReadDocument(stream));

            var mset = ToMetadataSet(protocol);

            var importer = new WsdlImporter(mset);
            var xsdImporter = new XsdDataContractImporter();
            var options = new ImportOptions();
            options.ReferencedCollectionTypes.Add(typeof(LinkedList<>));
            xsdImporter.Options = options;
            importer.State.Add(typeof(XsdDataContractImporter), xsdImporter);

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

            CodeCompileUnit ccu = new CodeCompileUnit();
            CodeNamespace cns = new CodeNamespace("TestNamespace");
            ccu.Namespaces.Add(cns);

            var generator = new ServiceContractGenerator(ccu);

            foreach (var cd in contracts)
                generator.GenerateServiceContractType(cd);

            var provider = new CSharpCodeProvider();
            provider.GenerateCodeFromCompileUnit(ccu, writer, null);
        }
        protected override CodeCompileUnit GenerateCode(EndPointSetting wsdl)
        {
            if (wsdl == null || string.IsNullOrEmpty(wsdl.Uri))
                throw new ApplicationException("WSDL Uri in endpoint section of the configuration is empty.");

            var wsdlContent = TryGetContent(wsdl.Uri);
            if (string.IsNullOrEmpty(wsdlContent))
                throw new ApplicationException("Could not get content from WSDL at " + wsdl.Uri);

            var codeCompileUnit = new CodeCompileUnit();

            try
            {
                var importer = CreateImporter(wsdl);
                var generator = new ServiceContractGenerator(codeCompileUnit);
                var ns = ProxyGeneratorSettings.Options.Services.Namespace;

                generator.Options = ServiceContractGenerationOptions.AsynchronousMethods |
                                    ServiceContractGenerationOptions.ChannelInterface |
                                    ServiceContractGenerationOptions.ClientClass |
                                    ServiceContractGenerationOptions.EventBasedAsynchronousMethods;

                // Data contract options
                importer.State.Remove(typeof(XsdDataContractExporter));
                var contractImporter = new XsdDataContractImporter();
                contractImporter.Options = new ImportOptions { EnableDataBinding = true };
                contractImporter.Options.Namespaces.Add("*", ns);
                importer.State.Add(typeof(XsdDataContractImporter), contractImporter);

                var contracts = importer.ImportAllContracts();
                var endpoints = importer.ImportAllEndpoints();

                var codeNamespace = new CodeNamespace(ns);
                codeCompileUnit.Namespaces.Add(codeNamespace);

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

                if(generator.Errors.HasWarnings())
                {
                    Logger.WarnFormat("There was warnings when importing WSDL file at {0}. Warning message is: {1}.", wsdl.Uri, generator.Errors.GetWarnings());
                }

                // Call SL fixups
                var slfix = new WcfSilverlightCodeGenerationExtension();
                slfix.ClientGenerated(generator);
            }
            catch (Exception ex)
            {
                string message = "The wsdl with path:" + wsdl.Uri + " could not be processed.Error during the CodeCompileUnit generation.";
                throw new ApplicationException(message, ex);
            }

            return codeCompileUnit;
        }
		public void CtorTest ()
		{
			XsdDataContractImporter xi = new XsdDataContractImporter ();
			Assert.IsNotNull (xi.CodeCompileUnit, "#c01");

			xi = new XsdDataContractImporter (null);
			Assert.IsNotNull (xi.CodeCompileUnit, "#c02");

			xi = new XsdDataContractImporter (new CodeCompileUnit ());
		}
Exemple #7
0
 private static void AddStateForDataContractSerializerImport(CommandProcessorOptions options, WsdlImporter importer, CodeCompileUnit codeCompileUnit)
 {
     DcNS.XsdDataContractImporter xsdDataContractImporter = CreateDCImporter(options, codeCompileUnit);
     importer.State.Add(typeof(DcNS.XsdDataContractImporter), xsdDataContractImporter);
     if (!importer.State.ContainsKey(typeof(WrappedOptions)))
     {
         importer.State.Add(typeof(WrappedOptions), new WrappedOptions {
             WrappedFlag = options.Wrapped == true
         });
     }
 }
 public void TestRemotingTypeConversions()
 {
     XsdDataContractExporter x = new XsdDataContractExporter();
     XsdDataContractImporter i = new XsdDataContractImporter();
     Type[] ta = new Type[]
                     {
                         typeof(int), typeof(string),
                         typeof(DateTime), typeof(float),
                         typeof(TimeSpan), typeof(Decimal),
                         typeof(bool), typeof(char),
                         typeof(short), typeof(Int16), typeof(long)
                     };
     foreach (var t in ta)
     {
         Debug.WriteLine(".NET: " + t.Name);
         var y = x.GetSchemaTypeName(t);
         Debug.WriteLine(string.Format("XSD: {0} {1}", y.Namespace, y.Name));
         var cr = i.GetCodeTypeReference(y);
         Debug.WriteLine(".NET2 :" + cr.BaseType);
     }
 }
Exemple #9
0
		public static CodeCompileUnit Import (MetadataSet metadata, ImportOptions options)
		{
			var importer = new WsdlImporter (metadata);
			var xsdImporter = new XsdDataContractImporter ();
			xsdImporter.Options = options;
			importer.State.Add (typeof(XsdDataContractImporter), xsdImporter);
			
			var contracts = importer.ImportAllContracts ();
			
			CodeCompileUnit ccu = new CodeCompileUnit ();
			var generator = new ServiceContractGenerator (ccu);

			if (contracts.Count != 1)
				throw new InvalidOperationException (string.Format (
					"Metadata import failed: found {0} contracts.", contracts.Count));
			
			var contract = contracts.First ();
			generator.GenerateServiceContractType (contract);
			
			return ccu;
		}
 private WsdlImporter CreateImporterFromMetadata(MetadataSet metaDocs)
 {
     var importer = new WsdlImporter(metaDocs);
     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 { 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();
         }
     }
     return importer;
 }
		CodeCompileUnit DoImport (params string [] schemaFiles)
		{
			var ccu = new CodeCompileUnit ();
			var xdi = new XsdDataContractImporter (ccu);
			var xss = new XmlSchemaSet ();
			foreach (var schemaFile in schemaFiles)
				xss.Add (null, schemaFile);
			xdi.Import (xss);

			return ccu;
		}
        void AddStateForDataContractSerializerImport(WsdlImporter importer)
        {
            XsdDataContractImporter xsdDataContractImporter =
                new XsdDataContractImporter(this.codeCompileUnit);
            xsdDataContractImporter.Options = new ImportOptions();
            xsdDataContractImporter.Options.ImportXmlType =
                (this.options.FormatMode ==
                    DynamicProxyFactoryOptions.FormatModeOptions.DataContractSerializer);

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

            foreach (IWsdlImportExtension importExtension in importer.WsdlImportExtensions)
            {
                DataContractSerializerMessageContractImporter dcConverter =
                    importExtension as DataContractSerializerMessageContractImporter;

                if (dcConverter != null)
                {
                    if (this.options.FormatMode ==
                        DynamicProxyFactoryOptions.FormatModeOptions.XmlSerializer)
                        dcConverter.Enabled = false;
                    else
                        dcConverter.Enabled = true;
                }

            }
        }
		protected override void Init (WsdlImporter importer)
		{
			if (dc_importer == null)
				dc_importer = importer.GetState<XsdDataContractImporter> ();
		}
		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");
		}
		CodeCompileUnit DoImport (bool xmlType, params string [] schemaFiles)
		{
			var ccu = new CodeCompileUnit ();
			var xdi = new XsdDataContractImporter (ccu);
			if (xmlType)
				xdi.Options = new ImportOptions () { ImportXmlType = true };
			var xss = new XmlSchemaSet ();
			foreach (var schemaFile in schemaFiles)
				xss.Add (null, schemaFile);
			xdi.Import (xss);

			return ccu;
		}
        private static void AddStateForDataContractSerializerImport(WsdlImporter importer, MetadataImporterSerializerFormatMode formatMode, CodeCompileUnit codeCompileUnit, CodeDomProvider codeDomProvider)
        {
            XsdDataContractImporter xsdDataContractImporter = new XsdDataContractImporter(codeCompileUnit);
            xsdDataContractImporter.Options = CreateDataContractImportOptions(formatMode, codeDomProvider);
            importer.State.Add(typeof(XsdDataContractImporter), xsdDataContractImporter);

            for (int i = 0; i < importer.WsdlImportExtensions.Count; i++)
            {
                IWsdlImportExtension importExtension = importer.WsdlImportExtensions[i];
                DataContractSerializerMessageContractImporter dataContractSerializerMessageContractImporter = importExtension as DataContractSerializerMessageContractImporter;

                if (dataContractSerializerMessageContractImporter != null)
                {
                    dataContractSerializerMessageContractImporter.Enabled = formatMode != MetadataImporterSerializerFormatMode.XmlSerializer;
                }
            }
        }
		private void ExportDataContract (MessagePartDescription md)
		{
#if USE_DATA_CONTRACT_IMPORTER
			if (xsd_data_importer == null)
				xsd_data_importer = md.Importer;
#else
			var mapping = md.XmlTypeMapping;

			if (mapping == null)
				return;

			QName qname = new QName (mapping.TypeName, mapping.Namespace);
			if (imported_names.ContainsKey (qname))
				return;

			CodeNamespace cns = new CodeNamespace ();

			XmlCodeExporter xce = new XmlCodeExporter (cns);
			xce.ExportTypeMapping (mapping);

			List <CodeTypeDeclaration> to_remove = new List <CodeTypeDeclaration> ();
			
			//Process the types just generated
			//FIXME: Iterate and assign the types to correct namespaces
			//At the end, add all those namespaces to the ccu
			foreach (CodeTypeDeclaration type in cns.Types) {
				string ns = GetXmlNamespace (type);
				if (ns == null)
					//FIXME: do what here?
					continue;

				QName type_name = new QName (type.Name, ns);
				if (imported_names.ContainsKey (type_name)) {
					//Type got reemitted, so remove it!
					to_remove.Add (type);
					continue;
				}
				if (ns == ms_arrays_ns) {
					//Do not emit arrays as an independent type.
					to_remove.Add (type);
					continue;
				}

				imported_names [type_name] = type_name;

				type.Comments.Clear ();
				//Custom Attributes
				type.CustomAttributes.Clear ();

				if (type.IsEnum)
					continue;
	
				type.CustomAttributes.Add (
					new CodeAttributeDeclaration (
						new CodeTypeReference ("System.CodeDom.Compiler.GeneratedCodeAttribute"),
						new CodeAttributeArgument (new CodePrimitiveExpression ("System.Runtime.Serialization")),
						new CodeAttributeArgument (new CodePrimitiveExpression ("3.0.0.0"))));
			
				type.CustomAttributes.Add (
					new CodeAttributeDeclaration (
						new CodeTypeReference ("System.Runtime.Serialization.DataContractAttribute")));

				//BaseType and interface
				type.BaseTypes.Add (new CodeTypeReference (typeof (object)));
				type.BaseTypes.Add (new CodeTypeReference ("System.Runtime.Serialization.IExtensibleDataObject"));

				foreach (CodeTypeMember mbr in type.Members) {
					CodeMemberProperty p = mbr as CodeMemberProperty;
					if (p == null)
						continue;

					if ((p.Attributes & MemberAttributes.Public) == MemberAttributes.Public) {
						//FIXME: Clear all attributes or only XmlElementAttribute?
						p.CustomAttributes.Clear ();
						p.CustomAttributes.Add (new CodeAttributeDeclaration (
							new CodeTypeReference ("System.Runtime.Serialization.DataMemberAttribute")));

						p.Comments.Clear ();
					}
				}

				//Fields
				CodeMemberField field = new CodeMemberField (
					new CodeTypeReference ("System.Runtime.Serialization.ExtensionDataObject"),
					"extensionDataField");
				field.Attributes = MemberAttributes.Private | MemberAttributes.Final;
				type.Members.Add (field);

				//Property 
				CodeMemberProperty prop = new CodeMemberProperty ();
				prop.Type = new CodeTypeReference ("System.Runtime.Serialization.ExtensionDataObject");
				prop.Name = "ExtensionData";
				prop.Attributes = MemberAttributes.Public | MemberAttributes.Final;

				//Get
				prop.GetStatements.Add (new CodeMethodReturnStatement (
					new CodeFieldReferenceExpression (
					new CodeThisReferenceExpression (),
					"extensionDataField")));

				//Set
				prop.SetStatements.Add (new CodeAssignStatement (
					new CodeFieldReferenceExpression (
					new CodeThisReferenceExpression (),
					"extensionDataField"),
					new CodePropertySetValueReferenceExpression ()));

				type.Members.Add (prop);
			}

			foreach (CodeTypeDeclaration type in to_remove)
				cns.Types.Remove (type);

			ccu.Namespaces.Add (cns);
#endif
		}
		public void ImportSkipArrayOfPrimitives ()
		{
			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");
			xdi.Import (xss);
			var sw = new StringWriter ();
			new CSharpCodeProvider ().GenerateCodeFromCompileUnit (ccu, sw, null);
			Assert.IsTrue (sw.ToString ().IndexOf ("ArrayOfint") < 0, "#1");
		}
		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");
		}
		void ConfigureImporter (WsdlImporter importer)
		{
			var xsdImporter = new XsdDataContractImporter ();
			var options = new ImportOptions ();

			var listMapping = refGroup.ClientOptions.CollectionMappings.FirstOrDefault (
				m => m.Category == "List");
			if (listMapping != null) {
				var listType = Dialogs.WCFConfigWidget.GetType (listMapping.TypeName);
				if (listType != null)
					options.ReferencedCollectionTypes.Add (listType);
			}

			var dictMapping = refGroup.ClientOptions.CollectionMappings.FirstOrDefault (
				m => m.Category == "Dictionary");
			if (dictMapping != null) {
				var dictType = Dialogs.WCFConfigWidget.GetType (dictMapping.TypeName);
				if (dictType != null)
					options.ReferencedCollectionTypes.Add (dictType);
			}

			xsdImporter.Options = options;
			importer.State.Add (typeof (XsdDataContractImporter), xsdImporter);
		}
		void DoCanImport (bool result, params string [] schemaFiles)
		{
			var ccu = new CodeCompileUnit ();
			var xdi = new XsdDataContractImporter (ccu);
			var xss = new XmlSchemaSet ();
			foreach (var schemaFile in schemaFiles)
				xss.Add (null, schemaFile);
			Assert.AreEqual (result, xdi.CanImport (xss));
		}
Exemple #22
0
        public static void GenerateProxyAssembly(string url, string guid, bool fromUi = false)
        {
            TestSuite suite = TestPackage.Suites.Find(s => s.Guid == guid);

            if (suite == null && fromUi)
            {
                suite = new TestSuite()
                {
                    ServiceUrl = url,
                    BaseUrl = url,
                    Wsdl = url + "?wsdl",
                    Guid = guid
                };
                TestPackage.Suites.Add(suite);
                url = suite.Wsdl;
            }

            StreamReader lResponseStream = GetHttpWebResponse(url);

            XmlTextReader xmlreader = new XmlTextReader(lResponseStream);

            //read the downloaded WSDL file
            ServiceDescription desc = ServiceDescription.Read(xmlreader);

            MetadataSection section = MetadataSection.CreateFromServiceDescription(desc);
            MetadataSet metaDocs = new MetadataSet(new[] { section });
            WsdlImporter wsdlimporter = new WsdlImporter(metaDocs);

            //Add any imported files
            foreach (XmlSchema wsdlSchema in desc.Types.Schemas)
            {
                foreach (XmlSchemaObject externalSchema in wsdlSchema.Includes)
                {
                    var import = externalSchema as XmlSchemaImport;
                    if (import != null)
                    {
                        if (suite != null)
                        {
                            Uri baseUri = new Uri(suite.BaseUrl);
                            if (string.IsNullOrEmpty(import.SchemaLocation)) continue;
                            Uri schemaUri = new Uri(baseUri, import.SchemaLocation);
                            StreamReader sr = GetHttpWebResponse(schemaUri.ToString());
                            XmlSchema schema = XmlSchema.Read(sr, null);
                            wsdlimporter.XmlSchemas.Add(schema);
                        }
                    }
                }
            }

            //Additional check in case some services do not generate end points using generator
            for (int w = 0; w < wsdlimporter.WsdlDocuments.Count; w++)
            {
                for (int se = 0; se < wsdlimporter.WsdlDocuments[w].Services.Count; se++)
                {
                    for (int po = 0; po < wsdlimporter.WsdlDocuments[w].Services[se].Ports.Count; po++)
                    {
                        // ReSharper disable once ForCanBeConvertedToForeach
                        for (int ext = 0; ext < wsdlimporter.WsdlDocuments[w].Services[se].Ports[po].Extensions.Count; ext++)
                        {

                            switch (wsdlimporter.WsdlDocuments[w].Services[se].Ports[po].Extensions[ext].GetType().Name)
                            {
                                //BasicHttpBinding
                                case "SoapAddressBinding":
                                    _endPointUrls.Add(((wsdlimporter.WsdlDocuments[w].Services[se].Ports[po])).Binding.Name, ((SoapAddressBinding)(wsdlimporter.WsdlDocuments[w].Services[se].Ports[po].Extensions[ext])).Location);
                                    if (suite != null &&
                                        !suite.EndPoints.ContainsKey(
                                            ((wsdlimporter.WsdlDocuments[w].Services[se].Ports[po])).Binding.Name))
                                    {
                                        suite.EndPoints.Add(
                                            ((wsdlimporter.WsdlDocuments[w].Services[se].Ports[po])).Binding.Name,
                                            ((SoapAddressBinding)
                                                (wsdlimporter.WsdlDocuments[w].Services[se].Ports[po].Extensions[ext]))
                                                .Location);
                                        suite.EndPointType.Add(((wsdlimporter.WsdlDocuments[w].Services[se].Ports[po])).Binding.Name,
                                            "BasicHttpBinding");
                                    }
                                    break;
                                //WSHttpBinding
                                case "Soap12AddressBinding":
                                    _endPointUrls.Add(((wsdlimporter.WsdlDocuments[w].Services[se].Ports[po])).Binding.Name, ((SoapAddressBinding)(wsdlimporter.WsdlDocuments[w].Services[se].Ports[po].Extensions[ext])).Location);
                                    if (suite != null &&
                                        !suite.EndPoints.ContainsKey(
                                            ((wsdlimporter.WsdlDocuments[w].Services[se].Ports[po])).Binding.Name))
                                    {
                                        if (((SoapAddressBinding)
                                            (wsdlimporter.WsdlDocuments[w].Services[se].Ports[po].Extensions[ext]))
                                            .Location.ToLower().StartsWith("net.tcp"))
                                        {
                                            suite.EndPoints.Add(
                                               ((wsdlimporter.WsdlDocuments[w].Services[se].Ports[po])).Binding.Name,
                                               ((SoapAddressBinding)
                                                   (wsdlimporter.WsdlDocuments[w].Services[se].Ports[po].Extensions[ext
                                                       ]))
                                                   .Location);
                                            suite.EndPointType.Add(
                                                ((wsdlimporter.WsdlDocuments[w].Services[se].Ports[po])).Binding.Name,
                                                "NetTcpBinding");
                                        }
                                        else
                                        {
                                            suite.EndPoints.Add(
                                                ((wsdlimporter.WsdlDocuments[w].Services[se].Ports[po])).Binding.Name,
                                                ((SoapAddressBinding)
                                                    (wsdlimporter.WsdlDocuments[w].Services[se].Ports[po].Extensions[ext
                                                        ]))
                                                    .Location);
                                            suite.EndPointType.Add(
                                                ((wsdlimporter.WsdlDocuments[w].Services[se].Ports[po])).Binding.Name,
                                                "WSHttpBinding");
                                        }
                                    }
                                    break;
                                case "XmlElement":
                                    break;
                            }
                        }
                    }
                }
            }

            foreach (Import import in wsdlimporter.WsdlDocuments[0].Imports)
            {
                GenerateProxyAssembly(import.Location, guid);
                return;
            }

            XsdDataContractImporter xsd = new XsdDataContractImporter
            {
                Options = new ImportOptions
                {
                    ImportXmlType = true,
                    GenerateSerializable = true
                }
            };
            xsd.Options.ReferencedTypes.Add(typeof(KeyValuePair<string, string>));
            xsd.Options.ReferencedTypes.Add(typeof(List<KeyValuePair<string, string>>));

            wsdlimporter.State.Add(typeof(XsdDataContractImporter), xsd);

            Collection<ContractDescription> contracts = wsdlimporter.ImportAllContracts();
            ServiceEndpointCollection allEndpoints = wsdlimporter.ImportAllEndpoints();
            // Generate type information for each contract.
            ServiceContractGenerator serviceContractGenerator = new ServiceContractGenerator();

            foreach (var contract in contracts)
            {
                serviceContractGenerator.GenerateServiceContractType(contract);
                // Keep a list of each contract's endpoints.
                if (suite != null)
                {
                    if (suite.EndpointsForContracts == null)
                        suite.EndpointsForContracts = new Dictionary<string, List<EndpointsForContractsClass>>();
                    suite.EndpointsForContracts[contract.Name] =
                        allEndpoints.Where(ep => ep.Contract.Name == contract.Name)
                            .Select(ep => new EndpointsForContractsClass()
                            {
                                Uri = ep.Address.Uri.ToString(),
                                Binding = ep.Binding
                            }).ToList();
                }
            }

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

            //Initialize the CODE DOM tree in which we will import the ServiceDescriptionImporter
            CodeNamespace nm = new CodeNamespace();
            CodeCompileUnit unit = new CodeCompileUnit();
            unit.Namespaces.Add(nm);

            CodeDomProvider compiler = CodeDomProvider.CreateProvider("C#");
            // include the assembly references needed to compile
            var references = new[] { "System.Web.Services.dll", "System.Xml.dll", "System.ServiceModel.dll", "System.configuration.dll", "System.Runtime.Serialization.dll" };
            var parameters = new CompilerParameters(references) { GenerateInMemory = true };
            var results = compiler.CompileAssemblyFromDom(parameters, serviceContractGenerator.TargetCompileUnit);

            if (results.Errors.Cast<CompilerError>().Any())
            {
                throw new Exception("Compilation Error Creating Assembly");
            }

            // all done....
            if (_assembly.ContainsKey(guid))
                _assembly[guid] = results.CompiledAssembly;
            else
                _assembly.Add(guid, results.CompiledAssembly);

            if (_serviceInterface.ContainsKey(guid))
                _serviceInterface[guid] = _assembly[guid].GetTypes()[0];
            else
                _serviceInterface.Add(guid, _assembly[guid].GetTypes()[0]);
        }
 private void AddStateForDataContractSerializerImport(ContractGenerationOptions options,
     WsdlImporter wsdlImporter, CodeCompileUnit codeCompileUnit)
 {
     XsdDataContractImporter xsdImporter = new XsdDataContractImporter(codeCompileUnit);
     xsdImporter.Options = CreateDataContractImportOptions(options);
     wsdlImporter.State.Add(typeof(XsdDataContractImporter), xsdImporter);
 }
        private CodeCompileUnit GenerateTypesWithDataContractImporter(XmlSchemaSet schemas)
		{
			XsdDataContractImporter importer = new XsdDataContractImporter();
			importer.Options = CreateImportOptions(false);

			schemas.ValidationEventHandler += this.validationEventHandler;

			try
			{				
				importer.Import(schemas);
				return importer.CodeCompileUnit;
			}
			catch (InvalidDataContractException dataContractException)
			{
				// double check since CanImport may trigger a "false" positive
				// after adding serialization and types schemas
				importer.CanImport(schemas);
				if (!importer.CanImport(schemas))
				{
					throw new InvalidSerializerException(dataContractException.Message);
				}
				throw;
			}
			catch (ArgumentException argumentException)
			{
				throw new InvalidOperationException(argumentException.Message, argumentException.InnerException);
			}
			finally
			{
				schemas.ValidationEventHandler -= this.validationEventHandler;
			}
		}
        /// <summary>
        /// Create an appropriate XsdDataContractImporter for the generator
        /// </summary>
        /// <param name="proxyOptions">Code/config generation options to use</param>
        /// <param name="targetCompileUnit">CodeCompileUnit into which we will generate the client code</param>
        /// <param name="codeDomProvider">CodeDomProvider for the language we will use to generate the client</param>
        /// <param name="proxyNamespace">CLR namespace in which the client code will be generated</param>
        /// <param name="typeLoader">Service used to resolve type/assembly names (strings) to actual Types and Assemblies</param>
        /// <param name="targetFrameworkVersion">Targetted Framework version number</param>
        /// <param name="importErrors">List of errors encountered. New errors will be added to this list</param>
        /// <returns></returns>
        protected static XsdDataContractImporter CreateDataContractImporter(
                ClientOptions proxyOptions,
                CodeCompileUnit targetCompileUnit,
                System.CodeDom.Compiler.CodeDomProvider codeDomProvider,
                string proxyNamespace,
                IContractGeneratorReferenceTypeLoader typeLoader,
                int targetFrameworkVersion,
                IList<ProxyGenerationError> importErrors)
        {
            System.Runtime.Serialization.XsdDataContractImporter xsdDataContractImporter = new System.Runtime.Serialization.XsdDataContractImporter(targetCompileUnit);
            System.Runtime.Serialization.ImportOptions options = new System.Runtime.Serialization.ImportOptions();

            options.CodeProvider = codeDomProvider;

            // We specify that we want to generate all types from all XML namespaces into
            // our proxy namespace. By default, each XML namespace get's its own CLR namespace
            options.Namespaces.Add("*", proxyNamespace);
            options.GenerateInternal = proxyOptions.GenerateInternalTypes;
            options.GenerateSerializable = proxyOptions.GenerateSerializableTypes;
            options.EnableDataBinding = proxyOptions.EnableDataBinding;
            options.ImportXmlType = proxyOptions.ImportXmlTypes;

            if (typeLoader != null)
            {
                IEnumerable<Type> referencedTypes = LoadSharedDataContractTypes(proxyOptions, typeLoader, targetFrameworkVersion, importErrors);
                if (referencedTypes != null)
                {
                    foreach (Type sharedType in referencedTypes)
                    {
                        options.ReferencedTypes.Add(sharedType);
                    }
                }

                IEnumerable<Type> referencedCollectionTypes = LoadSharedCollectionTypes(proxyOptions, typeLoader, importErrors);
                if (referencedCollectionTypes != null)
                {
                    foreach (Type collectionType in referencedCollectionTypes)
                    {
                        options.ReferencedCollectionTypes.Add(collectionType);
                    }
                }

            }

            foreach (NamespaceMapping namespaceMapping in proxyOptions.NamespaceMappingList)
            {
                options.Namespaces.Add(namespaceMapping.TargetNamespace, namespaceMapping.ClrNamespace);
            }

            xsdDataContractImporter.Options = options;

            return xsdDataContractImporter;
        }
		private void ExportDataContract (MessagePartDescription md)
		{
			if (xsd_data_importer == null)
				xsd_data_importer = md.Importer;
		}